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
= mh_xstrdup(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
= mh_xstrdup(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
, LEN(JSON_TYPE
)) == 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 return concat(user_agent
, " libcurl/", curl
, NULL
);
249 mh_oauth_new(mh_oauth_ctx
**result
, const char *svc_name
)
258 ctx
->cred_fn
= ctx
->sasl_client_res
= ctx
->err_formatted
= NULL
;
260 if (!mh_oauth_get_service_info(svc_name
, &ctx
->svc
, ctx
->err_buf
,
261 sizeof(ctx
->err_buf
))) {
262 set_err_details(ctx
, MH_OAUTH_BAD_PROFILE
, ctx
->err_buf
);
266 ctx
->curl
= curl_easy_init();
267 if (ctx
->curl
== NULL
) {
268 set_err(ctx
, MH_OAUTH_CURL_INIT
);
271 curl_easy_setopt(ctx
->curl
, CURLOPT_ERRORBUFFER
, ctx
->err_buf
);
273 ctx
->user_agent
= make_user_agent();
275 if (curl_easy_setopt(ctx
->curl
, CURLOPT_USERAGENT
,
276 ctx
->user_agent
) != CURLE_OK
) {
277 set_err_details(ctx
, MH_OAUTH_CURL_INIT
, ctx
->err_buf
);
285 mh_oauth_free(mh_oauth_ctx
*ctx
)
288 free(ctx
->svc
.scope
);
289 free(ctx
->svc
.client_id
);
290 free(ctx
->svc
.client_secret
);
291 free(ctx
->svc
.auth_endpoint
);
292 free(ctx
->svc
.token_endpoint
);
293 free(ctx
->svc
.redirect_uri
);
295 free(ctx
->sasl_client_res
);
296 free(ctx
->err_formatted
);
297 free(ctx
->user_agent
);
299 if (ctx
->curl
!= NULL
) {
300 curl_easy_cleanup(ctx
->curl
);
306 mh_oauth_svc_display_name(const mh_oauth_ctx
*ctx
)
308 return ctx
->svc
.display_name
;
312 mh_oauth_log_to(FILE *log
, mh_oauth_ctx
*ctx
)
318 mh_oauth_get_err_code(const mh_oauth_ctx
*ctx
)
320 return ctx
->err_code
;
324 mh_oauth_get_err_string(mh_oauth_ctx
*ctx
)
328 free(ctx
->err_formatted
);
330 switch (ctx
->err_code
) {
331 case MH_OAUTH_BAD_PROFILE
:
332 base
= "incomplete OAuth2 service definition";
334 case MH_OAUTH_CURL_INIT
:
335 base
= "error initializing libcurl";
337 case MH_OAUTH_REQUEST_INIT
:
338 base
= "local error initializing HTTP request";
341 base
= "error making HTTP request to OAuth2 authorization endpoint";
343 case MH_OAUTH_RESPONSE_TOO_BIG
:
344 base
= "refusing to process response body larger than 8192 bytes";
346 case MH_OAUTH_RESPONSE_BAD
:
347 base
= "invalid response";
349 case MH_OAUTH_BAD_GRANT
:
350 base
= "bad grant (authorization code or refresh token)";
352 case MH_OAUTH_REQUEST_BAD
:
353 base
= "bad OAuth request; re-run with -snoop and send REDACTED output"
356 case MH_OAUTH_NO_REFRESH
:
357 base
= "no refresh token";
359 case MH_OAUTH_CRED_USER_NOT_FOUND
:
360 base
= "user not found in cred file";
362 case MH_OAUTH_CRED_FILE
:
363 base
= "error loading cred file";
366 base
= "unknown error";
368 if (ctx
->err_details
== NULL
) {
369 return ctx
->err_formatted
= mh_xstrdup(base
);
372 ctx
->err_formatted
= concat(base
, ": ", ctx
->err_details
, NULL
);
373 return ctx
->err_formatted
;
377 mh_oauth_get_authorize_url(mh_oauth_ctx
*ctx
)
379 /* [1] 4.1.1 Authorization Request */
380 if (!make_query_url(ctx
->buf
, sizeof ctx
->buf
, ctx
->curl
,
381 ctx
->svc
.auth_endpoint
,
382 "response_type", "code",
383 "client_id", ctx
->svc
.client_id
,
384 "redirect_uri", ctx
->svc
.redirect_uri
,
385 "scope", ctx
->svc
.scope
,
387 set_err(ctx
, MH_OAUTH_REQUEST_INIT
);
394 cred_from_response(mh_oauth_cred
*cred
, const char *content_type
,
395 const char *input
, size_t input_len
)
397 boolean result
= FALSE
;
398 char *access_token
, *expires_in
, *refresh_token
;
399 const mh_oauth_ctx
*ctx
= cred
->ctx
;
401 if (!is_json(content_type
)) {
405 access_token
= expires_in
= refresh_token
= NULL
;
406 if (!get_json_strings(input
, input_len
, ctx
->log
,
407 "access_token", &access_token
,
408 "expires_in", &expires_in
,
409 "refresh_token", &refresh_token
,
414 if (access_token
== NULL
) {
415 /* Response is invalid, but if it has a refresh token, we can try. */
416 if (refresh_token
== NULL
) {
423 free(cred
->access_token
);
424 cred
->access_token
= access_token
;
427 cred
->expires_at
= 0;
428 if (expires_in
!= NULL
) {
431 e
= strtol(expires_in
, NULL
, 10);
434 cred
->expires_at
= time(NULL
) + e
;
436 } else if (ctx
->log
!= NULL
) {
437 fprintf(ctx
->log
, "* invalid expiration: %s\n", expires_in
);
441 /* [1] 6 Refreshing an Access Token says a new refresh token may be issued
442 * in refresh responses. */
443 if (refresh_token
!= NULL
) {
444 free(cred
->refresh_token
);
445 cred
->refresh_token
= refresh_token
;
446 refresh_token
= NULL
;
457 do_access_request(mh_oauth_cred
*cred
, const char *req_body
)
459 mh_oauth_ctx
*ctx
= cred
->ctx
;
460 struct curl_ctx curl_ctx
;
462 curl_ctx
.curl
= ctx
->curl
;
463 curl_ctx
.log
= ctx
->log
;
464 if (!post(&curl_ctx
, ctx
->svc
.token_endpoint
, req_body
)) {
465 if (curl_ctx
.too_big
) {
466 set_err(ctx
, MH_OAUTH_RESPONSE_TOO_BIG
);
468 set_err_details(ctx
, MH_OAUTH_POST
, ctx
->err_buf
);
473 if (curl_ctx
.res_code
!= 200) {
474 set_err_http(ctx
, &curl_ctx
);
478 if (!cred_from_response(cred
, curl_ctx
.content_type
, curl_ctx
.res_body
,
480 set_err(ctx
, MH_OAUTH_RESPONSE_BAD
);
488 mh_oauth_authorize(const char *code
, mh_oauth_ctx
*ctx
)
490 mh_oauth_cred
*result
;
492 if (!make_query_url(ctx
->buf
, sizeof ctx
->buf
, ctx
->curl
, NULL
,
494 "grant_type", "authorization_code",
495 "redirect_uri", ctx
->svc
.redirect_uri
,
496 "client_id", ctx
->svc
.client_id
,
497 "client_secret", ctx
->svc
.client_secret
,
499 set_err(ctx
, MH_OAUTH_REQUEST_INIT
);
505 result
->access_token
= result
->refresh_token
= NULL
;
507 if (!do_access_request(result
, ctx
->buf
)) {
516 mh_oauth_refresh(mh_oauth_cred
*cred
)
519 mh_oauth_ctx
*ctx
= cred
->ctx
;
521 if (cred
->refresh_token
== NULL
) {
522 set_err(ctx
, MH_OAUTH_NO_REFRESH
);
526 if (!make_query_url(ctx
->buf
, sizeof ctx
->buf
, ctx
->curl
, NULL
,
527 "grant_type", "refresh_token",
528 "refresh_token", cred
->refresh_token
,
529 "client_id", ctx
->svc
.client_id
,
530 "client_secret", ctx
->svc
.client_secret
,
532 set_err(ctx
, MH_OAUTH_REQUEST_INIT
);
536 result
= do_access_request(cred
, ctx
->buf
);
538 if (result
&& cred
->access_token
== NULL
) {
539 set_err_details(ctx
, MH_OAUTH_RESPONSE_BAD
, "no access token");
547 mh_oauth_access_token_valid(time_t t
, const mh_oauth_cred
*cred
)
549 return cred
->access_token
!= NULL
&& t
+ EXPIRY_FUDGE
< cred
->expires_at
;
553 mh_oauth_cred_free(mh_oauth_cred
*cred
)
555 free(cred
->refresh_token
);
556 free(cred
->access_token
);
560 /* for loading multi-user cred files */
562 mh_oauth_cred
*creds
;
564 /* number of allocated mh_oauth_cred structs above points to */
567 /* number that are actually filled in and used */
571 /* If user has an entry in user_creds, return pointer to it. Else allocate a
572 * new struct in user_creds and return pointer to that. */
573 static mh_oauth_cred
*
574 find_or_alloc_user_creds(struct user_creds user_creds
[], const char *user
)
576 mh_oauth_cred
*creds
= user_creds
->creds
;
578 for (i
= 0; i
< user_creds
->len
; i
++) {
579 if (strcmp(creds
[i
].user
, user
) == 0) {
583 if (user_creds
->alloc
== user_creds
->len
) {
584 user_creds
->alloc
*= 2;
585 user_creds
->creds
= mh_xrealloc(user_creds
->creds
, user_creds
->alloc
);
587 creds
= user_creds
->creds
+user_creds
->len
;
589 creds
->user
= getcpy(user
);
590 creds
->access_token
= creds
->refresh_token
= NULL
;
591 creds
->expires_at
= 0;
596 free_user_creds(struct user_creds
*user_creds
)
600 cred
= user_creds
->creds
;
601 for (i
= 0; i
< user_creds
->len
; i
++) {
603 free(cred
[i
].access_token
);
604 free(cred
[i
].refresh_token
);
606 free(user_creds
->creds
);
611 load_creds(struct user_creds
**result
, FILE *fp
, mh_oauth_ctx
*ctx
)
613 boolean success
= FALSE
;
614 char name
[NAMESZ
], value_buf
[BUFSIZ
];
616 m_getfld_state_t getfld_ctx
= 0;
618 struct user_creds
*user_creds
;
620 user_creds
->alloc
= 4;
622 user_creds
->creds
= mh_xmalloc(user_creds
->alloc
* sizeof *user_creds
->creds
);
625 int size
= sizeof value_buf
;
626 switch (state
= m_getfld(&getfld_ctx
, name
, value_buf
, &size
, fp
)) {
629 char **save
, *expire
;
630 time_t *expires_at
= NULL
;
631 if (has_prefix(name
, "access-")) {
632 const char *user
= name
+ 7;
633 mh_oauth_cred
*creds
= find_or_alloc_user_creds(user_creds
,
635 save
= &creds
->access_token
;
636 } else if (has_prefix(name
, "refresh-")) {
637 const char *user
= name
+ 8;
638 mh_oauth_cred
*creds
= find_or_alloc_user_creds(user_creds
,
640 save
= &creds
->refresh_token
;
641 } else if (has_prefix(name
, "expire-")) {
642 const char *user
= name
+ 7;
643 mh_oauth_cred
*creds
= find_or_alloc_user_creds(user_creds
,
645 expires_at
= &creds
->expires_at
;
648 set_err_details(ctx
, MH_OAUTH_CRED_FILE
, "unexpected field");
653 *save
= trimcpy(value_buf
);
655 char *tmp
= getcpy(value_buf
);
656 while (state
== FLDPLUS
) {
657 size
= sizeof value_buf
;
658 state
= m_getfld(&getfld_ctx
, name
, value_buf
, &size
, fp
);
659 tmp
= add(value_buf
, tmp
);
661 *save
= trimcpy(tmp
);
664 if (expires_at
!= NULL
) {
666 *expires_at
= strtol(expire
, NULL
, 10);
669 set_err_details(ctx
, MH_OAUTH_CRED_FILE
,
670 "invalid expiration time");
684 /* Not adding details for LENERR/FMTERR because m_getfld already
685 * wrote advise message to stderr. */
686 set_err(ctx
, MH_OAUTH_CRED_FILE
);
691 m_getfld_state_destroy(&getfld_ctx
);
694 *result
= user_creds
;
696 free_user_creds(user_creds
);
703 save_user(FILE *fp
, const char *user
, const char *access
, const char *refresh
,
706 if (access
!= NULL
) {
707 if (fprintf(fp
, "access-%s: %s\n", user
, access
) < 0) return FALSE
;
709 if (refresh
!= NULL
) {
710 if (fprintf(fp
, "refresh-%s: %s\n", user
, refresh
) < 0) return FALSE
;
712 if (expires_at
> 0) {
713 if (fprintf(fp
, "expire-%s: %ld\n", user
, (long)expires_at
) < 0) {
721 mh_oauth_cred_save(FILE *fp
, mh_oauth_cred
*cred
, const char *user
)
723 struct user_creds
*user_creds
;
727 /* Load existing creds if any. */
728 if (!load_creds(&user_creds
, fp
, cred
->ctx
)) {
732 if (fchmod(fd
, S_IRUSR
| S_IWUSR
) < 0) goto err
;
733 if (ftruncate(fd
, 0) < 0) goto err
;
734 if (fseek(fp
, 0, SEEK_SET
) < 0) goto err
;
736 /* Write all creds except for this user. */
737 for (i
= 0; i
< user_creds
->len
; i
++) {
738 mh_oauth_cred
*c
= &user_creds
->creds
[i
];
739 if (strcmp(c
->user
, user
) == 0) continue;
740 if (!save_user(fp
, c
->user
, c
->access_token
, c
->refresh_token
,
746 /* Write updated creds for this user. */
747 if (!save_user(fp
, user
, cred
->access_token
, cred
->refresh_token
,
752 free_user_creds(user_creds
);
757 free_user_creds(user_creds
);
758 set_err(cred
->ctx
, MH_OAUTH_CRED_FILE
);
763 mh_oauth_cred_load(FILE *fp
, mh_oauth_ctx
*ctx
, const char *user
)
765 mh_oauth_cred
*creds
, *result
= NULL
;
766 struct user_creds
*user_creds
;
769 if (!load_creds(&user_creds
, fp
, ctx
)) {
773 /* Search user_creds for this user. If we don't find it, return NULL.
774 * If we do, free fields of all structs except this one, moving this one to
775 * the first struct if necessary. When we return it, it just looks like one
776 * struct to the caller, and the whole array is freed later. */
777 creds
= user_creds
->creds
;
778 for (i
= 0; i
< user_creds
->len
; i
++) {
779 if (strcmp(creds
[i
].user
, user
) == 0) {
782 result
->access_token
= creds
[i
].access_token
;
783 result
->refresh_token
= creds
[i
].refresh_token
;
784 result
->expires_at
= creds
[i
].expires_at
;
787 free(creds
[i
].access_token
);
788 free(creds
[i
].refresh_token
);
793 /* No longer need user_creds. result just uses its creds member. */
796 if (result
== NULL
) {
797 set_err_details(ctx
, MH_OAUTH_CRED_USER_NOT_FOUND
, user
);
808 mh_oauth_sasl_client_response(size_t *res_len
,
809 const char *user
, const mh_oauth_cred
*cred
)
813 p
= &cred
->ctx
->sasl_client_res
;
815 *p
= concat("user=", user
, "\1auth=Bearer ", cred
->access_token
, "\1\1", NULL
);
816 *res_len
= strlen(*p
);
820 /*******************************************************************************
821 * building URLs and making HTTP requests with libcurl
825 * Build null-terminated URL in the array pointed to by s. If the URL doesn't
826 * fit within size (including the terminating null byte), return FALSE without *
827 * building the entire URL. Some of URL may already have been written into the
828 * result array in that case.
831 make_query_url(char *s
, size_t size
, CURL
*curl
, const char *base_url
, ...)
833 boolean result
= FALSE
;
839 if (base_url
== NULL
) {
843 len
= strlen(base_url
);
844 if (len
> size
- 1) /* Less one for NUL. */
850 va_start(ap
, base_url
);
851 for (name
= va_arg(ap
, char *); name
!= NULL
; name
= va_arg(ap
, char *)) {
852 char *name_esc
= curl_easy_escape(curl
, name
, 0);
853 char *val_esc
= curl_easy_escape(curl
, va_arg(ap
, char *), 0);
854 /* prefix + name_esc + '=' + val_esc + '\0' must fit within size */
860 if (new_len
+ 1 > size
) {
865 sprintf(s
+ len
, "%s%s=%s", prefix
, name_esc
, val_esc
);
880 debug_callback(const CURL
*handle
, curl_infotype type
, const char *data
,
881 size_t size
, void *userptr
)
887 case CURLINFO_HEADER_IN
:
888 case CURLINFO_DATA_IN
:
891 case CURLINFO_HEADER_OUT
:
892 case CURLINFO_DATA_OUT
:
898 fwrite(data
, 1, size
, fp
);
899 if (data
[size
- 1] != '\n') {
907 write_callback(const char *ptr
, size_t size
, size_t nmemb
, void *userdata
)
909 struct curl_ctx
*ctx
= userdata
;
917 new_len
= ctx
->res_len
+ size
;
918 if (new_len
> sizeof ctx
->res_body
) {
923 memcpy(ctx
->res_body
+ ctx
->res_len
, ptr
, size
);
924 ctx
->res_len
= new_len
;
930 post(struct curl_ctx
*ctx
, const char *url
, const char *req_body
)
932 CURL
*curl
= ctx
->curl
;
935 ctx
->too_big
= FALSE
;
938 if (ctx
->log
!= NULL
) {
939 curl_easy_setopt(curl
, CURLOPT_VERBOSE
, (long)1);
940 curl_easy_setopt(curl
, CURLOPT_DEBUGFUNCTION
, debug_callback
);
941 curl_easy_setopt(curl
, CURLOPT_DEBUGDATA
, ctx
->log
);
944 if ((status
= curl_easy_setopt(curl
, CURLOPT_URL
, url
)) != CURLE_OK
) {
948 curl_easy_setopt(curl
, CURLOPT_POSTFIELDS
, req_body
);
949 curl_easy_setopt(curl
, CURLOPT_WRITEFUNCTION
, write_callback
);
950 curl_easy_setopt(curl
, CURLOPT_WRITEDATA
, ctx
);
952 if (has_prefix(url
, "http://127.0.0.1:")) {
953 /* Hack: on Cygwin, curl doesn't fail to connect with ECONNREFUSED.
954 Instead, it waits to timeout. So set a really short timeout, but
955 just on localhost (for convenience of the user, and the test
957 curl_easy_setopt(curl
, CURLOPT_CONNECTTIMEOUT
, 2L);
960 status
= curl_easy_perform(curl
);
961 /* first check for error from callback */
966 if (status
!= CURLE_OK
) {
970 if ((status
= curl_easy_getinfo(curl
, CURLINFO_RESPONSE_CODE
,
971 &ctx
->res_code
)) != CURLE_OK
972 || (status
= curl_easy_getinfo(curl
, CURLINFO_CONTENT_TYPE
,
973 &ctx
->content_type
)) != CURLE_OK
) {
980 /*******************************************************************************
984 /* We need 2 for each key/value pair plus 1 for the enclosing object, which
985 * means we only need 9 for Gmail. Clients must not fail if the server returns
986 * more, though, e.g. for protocol extensions. */
987 #define JSMN_TOKENS 16
990 * Parse JSON, store pointer to array of jsmntok_t in tokens.
992 * Returns whether parsing is successful.
994 * Even in that case, tokens has been allocated and must be freed.
997 parse_json(jsmntok_t
**tokens
, size_t *tokens_len
,
998 const char *input
, size_t input_len
, FILE *log
)
1003 *tokens_len
= JSMN_TOKENS
;
1004 *tokens
= mh_xmalloc(*tokens_len
* sizeof **tokens
);
1007 while ((r
= jsmn_parse(&p
, input
, input_len
,
1008 *tokens
, *tokens_len
)) == JSMN_ERROR_NOMEM
) {
1009 *tokens_len
= 2 * *tokens_len
;
1011 fprintf(log
, "* need more jsmntok_t! allocating %ld\n",
1014 /* Don't need to limit how much we allocate; we already limited the size
1015 of the response body. */
1016 *tokens
= mh_xrealloc(*tokens
, *tokens_len
* sizeof **tokens
);
1026 * Search input and tokens for the value identified by null-terminated name.
1028 * If found, allocate a null-terminated copy of the value and store the address
1029 * in val. val is left untouched if not found.
1032 get_json_string(char **val
, const char *input
, const jsmntok_t
*tokens
,
1035 /* number of top-level tokens (not counting object/list children) */
1036 int token_count
= tokens
[0].size
* 2;
1037 /* number of tokens to skip when we encounter objects and lists */
1038 /* We only look for top-level strings. */
1039 int skip_tokens
= 0;
1040 /* whether the current token represents a field name */
1041 /* The next token will be the value. */
1042 boolean is_key
= TRUE
;
1045 for (i
= 1; i
<= token_count
; i
++) {
1048 if (tokens
[i
].type
== JSMN_ARRAY
|| tokens
[i
].type
== JSMN_OBJECT
) {
1049 /* We're not interested in any array or object children; skip. */
1050 int children
= tokens
[i
].size
;
1051 if (tokens
[i
].type
== JSMN_OBJECT
) {
1052 /* Object size counts key/value pairs, skip both. */
1055 /* Add children to token_count. */
1056 token_count
+= children
;
1057 if (skip_tokens
== 0) {
1058 /* This token not already skipped; skip it. */
1059 /* Would already be skipped if child of object or list. */
1062 /* Skip this token's children. */
1063 skip_tokens
+= children
;
1065 if (skip_tokens
> 0) {
1067 /* When we finish with the object or list, we'll have a key. */
1075 key
= input
+ tokens
[i
- 1].start
;
1076 key_len
= tokens
[i
- 1].end
- tokens
[i
- 1].start
;
1077 if (strncmp(key
, name
, key_len
) == 0) {
1078 int val_len
= tokens
[i
].end
- tokens
[i
].start
;
1079 *val
= mh_xmalloc(val_len
+ 1);
1080 memcpy(*val
, input
+ tokens
[i
].start
, val_len
);
1081 (*val
)[val_len
] = '\0';
1089 * Parse input as JSON, extracting specified string values.
1091 * Variadic arguments are pairs of null-terminated strings indicating the value
1092 * to extract from the JSON and addresses into which pointers to null-terminated
1093 * copies of the values are written. These must be followed by one NULL pointer
1094 * to indicate the end of pairs.
1096 * The extracted strings are copies which caller must free. If any name is not
1097 * found, the address to store the value is not touched.
1099 * Returns non-zero if parsing is successful.
1101 * When parsing failed, no strings have been copied.
1103 * log may be used for debug-logging if not NULL.
1106 get_json_strings(const char *input
, size_t input_len
, FILE *log
, ...)
1108 boolean result
= FALSE
;
1114 if (!parse_json(&tokens
, &tokens_len
, input
, input_len
, log
)) {
1118 if (tokens
->type
!= JSMN_OBJECT
|| tokens
->size
== 0) {
1125 for (name
= va_arg(ap
, char *); name
!= NULL
; name
= va_arg(ap
, char *)) {
1126 get_json_string(va_arg(ap
, char **), input
, tokens
, name
);