2 * This code is Copyright (c) 2014, by the authors of nmh. See the
3 * COPYRIGHT file in the root directory of the nmh distribution for
4 * complete copyright information.
21 #include <curl/curl.h>
22 #include <thirdparty/jsmn/jsmn.h>
27 #define JSON_TYPE "application/json"
29 /* We pretend access tokens expire 60 seconds earlier than they actually do to
30 * allow for separate processes to use and refresh access tokens. The process
31 * that uses the access token (post) has an error if the token is expired; the
32 * process that refreshes the access token (send) must have already refreshed if
33 * the expiration is close.
35 * 60s is arbitrary, and hopefully is enough to allow for clock skew.
36 * Currently only Gmail supports XOAUTH2, and seems to always use a token
37 * life-time of 3600s, but that is not guaranteed. It is possible for Gmail to
38 * issue an access token with a life-time so short that even after send
39 * refreshes it, it's already expired when post tries to use it, but that seems
41 #define EXPIRY_FUDGE 60
43 /* maximum size for HTTP response bodies
44 * (not counting header and not null-terminated) */
45 #define RESPONSE_BODY_MAX 8192
47 /* Maximum size for URLs and URI-encoded query strings, null-terminated.
49 * Actual maximum we need is based on the size of tokens (limited by
50 * RESPONSE_BODY_MAX), code user copies from a web page (arbitrarily large), and
51 * various service parameters (all arbitrarily large). In practice, all these
52 * are just tens of bytes. It's not hard to change this to realloc as needed,
53 * but we should still have some limit, so why not this one?
57 struct mh_oauth_cred
{
60 /* opaque access token ([1] 1.4) in null-terminated string */
62 /* opaque refresh token ([1] 1.5) in null-terminated string */
65 /* time at which the access token expires, or 0 if unknown */
68 /* Ignoring token_type ([1] 7.1) because
69 * https://developers.google.com/accounts/docs/OAuth2InstalledApp says
70 * "Currently, this field always has the value Bearer". */
72 /* only filled while loading cred files, otherwise NULL */
77 struct mh_oauth_service_info svc
;
84 char *sasl_client_res
;
87 mh_oauth_err_code err_code
;
89 /* If any detailed message about the error is available, this points to it.
90 * May point to err_buf, or something else. */
91 const char *err_details
;
93 /* Pointer to buffer mh_oauth_err_get_string allocates. */
96 /* Ask libcurl to store errors here. */
97 char err_buf
[CURL_ERROR_SIZE
];
104 /* NULL or a file handle to have curl log diagnostics to */
109 /* Whether the response was too big; if so, the rest of the output fields
113 /* HTTP response code */
116 /* NULL or null-terminated value of Content-Type response header field */
117 const char *content_type
;
119 /* number of bytes in the response body */
122 /* response body; NOT null-terminated */
123 char res_body
[RESPONSE_BODY_MAX
];
126 static boolean
get_json_strings(const char *, size_t, FILE *, ...);
127 static boolean
make_query_url(char *, size_t, CURL
*, const char *, ...);
128 static boolean
post(struct curl_ctx
*, const char *, const char *);
131 mh_oauth_do_xoauth(const char *user
, const char *svc
, unsigned char **oauth_res
,
132 size_t *oauth_res_len
, FILE *log
)
137 int failed_to_lock
= 0;
141 if (!mh_oauth_new (&ctx
, svc
)) adios(NULL
, mh_oauth_get_err_string(ctx
));
143 if (log
!= NULL
) mh_oauth_log_to(stderr
, ctx
);
145 fn
= getcpy(mh_oauth_cred_fn(svc
));
146 fp
= lkfopendata(fn
, "r+", &failed_to_lock
);
148 if (errno
== ENOENT
) {
149 adios(NULL
, "no credentials -- run mhlogin -saslmech xoauth2 -authservice %s", svc
);
151 adios(fn
, "failed to open");
153 if (failed_to_lock
) {
154 adios(fn
, "failed to lock");
157 if ((cred
= mh_oauth_cred_load(fp
, ctx
, user
)) == NULL
) {
158 adios(NULL
, mh_oauth_get_err_string(ctx
));
161 if (!mh_oauth_access_token_valid(time(NULL
), cred
)) {
162 if (!mh_oauth_refresh(cred
)) {
163 if (mh_oauth_get_err_code(ctx
) == MH_OAUTH_NO_REFRESH
) {
164 adios(NULL
, "no valid credentials -- run mhlogin -saslmech xoauth2 -authservice %s", svc
);
166 if (mh_oauth_get_err_code(ctx
) == MH_OAUTH_BAD_GRANT
) {
167 adios(NULL
, "credentials rejected -- run mhlogin -saslmech xoauth2 -authservice %s", svc
);
169 advise(NULL
, "error refreshing OAuth2 token");
170 adios(NULL
, mh_oauth_get_err_string(ctx
));
173 fseek(fp
, 0, SEEK_SET
);
174 if (!mh_oauth_cred_save(fp
, cred
, user
)) {
175 adios(NULL
, mh_oauth_get_err_string(ctx
));
179 if (lkfclosedata(fp
, fn
) < 0) {
180 adios(fn
, "failed to close");
184 /* XXX writeBase64raw modifies the source buffer! make a copy */
185 client_res
= getcpy(mh_oauth_sasl_client_response(oauth_res_len
, user
,
187 mh_oauth_cred_free(cred
);
190 *oauth_res
= (unsigned char *) client_res
;
196 is_json(const char *content_type
)
198 return content_type
!= NULL
199 && strncasecmp(content_type
, JSON_TYPE
, sizeof JSON_TYPE
- 1) == 0;
203 set_err_details(mh_oauth_ctx
*ctx
, mh_oauth_err_code code
, const char *details
)
205 ctx
->err_code
= code
;
206 ctx
->err_details
= details
;
210 set_err(mh_oauth_ctx
*ctx
, mh_oauth_err_code code
)
212 set_err_details(ctx
, code
, NULL
);
216 set_err_http(mh_oauth_ctx
*ctx
, const struct curl_ctx
*curl_ctx
)
219 mh_oauth_err_code code
;
220 /* 5.2. Error Response says error response should use status code 400 and
221 * application/json body. If Content-Type matches, try to parse the body
222 * regardless of the status code. */
223 if (curl_ctx
->res_len
> 0
224 && is_json(curl_ctx
->content_type
)
225 && get_json_strings(curl_ctx
->res_body
, curl_ctx
->res_len
, ctx
->log
,
226 "error", &error
, (void *)NULL
)
228 if (strcmp(error
, "invalid_grant") == 0) {
229 code
= MH_OAUTH_BAD_GRANT
;
231 /* All other errors indicate a bug, not anything the user did. */
232 code
= MH_OAUTH_REQUEST_BAD
;
235 code
= MH_OAUTH_RESPONSE_BAD
;
244 const char *curl
= curl_version_info(CURLVERSION_NOW
)->version
;
245 char *s
= mh_xmalloc(strlen(user_agent
)
251 sprintf(s
, "%s libcurl/%s", user_agent
, curl
);
256 mh_oauth_new(mh_oauth_ctx
**result
, const char *svc_name
)
258 mh_oauth_ctx
*ctx
= *result
= mh_xmalloc(sizeof *ctx
);
263 ctx
->cred_fn
= ctx
->sasl_client_res
= ctx
->err_formatted
= NULL
;
265 if (!mh_oauth_get_service_info(svc_name
, &ctx
->svc
, ctx
->err_buf
,
266 sizeof(ctx
->err_buf
))) {
267 set_err_details(ctx
, MH_OAUTH_BAD_PROFILE
, ctx
->err_buf
);
271 ctx
->curl
= curl_easy_init();
272 if (ctx
->curl
== NULL
) {
273 set_err(ctx
, MH_OAUTH_CURL_INIT
);
276 curl_easy_setopt(ctx
->curl
, CURLOPT_ERRORBUFFER
, ctx
->err_buf
);
278 ctx
->user_agent
= make_user_agent();
280 if (curl_easy_setopt(ctx
->curl
, CURLOPT_USERAGENT
,
281 ctx
->user_agent
) != CURLE_OK
) {
282 set_err_details(ctx
, MH_OAUTH_CURL_INIT
, ctx
->err_buf
);
290 mh_oauth_free(mh_oauth_ctx
*ctx
)
293 free(ctx
->svc
.scope
);
294 free(ctx
->svc
.client_id
);
295 free(ctx
->svc
.client_secret
);
296 free(ctx
->svc
.auth_endpoint
);
297 free(ctx
->svc
.token_endpoint
);
298 free(ctx
->svc
.redirect_uri
);
300 free(ctx
->sasl_client_res
);
301 free(ctx
->err_formatted
);
302 free(ctx
->user_agent
);
304 if (ctx
->curl
!= NULL
) {
305 curl_easy_cleanup(ctx
->curl
);
311 mh_oauth_svc_display_name(const mh_oauth_ctx
*ctx
)
313 return ctx
->svc
.display_name
;
317 mh_oauth_log_to(FILE *log
, mh_oauth_ctx
*ctx
)
323 mh_oauth_get_err_code(const mh_oauth_ctx
*ctx
)
325 return ctx
->err_code
;
329 mh_oauth_get_err_string(mh_oauth_ctx
*ctx
)
334 free(ctx
->err_formatted
);
336 switch (ctx
->err_code
) {
337 case MH_OAUTH_BAD_PROFILE
:
338 base
= "incomplete OAuth2 service definition";
340 case MH_OAUTH_CURL_INIT
:
341 base
= "error initializing libcurl";
343 case MH_OAUTH_REQUEST_INIT
:
344 base
= "local error initializing HTTP request";
347 base
= "error making HTTP request to OAuth2 authorization endpoint";
349 case MH_OAUTH_RESPONSE_TOO_BIG
:
350 base
= "refusing to process response body larger than 8192 bytes";
352 case MH_OAUTH_RESPONSE_BAD
:
353 base
= "invalid response";
355 case MH_OAUTH_BAD_GRANT
:
356 base
= "bad grant (authorization code or refresh token)";
358 case MH_OAUTH_REQUEST_BAD
:
359 base
= "bad OAuth request; re-run with -snoop and send REDACTED output"
362 case MH_OAUTH_NO_REFRESH
:
363 base
= "no refresh token";
365 case MH_OAUTH_CRED_USER_NOT_FOUND
:
366 base
= "user not found in cred file";
368 case MH_OAUTH_CRED_FILE
:
369 base
= "error loading cred file";
372 base
= "unknown error";
374 if (ctx
->err_details
== NULL
) {
375 return ctx
->err_formatted
= getcpy(base
);
377 /* length of the two strings plus ": " and '\0' */
378 result
= mh_xmalloc(strlen(base
) + strlen(ctx
->err_details
) + 3);
379 sprintf(result
, "%s: %s", base
, ctx
->err_details
);
380 return ctx
->err_formatted
= result
;
384 mh_oauth_get_authorize_url(mh_oauth_ctx
*ctx
)
386 /* [1] 4.1.1 Authorization Request */
387 if (!make_query_url(ctx
->buf
, sizeof ctx
->buf
, ctx
->curl
,
388 ctx
->svc
.auth_endpoint
,
389 "response_type", "code",
390 "client_id", ctx
->svc
.client_id
,
391 "redirect_uri", ctx
->svc
.redirect_uri
,
392 "scope", ctx
->svc
.scope
,
394 set_err(ctx
, MH_OAUTH_REQUEST_INIT
);
401 cred_from_response(mh_oauth_cred
*cred
, const char *content_type
,
402 const char *input
, size_t input_len
)
404 boolean result
= FALSE
;
405 char *access_token
, *expires_in
, *refresh_token
;
406 const mh_oauth_ctx
*ctx
= cred
->ctx
;
408 if (!is_json(content_type
)) {
412 access_token
= expires_in
= refresh_token
= NULL
;
413 if (!get_json_strings(input
, input_len
, ctx
->log
,
414 "access_token", &access_token
,
415 "expires_in", &expires_in
,
416 "refresh_token", &refresh_token
,
421 if (access_token
== NULL
) {
422 /* Response is invalid, but if it has a refresh token, we can try. */
423 if (refresh_token
== NULL
) {
430 free(cred
->access_token
);
431 cred
->access_token
= access_token
;
434 cred
->expires_at
= 0;
435 if (expires_in
!= NULL
) {
438 e
= strtol(expires_in
, NULL
, 10);
441 cred
->expires_at
= time(NULL
) + e
;
443 } else if (ctx
->log
!= NULL
) {
444 fprintf(ctx
->log
, "* invalid expiration: %s\n", expires_in
);
448 /* [1] 6 Refreshing an Access Token says a new refresh token may be issued
449 * in refresh responses. */
450 if (refresh_token
!= NULL
) {
451 free(cred
->refresh_token
);
452 cred
->refresh_token
= refresh_token
;
453 refresh_token
= NULL
;
464 do_access_request(mh_oauth_cred
*cred
, const char *req_body
)
466 mh_oauth_ctx
*ctx
= cred
->ctx
;
467 struct curl_ctx curl_ctx
;
469 curl_ctx
.curl
= ctx
->curl
;
470 curl_ctx
.log
= ctx
->log
;
471 if (!post(&curl_ctx
, ctx
->svc
.token_endpoint
, req_body
)) {
472 if (curl_ctx
.too_big
) {
473 set_err(ctx
, MH_OAUTH_RESPONSE_TOO_BIG
);
475 set_err_details(ctx
, MH_OAUTH_POST
, ctx
->err_buf
);
480 if (curl_ctx
.res_code
!= 200) {
481 set_err_http(ctx
, &curl_ctx
);
485 if (!cred_from_response(cred
, curl_ctx
.content_type
, curl_ctx
.res_body
,
487 set_err(ctx
, MH_OAUTH_RESPONSE_BAD
);
495 mh_oauth_authorize(const char *code
, mh_oauth_ctx
*ctx
)
497 mh_oauth_cred
*result
;
499 if (!make_query_url(ctx
->buf
, sizeof ctx
->buf
, ctx
->curl
, NULL
,
501 "grant_type", "authorization_code",
502 "redirect_uri", ctx
->svc
.redirect_uri
,
503 "client_id", ctx
->svc
.client_id
,
504 "client_secret", ctx
->svc
.client_secret
,
506 set_err(ctx
, MH_OAUTH_REQUEST_INIT
);
510 result
= mh_xmalloc(sizeof *result
);
512 result
->access_token
= result
->refresh_token
= NULL
;
514 if (!do_access_request(result
, ctx
->buf
)) {
523 mh_oauth_refresh(mh_oauth_cred
*cred
)
526 mh_oauth_ctx
*ctx
= cred
->ctx
;
528 if (cred
->refresh_token
== NULL
) {
529 set_err(ctx
, MH_OAUTH_NO_REFRESH
);
533 if (!make_query_url(ctx
->buf
, sizeof ctx
->buf
, ctx
->curl
, NULL
,
534 "grant_type", "refresh_token",
535 "refresh_token", cred
->refresh_token
,
536 "client_id", ctx
->svc
.client_id
,
537 "client_secret", ctx
->svc
.client_secret
,
539 set_err(ctx
, MH_OAUTH_REQUEST_INIT
);
543 result
= do_access_request(cred
, ctx
->buf
);
545 if (result
&& cred
->access_token
== NULL
) {
546 set_err_details(ctx
, MH_OAUTH_RESPONSE_BAD
, "no access token");
554 mh_oauth_access_token_valid(time_t t
, const mh_oauth_cred
*cred
)
556 return cred
->access_token
!= NULL
&& t
+ EXPIRY_FUDGE
< cred
->expires_at
;
560 mh_oauth_cred_free(mh_oauth_cred
*cred
)
562 free(cred
->refresh_token
);
563 free(cred
->access_token
);
567 /* for loading multi-user cred files */
569 mh_oauth_cred
*creds
;
571 /* number of allocated mh_oauth_cred structs above points to */
574 /* number that are actually filled in and used */
578 /* If user has an entry in user_creds, return pointer to it. Else allocate a
579 * new struct in user_creds and return pointer to that. */
580 static mh_oauth_cred
*
581 find_or_alloc_user_creds(struct user_creds user_creds
[], const char *user
)
583 mh_oauth_cred
*creds
= user_creds
->creds
;
585 for (i
= 0; i
< user_creds
->len
; i
++) {
586 if (strcmp(creds
[i
].user
, user
) == 0) {
590 if (user_creds
->alloc
== user_creds
->len
) {
591 user_creds
->alloc
*= 2;
592 user_creds
->creds
= mh_xrealloc(user_creds
->creds
, user_creds
->alloc
);
594 creds
= user_creds
->creds
+user_creds
->len
;
596 creds
->user
= getcpy(user
);
597 creds
->access_token
= creds
->refresh_token
= NULL
;
598 creds
->expires_at
= 0;
603 free_user_creds(struct user_creds
*user_creds
)
607 cred
= user_creds
->creds
;
608 for (i
= 0; i
< user_creds
->len
; i
++) {
610 free(cred
[i
].access_token
);
611 free(cred
[i
].refresh_token
);
613 free(user_creds
->creds
);
618 load_creds(struct user_creds
**result
, FILE *fp
, mh_oauth_ctx
*ctx
)
620 boolean success
= FALSE
;
621 char name
[NAMESZ
], value_buf
[BUFSIZ
];
623 m_getfld_state_t getfld_ctx
= 0;
625 struct user_creds
*user_creds
= mh_xmalloc(sizeof *user_creds
);
626 user_creds
->alloc
= 4;
628 user_creds
->creds
= mh_xmalloc(user_creds
->alloc
* sizeof *user_creds
->creds
);
631 int size
= sizeof value_buf
;
632 switch (state
= m_getfld(&getfld_ctx
, name
, value_buf
, &size
, fp
)) {
635 char **save
, *expire
;
636 time_t *expires_at
= NULL
;
637 if (strncmp(name
, "access-", 7) == 0) {
638 const char *user
= name
+ 7;
639 mh_oauth_cred
*creds
= find_or_alloc_user_creds(user_creds
,
641 save
= &creds
->access_token
;
642 } else if (strncmp(name
, "refresh-", 8) == 0) {
643 const char *user
= name
+ 8;
644 mh_oauth_cred
*creds
= find_or_alloc_user_creds(user_creds
,
646 save
= &creds
->refresh_token
;
647 } else if (strncmp(name
, "expire-", 7) == 0) {
648 const char *user
= name
+ 7;
649 mh_oauth_cred
*creds
= find_or_alloc_user_creds(user_creds
,
651 expires_at
= &creds
->expires_at
;
654 set_err_details(ctx
, MH_OAUTH_CRED_FILE
, "unexpected field");
659 *save
= trimcpy(value_buf
);
661 char *tmp
= getcpy(value_buf
);
662 while (state
== FLDPLUS
) {
663 size
= sizeof value_buf
;
664 state
= m_getfld(&getfld_ctx
, name
, value_buf
, &size
, fp
);
665 tmp
= add(value_buf
, tmp
);
667 *save
= trimcpy(tmp
);
670 if (expires_at
!= NULL
) {
672 *expires_at
= strtol(expire
, NULL
, 10);
675 set_err_details(ctx
, MH_OAUTH_CRED_FILE
,
676 "invalid expiration time");
690 /* Not adding details for LENERR/FMTERR because m_getfld already
691 * wrote advise message to stderr. */
692 set_err(ctx
, MH_OAUTH_CRED_FILE
);
697 m_getfld_state_destroy(&getfld_ctx
);
700 *result
= user_creds
;
702 free_user_creds(user_creds
);
709 save_user(FILE *fp
, const char *user
, const char *access
, const char *refresh
,
712 if (access
!= NULL
) {
713 if (fprintf(fp
, "access-%s: %s\n", user
, access
) < 0) return FALSE
;
715 if (refresh
!= NULL
) {
716 if (fprintf(fp
, "refresh-%s: %s\n", user
, refresh
) < 0) return FALSE
;
718 if (expires_at
> 0) {
719 if (fprintf(fp
, "expire-%s: %ld\n", user
, (long)expires_at
) < 0) {
727 mh_oauth_cred_save(FILE *fp
, mh_oauth_cred
*cred
, const char *user
)
729 struct user_creds
*user_creds
;
733 /* Load existing creds if any. */
734 if (!load_creds(&user_creds
, fp
, cred
->ctx
)) {
738 if (fchmod(fd
, S_IRUSR
| S_IWUSR
) < 0) goto err
;
739 if (ftruncate(fd
, 0) < 0) goto err
;
740 if (fseek(fp
, 0, SEEK_SET
) < 0) goto err
;
742 /* Write all creds except for this user. */
743 for (i
= 0; i
< user_creds
->len
; i
++) {
744 mh_oauth_cred
*c
= &user_creds
->creds
[i
];
745 if (strcmp(c
->user
, user
) == 0) continue;
746 if (!save_user(fp
, c
->user
, c
->access_token
, c
->refresh_token
,
752 /* Write updated creds for this user. */
753 if (!save_user(fp
, user
, cred
->access_token
, cred
->refresh_token
,
758 free_user_creds(user_creds
);
763 free_user_creds(user_creds
);
764 set_err(cred
->ctx
, MH_OAUTH_CRED_FILE
);
769 mh_oauth_cred_load(FILE *fp
, mh_oauth_ctx
*ctx
, const char *user
)
771 mh_oauth_cred
*creds
, *result
= NULL
;
772 struct user_creds
*user_creds
;
775 if (!load_creds(&user_creds
, fp
, ctx
)) {
779 /* Search user_creds for this user. If we don't find it, return NULL.
780 * If we do, free fields of all structs except this one, moving this one to
781 * the first struct if necessary. When we return it, it just looks like one
782 * struct to the caller, and the whole array is freed later. */
783 creds
= user_creds
->creds
;
784 for (i
= 0; i
< user_creds
->len
; i
++) {
785 if (strcmp(creds
[i
].user
, user
) == 0) {
788 result
->access_token
= creds
[i
].access_token
;
789 result
->refresh_token
= creds
[i
].refresh_token
;
790 result
->expires_at
= creds
[i
].expires_at
;
793 free(creds
[i
].access_token
);
794 free(creds
[i
].refresh_token
);
799 /* No longer need user_creds. result just uses its creds member. */
802 if (result
== NULL
) {
803 set_err_details(ctx
, MH_OAUTH_CRED_USER_NOT_FOUND
, user
);
814 mh_oauth_sasl_client_response(size_t *res_len
,
815 const char *user
, const mh_oauth_cred
*cred
)
817 size_t len
= sizeof "user=" - 1
819 + sizeof "\1auth=Bearer " - 1
820 + strlen(cred
->access_token
)
822 free(cred
->ctx
->sasl_client_res
);
823 cred
->ctx
->sasl_client_res
= mh_xmalloc(len
+ 1);
825 sprintf(cred
->ctx
->sasl_client_res
, "user=%s\1auth=Bearer %s\1\1",
826 user
, cred
->access_token
);
827 return cred
->ctx
->sasl_client_res
;
830 /*******************************************************************************
831 * building URLs and making HTTP requests with libcurl
835 * Build null-terminated URL in the array pointed to by s. If the URL doesn't
836 * fit within size (including the terminating null byte), return FALSE without *
837 * building the entire URL. Some of URL may already have been written into the
838 * result array in that case.
841 make_query_url(char *s
, size_t size
, CURL
*curl
, const char *base_url
, ...)
843 boolean result
= FALSE
;
849 if (base_url
== NULL
) {
853 len
= sprintf(s
, "%s", base_url
);
857 va_start(ap
, base_url
);
858 for (name
= va_arg(ap
, char *); name
!= NULL
; name
= va_arg(ap
, char *)) {
859 char *name_esc
= curl_easy_escape(curl
, name
, 0);
860 char *val_esc
= curl_easy_escape(curl
, va_arg(ap
, char *), 0);
861 /* prefix + name_esc + '=' + val_esc + '\0' must fit within size */
867 if (new_len
+ 1 > size
) {
872 sprintf(s
+ len
, "%s%s=%s", prefix
, name_esc
, val_esc
);
887 debug_callback(const CURL
*handle
, curl_infotype type
, const char *data
,
888 size_t size
, void *userptr
)
894 case CURLINFO_HEADER_IN
:
895 case CURLINFO_DATA_IN
:
898 case CURLINFO_HEADER_OUT
:
899 case CURLINFO_DATA_OUT
:
905 fwrite(data
, 1, size
, fp
);
906 if (data
[size
- 1] != '\n') {
914 write_callback(const char *ptr
, size_t size
, size_t nmemb
, void *userdata
)
916 struct curl_ctx
*ctx
= userdata
;
924 new_len
= ctx
->res_len
+ size
;
925 if (new_len
> sizeof ctx
->res_body
) {
930 memcpy(ctx
->res_body
+ ctx
->res_len
, ptr
, size
);
931 ctx
->res_len
= new_len
;
937 post(struct curl_ctx
*ctx
, const char *url
, const char *req_body
)
939 CURL
*curl
= ctx
->curl
;
942 ctx
->too_big
= FALSE
;
945 if (ctx
->log
!= NULL
) {
946 curl_easy_setopt(curl
, CURLOPT_VERBOSE
, (long)1);
947 curl_easy_setopt(curl
, CURLOPT_DEBUGFUNCTION
, debug_callback
);
948 curl_easy_setopt(curl
, CURLOPT_DEBUGDATA
, ctx
->log
);
951 if ((status
= curl_easy_setopt(curl
, CURLOPT_URL
, url
)) != CURLE_OK
) {
955 curl_easy_setopt(curl
, CURLOPT_POSTFIELDS
, req_body
);
956 curl_easy_setopt(curl
, CURLOPT_WRITEFUNCTION
, write_callback
);
957 curl_easy_setopt(curl
, CURLOPT_WRITEDATA
, ctx
);
959 if (strncmp(url
, "http://127.0.0.1:", 17) == 0) {
960 /* Hack: on Cygwin, curl doesn't fail to connect with ECONNREFUSED.
961 Instead, it waits to timeout. So set a really short timeout, but
962 just on localhost (for convenience of the user, and the test
964 curl_easy_setopt(curl
, CURLOPT_CONNECTTIMEOUT
, 2L);
967 status
= curl_easy_perform(curl
);
968 /* first check for error from callback */
973 if (status
!= CURLE_OK
) {
977 if ((status
= curl_easy_getinfo(curl
, CURLINFO_RESPONSE_CODE
,
978 &ctx
->res_code
)) != CURLE_OK
979 || (status
= curl_easy_getinfo(curl
, CURLINFO_CONTENT_TYPE
,
980 &ctx
->content_type
)) != CURLE_OK
) {
987 /*******************************************************************************
991 /* We need 2 for each key/value pair plus 1 for the enclosing object, which
992 * means we only need 9 for Gmail. Clients must not fail if the server returns
993 * more, though, e.g. for protocol extensions. */
994 #define JSMN_TOKENS 16
997 * Parse JSON, store pointer to array of jsmntok_t in tokens.
999 * Returns whether parsing is successful.
1001 * Even in that case, tokens has been allocated and must be freed.
1004 parse_json(jsmntok_t
**tokens
, size_t *tokens_len
,
1005 const char *input
, size_t input_len
, FILE *log
)
1010 *tokens_len
= JSMN_TOKENS
;
1011 *tokens
= mh_xmalloc(*tokens_len
* sizeof **tokens
);
1014 while ((r
= jsmn_parse(&p
, input
, input_len
,
1015 *tokens
, *tokens_len
)) == JSMN_ERROR_NOMEM
) {
1016 *tokens_len
= 2 * *tokens_len
;
1018 fprintf(log
, "* need more jsmntok_t! allocating %ld\n",
1021 /* Don't need to limit how much we allocate; we already limited the size
1022 of the response body. */
1023 *tokens
= mh_xrealloc(*tokens
, *tokens_len
* sizeof **tokens
);
1033 * Search input and tokens for the value identified by null-terminated name.
1035 * If found, allocate a null-terminated copy of the value and store the address
1036 * in val. val is left untouched if not found.
1039 get_json_string(char **val
, const char *input
, const jsmntok_t
*tokens
,
1042 /* number of top-level tokens (not counting object/list children) */
1043 int token_count
= tokens
[0].size
* 2;
1044 /* number of tokens to skip when we encounter objects and lists */
1045 /* We only look for top-level strings. */
1046 int skip_tokens
= 0;
1047 /* whether the current token represents a field name */
1048 /* The next token will be the value. */
1049 boolean is_key
= TRUE
;
1052 for (i
= 1; i
<= token_count
; i
++) {
1055 if (tokens
[i
].type
== JSMN_ARRAY
|| tokens
[i
].type
== JSMN_OBJECT
) {
1056 /* We're not interested in any array or object children; skip. */
1057 int children
= tokens
[i
].size
;
1058 if (tokens
[i
].type
== JSMN_OBJECT
) {
1059 /* Object size counts key/value pairs, skip both. */
1062 /* Add children to token_count. */
1063 token_count
+= children
;
1064 if (skip_tokens
== 0) {
1065 /* This token not already skipped; skip it. */
1066 /* Would already be skipped if child of object or list. */
1069 /* Skip this token's children. */
1070 skip_tokens
+= children
;
1072 if (skip_tokens
> 0) {
1074 /* When we finish with the object or list, we'll have a key. */
1082 key
= input
+ tokens
[i
- 1].start
;
1083 key_len
= tokens
[i
- 1].end
- tokens
[i
- 1].start
;
1084 if (strncmp(key
, name
, key_len
) == 0) {
1085 int val_len
= tokens
[i
].end
- tokens
[i
].start
;
1086 *val
= mh_xmalloc(val_len
+ 1);
1087 memcpy(*val
, input
+ tokens
[i
].start
, val_len
);
1088 (*val
)[val_len
] = '\0';
1096 * Parse input as JSON, extracting specified string values.
1098 * Variadic arguments are pairs of null-terminated strings indicating the value
1099 * to extract from the JSON and addresses into which pointers to null-terminated
1100 * copies of the values are written. These must be followed by one NULL pointer
1101 * to indicate the end of pairs.
1103 * The extracted strings are copies which caller must free. If any name is not
1104 * found, the address to store the value is not touched.
1106 * Returns non-zero if parsing is successful.
1108 * When parsing failed, no strings have been copied.
1110 * log may be used for debug-logging if not NULL.
1113 get_json_strings(const char *input
, size_t input_len
, FILE *log
, ...)
1115 boolean result
= FALSE
;
1121 if (!parse_json(&tokens
, &tokens_len
, input
, input_len
, log
)) {
1125 if (tokens
->type
!= JSMN_OBJECT
|| tokens
->size
== 0) {
1132 for (name
= va_arg(ap
, char *); name
!= NULL
; name
= va_arg(ap
, char *)) {
1133 get_json_string(va_arg(ap
, char **), input
, tokens
, name
);