1 /* oauth.c -- OAuth 2.0 implementation for XOAUTH2 in SMTP and POP3.
3 * This code is Copyright (c) 2014, by the authors of nmh. See the
4 * COPYRIGHT file in the root directory of the nmh distribution for
5 * complete copyright information.
27 #include <curl/curl.h>
28 #include "thirdparty/jsmn/jsmn.h"
32 #include "lock_file.h"
34 #define JSON_TYPE "application/json"
36 /* We pretend access tokens expire 60 seconds earlier than they actually do to
37 * allow for separate processes to use and refresh access tokens. The process
38 * that uses the access token (post) has an error if the token is expired; the
39 * process that refreshes the access token (send) must have already refreshed if
40 * the expiration is close.
42 * 60s is arbitrary, and hopefully is enough to allow for clock skew.
43 * Currently only Gmail supports XOAUTH2, and seems to always use a token
44 * life-time of 3600s, but that is not guaranteed. It is possible for Gmail to
45 * issue an access token with a life-time so short that even after send
46 * refreshes it, it's already expired when post tries to use it, but that seems
48 #define EXPIRY_FUDGE 60
50 /* maximum size for HTTP response bodies
51 * (not counting header and not null-terminated) */
52 #define RESPONSE_BODY_MAX 8192
54 /* Maximum size for URLs and URI-encoded query strings, null-terminated.
56 * Actual maximum we need is based on the size of tokens (limited by
57 * RESPONSE_BODY_MAX), code user copies from a web page (arbitrarily large), and
58 * various service parameters (all arbitrarily large). In practice, all these
59 * are just tens of bytes. It's not hard to change this to realloc as needed,
60 * but we should still have some limit, so why not this one?
64 struct mh_oauth_cred
{
67 /* opaque access token ([1] 1.4) in null-terminated string */
69 /* opaque refresh token ([1] 1.5) in null-terminated string */
72 /* time at which the access token expires, or 0 if unknown */
75 /* Ignoring token_type ([1] 7.1) because
76 * https://developers.google.com/accounts/docs/OAuth2InstalledApp says
77 * "Currently, this field always has the value Bearer". */
79 /* only filled while loading cred files, otherwise NULL */
84 struct mh_oauth_service_info svc
;
91 char *sasl_client_res
;
94 mh_oauth_err_code err_code
;
96 /* If any detailed message about the error is available, this points to it.
97 * May point to err_buf, or something else. */
98 const char *err_details
;
100 /* Pointer to buffer mh_oauth_err_get_string allocates. */
103 /* Ask libcurl to store errors here. */
104 char err_buf
[CURL_ERROR_SIZE
];
111 /* NULL or a file handle to have curl log diagnostics to */
116 /* Whether the response was too big; if so, the rest of the output fields
120 /* HTTP response code */
123 /* NULL or null-terminated value of Content-Type response header field */
124 const char *content_type
;
126 /* number of bytes in the response body */
129 /* response body; NOT null-terminated */
130 char res_body
[RESPONSE_BODY_MAX
];
133 static bool get_json_strings(const char *, size_t, FILE *, ...) ENDNULL
;
134 static bool make_query_url(char *, size_t, CURL
*, const char *, ...) ENDNULL
;
135 static bool post(struct curl_ctx
*, const char *, const char *);
138 mh_oauth_do_xoauth(const char *user
, const char *svc
, unsigned char **oauth_res
,
139 size_t *oauth_res_len
, FILE *log
)
144 int failed_to_lock
= 0;
148 if (!mh_oauth_new (&ctx
, svc
))
149 die("%s", mh_oauth_get_err_string(ctx
));
151 if (log
!= NULL
) mh_oauth_log_to(stderr
, ctx
);
153 fn
= mh_oauth_cred_fn(svc
);
154 fp
= lkfopendata(fn
, "r+", &failed_to_lock
);
156 if (errno
== ENOENT
) {
157 die("no credentials -- run mhlogin -saslmech xoauth2 -authservice %s", svc
);
159 adios(fn
, "failed to open");
161 if (failed_to_lock
) {
162 adios(fn
, "failed to lock");
165 if ((cred
= mh_oauth_cred_load(fp
, ctx
, user
)) == NULL
) {
166 die("%s", mh_oauth_get_err_string(ctx
));
169 if (!mh_oauth_access_token_valid(time(NULL
), cred
)) {
170 if (!mh_oauth_refresh(cred
)) {
171 if (mh_oauth_get_err_code(ctx
) == MH_OAUTH_NO_REFRESH
) {
172 die("no valid credentials -- run mhlogin -saslmech xoauth2 -authservice %s", svc
);
174 if (mh_oauth_get_err_code(ctx
) == MH_OAUTH_BAD_GRANT
) {
175 die("credentials rejected -- run mhlogin -saslmech xoauth2 -authservice %s", svc
);
177 inform("error refreshing OAuth2 token");
178 die("%s", mh_oauth_get_err_string(ctx
));
181 fseek(fp
, 0, SEEK_SET
);
182 if (!mh_oauth_cred_save(fp
, cred
, user
)) {
183 die("%s", mh_oauth_get_err_string(ctx
));
187 if (lkfclosedata(fp
, fn
) < 0) {
188 adios(fn
, "failed to close");
192 /* XXX writeBase64raw modifies the source buffer! make a copy */
193 client_res
= mh_xstrdup(mh_oauth_sasl_client_response(oauth_res_len
, user
,
195 mh_oauth_cred_free(cred
);
198 *oauth_res
= (unsigned char *) client_res
;
204 is_json(const char *content_type
)
206 return content_type
!= NULL
207 && strncasecmp(content_type
, JSON_TYPE
, LEN(JSON_TYPE
)) == 0;
211 set_err_details(mh_oauth_ctx
*ctx
, mh_oauth_err_code code
, const char *details
)
213 ctx
->err_code
= code
;
214 ctx
->err_details
= details
;
218 set_err(mh_oauth_ctx
*ctx
, mh_oauth_err_code code
)
220 set_err_details(ctx
, code
, NULL
);
224 set_err_http(mh_oauth_ctx
*ctx
, const struct curl_ctx
*curl_ctx
)
227 mh_oauth_err_code code
;
228 /* 5.2. Error Response says error response should use status code 400 and
229 * application/json body. If Content-Type matches, try to parse the body
230 * regardless of the status code. */
231 if (curl_ctx
->res_len
> 0
232 && is_json(curl_ctx
->content_type
)
233 && get_json_strings(curl_ctx
->res_body
, curl_ctx
->res_len
, ctx
->log
,
234 "error", &error
, NULL
)
236 if (strcmp(error
, "invalid_grant") == 0) {
237 code
= MH_OAUTH_BAD_GRANT
;
239 /* All other errors indicate a bug, not anything the user did. */
240 code
= MH_OAUTH_REQUEST_BAD
;
243 code
= MH_OAUTH_RESPONSE_BAD
;
250 make_user_agent(void)
252 const char *curl
= curl_version_info(CURLVERSION_NOW
)->version
;
253 return concat(user_agent
, " libcurl/", curl
, NULL
);
257 mh_oauth_new(mh_oauth_ctx
**result
, const char *svc_name
)
266 ctx
->cred_fn
= ctx
->sasl_client_res
= ctx
->err_formatted
= NULL
;
268 if (!mh_oauth_get_service_info(svc_name
, &ctx
->svc
, ctx
->err_buf
,
269 sizeof(ctx
->err_buf
))) {
270 set_err_details(ctx
, MH_OAUTH_BAD_PROFILE
, ctx
->err_buf
);
274 ctx
->curl
= curl_easy_init();
275 if (ctx
->curl
== NULL
) {
276 set_err(ctx
, MH_OAUTH_CURL_INIT
);
279 curl_easy_setopt(ctx
->curl
, CURLOPT_ERRORBUFFER
, ctx
->err_buf
);
281 ctx
->user_agent
= make_user_agent();
283 if (curl_easy_setopt(ctx
->curl
, CURLOPT_USERAGENT
,
284 ctx
->user_agent
) != CURLE_OK
) {
285 set_err_details(ctx
, MH_OAUTH_CURL_INIT
, ctx
->err_buf
);
293 mh_oauth_free(mh_oauth_ctx
*ctx
)
296 free(ctx
->svc
.scope
);
297 free(ctx
->svc
.client_id
);
298 free(ctx
->svc
.client_secret
);
299 free(ctx
->svc
.auth_endpoint
);
300 free(ctx
->svc
.token_endpoint
);
301 free(ctx
->svc
.redirect_uri
);
303 free(ctx
->sasl_client_res
);
304 free(ctx
->err_formatted
);
305 free(ctx
->user_agent
);
307 if (ctx
->curl
!= NULL
) {
308 curl_easy_cleanup(ctx
->curl
);
314 mh_oauth_svc_display_name(const mh_oauth_ctx
*ctx
)
316 return ctx
->svc
.display_name
;
320 mh_oauth_log_to(FILE *log
, mh_oauth_ctx
*ctx
)
326 mh_oauth_get_err_code(const mh_oauth_ctx
*ctx
)
328 return ctx
->err_code
;
332 mh_oauth_get_err_string(mh_oauth_ctx
*ctx
)
336 free(ctx
->err_formatted
);
338 switch (ctx
->err_code
) {
339 case MH_OAUTH_BAD_PROFILE
:
340 base
= "incomplete OAuth2 service definition";
342 case MH_OAUTH_CURL_INIT
:
343 base
= "error initializing libcurl";
345 case MH_OAUTH_REQUEST_INIT
:
346 base
= "local error initializing HTTP request";
349 base
= "error making HTTP request to OAuth2 authorization endpoint";
351 case MH_OAUTH_RESPONSE_TOO_BIG
:
352 base
= "refusing to process response body larger than 8192 bytes";
354 case MH_OAUTH_RESPONSE_BAD
:
355 base
= "invalid response";
357 case MH_OAUTH_BAD_GRANT
:
358 base
= "bad grant (authorization code or refresh token)";
360 case MH_OAUTH_REQUEST_BAD
:
361 base
= "bad OAuth request; re-run with -snoop and send REDACTED output"
364 case MH_OAUTH_NO_REFRESH
:
365 base
= "no refresh token";
367 case MH_OAUTH_CRED_USER_NOT_FOUND
:
368 base
= "user not found in cred file";
370 case MH_OAUTH_CRED_FILE
:
371 base
= "error loading cred file";
374 base
= "unknown error";
376 if (ctx
->err_details
== NULL
) {
377 return ctx
->err_formatted
= mh_xstrdup(base
);
380 ctx
->err_formatted
= concat(base
, ": ", ctx
->err_details
, NULL
);
381 return ctx
->err_formatted
;
385 mh_oauth_get_authorize_url(mh_oauth_ctx
*ctx
)
387 /* [1] 4.1.1 Authorization Request */
388 if (!make_query_url(ctx
->buf
, sizeof ctx
->buf
, ctx
->curl
,
389 ctx
->svc
.auth_endpoint
,
390 "response_type", "code",
391 "client_id", ctx
->svc
.client_id
,
392 "redirect_uri", ctx
->svc
.redirect_uri
,
393 "scope", ctx
->svc
.scope
,
395 set_err(ctx
, MH_OAUTH_REQUEST_INIT
);
402 cred_from_response(mh_oauth_cred
*cred
, const char *content_type
,
403 const char *input
, size_t input_len
)
406 char *access_token
, *expires_in
, *refresh_token
;
407 const mh_oauth_ctx
*ctx
= cred
->ctx
;
409 if (!is_json(content_type
)) {
413 access_token
= expires_in
= refresh_token
= NULL
;
414 if (!get_json_strings(input
, input_len
, ctx
->log
,
415 "access_token", &access_token
,
416 "expires_in", &expires_in
,
417 "refresh_token", &refresh_token
,
422 if (access_token
== NULL
) {
423 /* Response is invalid, but if it has a refresh token, we can try. */
424 if (refresh_token
== NULL
) {
431 free(cred
->access_token
);
432 cred
->access_token
= access_token
;
435 cred
->expires_at
= 0;
436 if (expires_in
!= NULL
) {
439 e
= strtol(expires_in
, NULL
, 10);
442 cred
->expires_at
= time(NULL
) + e
;
444 } else if (ctx
->log
!= NULL
) {
445 fprintf(ctx
->log
, "* invalid expiration: %s\n", expires_in
);
449 /* [1] 6 Refreshing an Access Token says a new refresh token may be issued
450 * in refresh responses. */
451 if (refresh_token
!= NULL
) {
452 free(cred
->refresh_token
);
453 cred
->refresh_token
= refresh_token
;
454 refresh_token
= NULL
;
465 do_access_request(mh_oauth_cred
*cred
, const char *req_body
)
467 mh_oauth_ctx
*ctx
= cred
->ctx
;
468 struct curl_ctx curl_ctx
;
470 curl_ctx
.curl
= ctx
->curl
;
471 curl_ctx
.log
= ctx
->log
;
472 if (!post(&curl_ctx
, ctx
->svc
.token_endpoint
, req_body
)) {
473 if (curl_ctx
.too_big
) {
474 set_err(ctx
, MH_OAUTH_RESPONSE_TOO_BIG
);
476 set_err_details(ctx
, MH_OAUTH_POST
, ctx
->err_buf
);
481 if (curl_ctx
.res_code
!= 200) {
482 set_err_http(ctx
, &curl_ctx
);
486 if (!cred_from_response(cred
, curl_ctx
.content_type
, curl_ctx
.res_body
,
488 set_err(ctx
, MH_OAUTH_RESPONSE_BAD
);
496 mh_oauth_authorize(const char *code
, mh_oauth_ctx
*ctx
)
498 mh_oauth_cred
*result
;
500 if (!make_query_url(ctx
->buf
, sizeof ctx
->buf
, ctx
->curl
, NULL
,
502 "grant_type", "authorization_code",
503 "redirect_uri", ctx
->svc
.redirect_uri
,
504 "client_id", ctx
->svc
.client_id
,
505 "client_secret", ctx
->svc
.client_secret
,
507 set_err(ctx
, MH_OAUTH_REQUEST_INIT
);
513 result
->access_token
= result
->refresh_token
= NULL
;
515 if (!do_access_request(result
, ctx
->buf
)) {
524 mh_oauth_refresh(mh_oauth_cred
*cred
)
527 mh_oauth_ctx
*ctx
= cred
->ctx
;
529 if (cred
->refresh_token
== NULL
) {
530 set_err(ctx
, MH_OAUTH_NO_REFRESH
);
534 if (!make_query_url(ctx
->buf
, sizeof ctx
->buf
, ctx
->curl
, NULL
,
535 "grant_type", "refresh_token",
536 "refresh_token", cred
->refresh_token
,
537 "client_id", ctx
->svc
.client_id
,
538 "client_secret", ctx
->svc
.client_secret
,
540 set_err(ctx
, MH_OAUTH_REQUEST_INIT
);
544 result
= do_access_request(cred
, ctx
->buf
);
546 if (result
&& cred
->access_token
== NULL
) {
547 set_err_details(ctx
, MH_OAUTH_RESPONSE_BAD
, "no access token");
555 mh_oauth_access_token_valid(time_t t
, const mh_oauth_cred
*cred
)
557 return cred
->access_token
!= NULL
&& t
+ EXPIRY_FUDGE
< cred
->expires_at
;
561 mh_oauth_cred_free(mh_oauth_cred
*cred
)
563 free(cred
->refresh_token
);
564 free(cred
->access_token
);
568 /* for loading multi-user cred files */
570 mh_oauth_cred
*creds
;
572 /* number of allocated mh_oauth_cred structs above points to */
575 /* number that are actually filled in and used */
579 /* If user has an entry in user_creds, return pointer to it. Else allocate a
580 * new struct in user_creds and return pointer to that. */
581 static mh_oauth_cred
*
582 find_or_alloc_user_creds(struct user_creds user_creds
[], const char *user
)
584 mh_oauth_cred
*creds
= user_creds
->creds
;
586 for (i
= 0; i
< user_creds
->len
; i
++) {
587 if (strcmp(creds
[i
].user
, user
) == 0) {
591 if (user_creds
->alloc
== user_creds
->len
) {
592 user_creds
->alloc
*= 2;
593 user_creds
->creds
= mh_xrealloc(user_creds
->creds
,
594 user_creds
->alloc
* sizeof *user_creds
->creds
);
596 creds
= user_creds
->creds
+user_creds
->len
;
598 creds
->user
= getcpy(user
);
599 creds
->access_token
= creds
->refresh_token
= NULL
;
600 creds
->expires_at
= 0;
605 free_user_creds(struct user_creds
*user_creds
)
609 cred
= user_creds
->creds
;
610 for (i
= 0; i
< user_creds
->len
; i
++) {
612 free(cred
[i
].access_token
);
613 free(cred
[i
].refresh_token
);
615 free(user_creds
->creds
);
620 load_creds(struct user_creds
**result
, FILE *fp
, mh_oauth_ctx
*ctx
)
622 bool success
= false;
623 char name
[NAMESZ
], value_buf
[BUFSIZ
];
625 m_getfld_state_t getfld_ctx
;
627 struct user_creds
*user_creds
;
629 user_creds
->alloc
= 16;
631 user_creds
->creds
= mh_xmalloc(user_creds
->alloc
* sizeof *user_creds
->creds
);
633 getfld_ctx
= m_getfld_state_init(fp
);
635 int size
= sizeof value_buf
;
636 switch (state
= m_getfld2(&getfld_ctx
, name
, value_buf
, &size
)) {
639 char **save
, *expire
;
640 time_t *expires_at
= NULL
;
641 if (has_prefix(name
, "access-")) {
642 const char *user
= name
+ 7;
643 mh_oauth_cred
*creds
= find_or_alloc_user_creds(user_creds
,
645 save
= &creds
->access_token
;
646 } else if (has_prefix(name
, "refresh-")) {
647 const char *user
= name
+ 8;
648 mh_oauth_cred
*creds
= find_or_alloc_user_creds(user_creds
,
650 save
= &creds
->refresh_token
;
651 } else if (has_prefix(name
, "expire-")) {
652 const char *user
= name
+ 7;
653 mh_oauth_cred
*creds
= find_or_alloc_user_creds(user_creds
,
655 expires_at
= &creds
->expires_at
;
658 set_err_details(ctx
, MH_OAUTH_CRED_FILE
, "unexpected field");
663 *save
= trimcpy(value_buf
);
665 char *tmp
= getcpy(value_buf
);
666 while (state
== FLDPLUS
) {
667 size
= sizeof value_buf
;
668 state
= m_getfld2(&getfld_ctx
, name
, value_buf
, &size
);
669 tmp
= add(value_buf
, tmp
);
671 *save
= trimcpy(tmp
);
674 if (expires_at
!= NULL
) {
676 *expires_at
= strtol(expire
, NULL
, 10);
679 set_err_details(ctx
, MH_OAUTH_CRED_FILE
,
680 "invalid expiration time");
694 /* Not adding details for LENERR/FMTERR because m_getfld2 already
695 * wrote advise message to stderr. */
696 set_err(ctx
, MH_OAUTH_CRED_FILE
);
701 m_getfld_state_destroy(&getfld_ctx
);
704 *result
= user_creds
;
706 free_user_creds(user_creds
);
713 save_user(FILE *fp
, const char *user
, const char *access
, const char *refresh
,
716 if (access
!= NULL
) {
717 if (fprintf(fp
, "access-%s: %s\n", user
, access
) < 0) return false;
719 if (refresh
!= NULL
) {
720 if (fprintf(fp
, "refresh-%s: %s\n", user
, refresh
) < 0) return false;
722 if (expires_at
> 0) {
723 if (fprintf(fp
, "expire-%s: %ld\n", user
, (long)expires_at
) < 0) {
731 mh_oauth_cred_save(FILE *fp
, mh_oauth_cred
*cred
, const char *user
)
733 struct user_creds
*user_creds
;
737 /* Load existing creds if any. */
738 if (!load_creds(&user_creds
, fp
, cred
->ctx
)) {
742 if (fchmod(fd
, S_IRUSR
| S_IWUSR
) < 0) goto err
;
743 if (ftruncate(fd
, 0) < 0) goto err
;
744 if (fseek(fp
, 0, SEEK_SET
) < 0) goto err
;
746 /* Write all creds except for this user. */
747 for (i
= 0; i
< user_creds
->len
; i
++) {
748 mh_oauth_cred
*c
= &user_creds
->creds
[i
];
749 if (strcmp(c
->user
, user
) == 0) continue;
750 if (!save_user(fp
, c
->user
, c
->access_token
, c
->refresh_token
,
756 /* Write updated creds for this user. */
757 if (!save_user(fp
, user
, cred
->access_token
, cred
->refresh_token
,
762 free_user_creds(user_creds
);
767 free_user_creds(user_creds
);
768 set_err(cred
->ctx
, MH_OAUTH_CRED_FILE
);
773 mh_oauth_cred_load(FILE *fp
, mh_oauth_ctx
*ctx
, const char *user
)
775 mh_oauth_cred
*creds
, *result
= NULL
;
776 struct user_creds
*user_creds
;
779 if (!load_creds(&user_creds
, fp
, ctx
)) {
783 /* Search user_creds for this user. If we don't find it, return NULL.
784 * If we do, free fields of all structs except this one, moving this one to
785 * the first struct if necessary. When we return it, it just looks like one
786 * struct to the caller, and the whole array is freed later. */
787 creds
= user_creds
->creds
;
788 for (i
= 0; i
< user_creds
->len
; i
++) {
789 if (strcmp(creds
[i
].user
, user
) == 0) {
792 result
->access_token
= creds
[i
].access_token
;
793 result
->refresh_token
= creds
[i
].refresh_token
;
794 result
->expires_at
= creds
[i
].expires_at
;
797 free(creds
[i
].access_token
);
798 free(creds
[i
].refresh_token
);
803 /* No longer need user_creds. result just uses its creds member. */
806 if (result
== NULL
) {
807 set_err_details(ctx
, MH_OAUTH_CRED_USER_NOT_FOUND
, user
);
818 mh_oauth_sasl_client_response(size_t *res_len
,
819 const char *user
, const mh_oauth_cred
*cred
)
823 p
= &cred
->ctx
->sasl_client_res
;
825 *p
= concat("user=", user
, "\1auth=Bearer ", cred
->access_token
, "\1\1", NULL
);
826 *res_len
= strlen(*p
);
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
, ...)
849 if (base_url
== NULL
) {
853 len
= strlen(base_url
);
854 if (len
> size
- 1) /* Less one for NUL. */
860 va_start(ap
, base_url
);
861 for (name
= va_arg(ap
, char *); name
!= NULL
; name
= va_arg(ap
, char *)) {
862 char *name_esc
= curl_easy_escape(curl
, name
, 0);
863 char *val_esc
= curl_easy_escape(curl
, va_arg(ap
, char *), 0);
864 /* prefix + name_esc + '=' + val_esc + '\0' must fit within size */
870 if (new_len
+ 1 > size
) {
875 sprintf(s
+ len
, "%s%s=%s", prefix
, name_esc
, val_esc
);
890 debug_callback(CURL
*handle
, curl_infotype type
, char *data
,
891 size_t size
, void *userptr
)
897 case CURLINFO_HEADER_IN
:
898 case CURLINFO_DATA_IN
:
901 case CURLINFO_HEADER_OUT
:
902 case CURLINFO_DATA_OUT
:
908 fwrite(data
, 1, size
, fp
);
909 if (data
[size
- 1] != '\n') {
917 write_callback(const char *ptr
, size_t size
, size_t nmemb
, void *userdata
)
919 struct curl_ctx
*ctx
= userdata
;
927 new_len
= ctx
->res_len
+ size
;
928 if (new_len
> sizeof ctx
->res_body
) {
933 memcpy(ctx
->res_body
+ ctx
->res_len
, ptr
, size
);
934 ctx
->res_len
= new_len
;
940 post(struct curl_ctx
*ctx
, const char *url
, const char *req_body
)
942 CURL
*curl
= ctx
->curl
;
945 ctx
->too_big
= false;
948 if (ctx
->log
!= NULL
) {
949 curl_easy_setopt(curl
, CURLOPT_VERBOSE
, (long)1);
950 curl_easy_setopt(curl
, CURLOPT_DEBUGFUNCTION
, debug_callback
);
951 curl_easy_setopt(curl
, CURLOPT_DEBUGDATA
, ctx
->log
);
954 if (curl_easy_setopt(curl
, CURLOPT_URL
, url
) != CURLE_OK
) {
958 curl_easy_setopt(curl
, CURLOPT_POSTFIELDS
, req_body
);
959 curl_easy_setopt(curl
, CURLOPT_WRITEFUNCTION
, write_callback
);
960 curl_easy_setopt(curl
, CURLOPT_WRITEDATA
, ctx
);
962 if (has_prefix(url
, "http://127.0.0.1:")) {
963 /* Hack: on Cygwin, curl doesn't fail to connect with ECONNREFUSED.
964 Instead, it waits to timeout. So set a really short timeout, but
965 just on localhost (for convenience of the user, and the test
967 curl_easy_setopt(curl
, CURLOPT_CONNECTTIMEOUT
, 2L);
970 status
= curl_easy_perform(curl
);
971 /* first check for error from callback */
976 if (status
!= CURLE_OK
) {
980 return curl_easy_getinfo(curl
,
981 CURLINFO_RESPONSE_CODE
, &ctx
->res_code
) == CURLE_OK
&&
982 curl_easy_getinfo(curl
,
983 CURLINFO_CONTENT_TYPE
, &ctx
->content_type
) == CURLE_OK
;
986 /*******************************************************************************
990 /* We need 2 for each key/value pair plus 1 for the enclosing object, which
991 * means we only need 9 for Gmail. Clients must not fail if the server returns
992 * more, though, e.g. for protocol extensions. */
993 #define JSMN_TOKENS 16
996 * Parse JSON, store pointer to array of jsmntok_t in tokens.
998 * Returns whether parsing is successful.
1000 * Even in that case, tokens has been allocated and must be freed.
1003 parse_json(jsmntok_t
**tokens
, size_t *tokens_len
,
1004 const char *input
, size_t input_len
, FILE *log
)
1009 *tokens_len
= JSMN_TOKENS
;
1010 *tokens
= mh_xmalloc(*tokens_len
* sizeof **tokens
);
1013 while ((r
= jsmn_parse(&p
, input
, input_len
,
1014 *tokens
, *tokens_len
)) == JSMN_ERROR_NOMEM
) {
1015 *tokens_len
= 2 * *tokens_len
;
1017 fprintf(log
, "* need more jsmntok_t! allocating %ld\n",
1020 /* Don't need to limit how much we allocate; we already limited the size
1021 of the response body. */
1022 *tokens
= mh_xrealloc(*tokens
, *tokens_len
* sizeof **tokens
);
1029 * Search input and tokens for the value identified by null-terminated name.
1031 * If found, allocate a null-terminated copy of the value and store the address
1032 * in val. val is left untouched if not found.
1035 get_json_string(char **val
, const char *input
, const jsmntok_t
*tokens
,
1038 /* number of top-level tokens (not counting object/list children) */
1039 int token_count
= tokens
[0].size
* 2;
1040 /* number of tokens to skip when we encounter objects and lists */
1041 /* We only look for top-level strings. */
1042 int skip_tokens
= 0;
1043 /* whether the current token represents a field name */
1044 /* The next token will be the value. */
1048 for (i
= 1; i
<= token_count
; i
++) {
1051 if (tokens
[i
].type
== JSMN_ARRAY
|| tokens
[i
].type
== JSMN_OBJECT
) {
1052 /* We're not interested in any array or object children; skip. */
1053 int children
= tokens
[i
].size
;
1054 if (tokens
[i
].type
== JSMN_OBJECT
) {
1055 /* Object size counts key/value pairs, skip both. */
1058 /* Add children to token_count. */
1059 token_count
+= children
;
1060 if (skip_tokens
== 0) {
1061 /* This token not already skipped; skip it. */
1062 /* Would already be skipped if child of object or list. */
1065 /* Skip this token's children. */
1066 skip_tokens
+= children
;
1068 if (skip_tokens
> 0) {
1070 /* When we finish with the object or list, we'll have a key. */
1078 key
= input
+ tokens
[i
- 1].start
;
1079 key_len
= tokens
[i
- 1].end
- tokens
[i
- 1].start
;
1080 if (strncmp(key
, name
, key_len
) == 0) {
1081 int val_len
= tokens
[i
].end
- tokens
[i
].start
;
1082 *val
= mh_xmalloc(val_len
+ 1);
1083 memcpy(*val
, input
+ tokens
[i
].start
, val_len
);
1084 (*val
)[val_len
] = '\0';
1092 * Parse input as JSON, extracting specified string values.
1094 * Variadic arguments are pairs of null-terminated strings indicating the value
1095 * to extract from the JSON and addresses into which pointers to null-terminated
1096 * copies of the values are written. These must be followed by one NULL pointer
1097 * to indicate the end of pairs.
1099 * The extracted strings are copies which caller must free. If any name is not
1100 * found, the address to store the value is not touched.
1102 * Returns non-zero if parsing is successful.
1104 * When parsing failed, no strings have been copied.
1106 * log may be used for debug-logging if not NULL.
1109 get_json_strings(const char *input
, size_t input_len
, FILE *log
, ...)
1111 bool result
= false;
1117 if (!parse_json(&tokens
, &tokens_len
, input
, input_len
, log
)) {
1121 if (tokens
->type
!= JSMN_OBJECT
|| tokens
->size
== 0) {
1128 for (name
= va_arg(ap
, char *); name
!= NULL
; name
= va_arg(ap
, char *)) {
1129 get_json_string(va_arg(ap
, char **), input
, tokens
, name
);