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.
26 #include <curl/curl.h>
27 #include "thirdparty/jsmn/jsmn.h"
31 #include "lock_file.h"
33 #define JSON_TYPE "application/json"
35 /* We pretend access tokens expire 60 seconds earlier than they actually do to
36 * allow for separate processes to use and refresh access tokens. The process
37 * that uses the access token (post) has an error if the token is expired; the
38 * process that refreshes the access token (send) must have already refreshed if
39 * the expiration is close.
41 * 60s is arbitrary, and hopefully is enough to allow for clock skew.
42 * Currently only Gmail supports XOAUTH2, and seems to always use a token
43 * life-time of 3600s, but that is not guaranteed. It is possible for Gmail to
44 * issue an access token with a life-time so short that even after send
45 * refreshes it, it's already expired when post tries to use it, but that seems
47 #define EXPIRY_FUDGE 60
49 /* maximum size for HTTP response bodies
50 * (not counting header and not null-terminated) */
51 #define RESPONSE_BODY_MAX 8192
53 /* Maximum size for URLs and URI-encoded query strings, null-terminated.
55 * Actual maximum we need is based on the size of tokens (limited by
56 * RESPONSE_BODY_MAX), code user copies from a web page (arbitrarily large), and
57 * various service parameters (all arbitrarily large). In practice, all these
58 * are just tens of bytes. It's not hard to change this to realloc as needed,
59 * but we should still have some limit, so why not this one?
63 struct mh_oauth_cred
{
66 /* opaque access token ([1] 1.4) in null-terminated string */
68 /* opaque refresh token ([1] 1.5) in null-terminated string */
71 /* time at which the access token expires, or 0 if unknown */
74 /* Ignoring token_type ([1] 7.1) because
75 * https://developers.google.com/accounts/docs/OAuth2InstalledApp says
76 * "Currently, this field always has the value Bearer". */
78 /* only filled while loading cred files, otherwise NULL */
83 struct mh_oauth_service_info svc
;
90 char *sasl_client_res
;
93 mh_oauth_err_code err_code
;
95 /* If any detailed message about the error is available, this points to it.
96 * May point to err_buf, or something else. */
97 const char *err_details
;
99 /* Pointer to buffer mh_oauth_err_get_string allocates. */
102 /* Ask libcurl to store errors here. */
103 char err_buf
[CURL_ERROR_SIZE
];
110 /* NULL or a file handle to have curl log diagnostics to */
115 /* Whether the response was too big; if so, the rest of the output fields
119 /* HTTP response code */
122 /* NULL or null-terminated value of Content-Type response header field */
123 const char *content_type
;
125 /* number of bytes in the response body */
128 /* response body; NOT null-terminated */
129 char res_body
[RESPONSE_BODY_MAX
];
132 static bool get_json_strings(const char *, size_t, FILE *, ...) ENDNULL
;
133 static bool make_query_url(char *, size_t, CURL
*, const char *, ...) ENDNULL
;
134 static bool post(struct curl_ctx
*, const char *, const char *);
137 mh_oauth_do_xoauth(const char *user
, const char *svc
, unsigned char **oauth_res
,
138 size_t *oauth_res_len
, FILE *log
)
143 int failed_to_lock
= 0;
147 if (!mh_oauth_new (&ctx
, svc
))
148 die("%s", mh_oauth_get_err_string(ctx
));
150 if (log
!= NULL
) mh_oauth_log_to(stderr
, ctx
);
152 fn
= mh_oauth_cred_fn(svc
);
153 fp
= lkfopendata(fn
, "r+", &failed_to_lock
);
155 if (errno
== ENOENT
) {
156 die("no credentials -- run mhlogin -saslmech xoauth2 -authservice %s", svc
);
158 adios(fn
, "failed to open");
160 if (failed_to_lock
) {
161 adios(fn
, "failed to lock");
164 if ((cred
= mh_oauth_cred_load(fp
, ctx
, user
)) == NULL
) {
165 die("%s", mh_oauth_get_err_string(ctx
));
168 if (!mh_oauth_access_token_valid(time(NULL
), cred
)) {
169 if (!mh_oauth_refresh(cred
)) {
170 if (mh_oauth_get_err_code(ctx
) == MH_OAUTH_NO_REFRESH
) {
171 die("no valid credentials -- run mhlogin -saslmech xoauth2 -authservice %s", svc
);
173 if (mh_oauth_get_err_code(ctx
) == MH_OAUTH_BAD_GRANT
) {
174 die("credentials rejected -- run mhlogin -saslmech xoauth2 -authservice %s", svc
);
176 inform("error refreshing OAuth2 token");
177 die("%s", mh_oauth_get_err_string(ctx
));
180 fseek(fp
, 0, SEEK_SET
);
181 if (!mh_oauth_cred_save(fp
, cred
, user
)) {
182 die("%s", mh_oauth_get_err_string(ctx
));
186 if (lkfclosedata(fp
, fn
) < 0) {
187 adios(fn
, "failed to close");
191 /* XXX writeBase64raw modifies the source buffer! make a copy */
192 client_res
= mh_xstrdup(mh_oauth_sasl_client_response(oauth_res_len
, user
,
194 mh_oauth_cred_free(cred
);
197 *oauth_res
= (unsigned char *) client_res
;
203 is_json(const char *content_type
)
205 return content_type
!= NULL
206 && strncasecmp(content_type
, JSON_TYPE
, LEN(JSON_TYPE
)) == 0;
210 set_err_details(mh_oauth_ctx
*ctx
, mh_oauth_err_code code
, const char *details
)
212 ctx
->err_code
= code
;
213 ctx
->err_details
= details
;
217 set_err(mh_oauth_ctx
*ctx
, mh_oauth_err_code code
)
219 set_err_details(ctx
, code
, NULL
);
223 set_err_http(mh_oauth_ctx
*ctx
, const struct curl_ctx
*curl_ctx
)
226 mh_oauth_err_code code
;
227 /* 5.2. Error Response says error response should use status code 400 and
228 * application/json body. If Content-Type matches, try to parse the body
229 * regardless of the status code. */
230 if (curl_ctx
->res_len
> 0
231 && is_json(curl_ctx
->content_type
)
232 && get_json_strings(curl_ctx
->res_body
, curl_ctx
->res_len
, ctx
->log
,
233 "error", &error
, NULL
)
235 if (strcmp(error
, "invalid_grant") == 0) {
236 code
= MH_OAUTH_BAD_GRANT
;
238 /* All other errors indicate a bug, not anything the user did. */
239 code
= MH_OAUTH_REQUEST_BAD
;
242 code
= MH_OAUTH_RESPONSE_BAD
;
249 make_user_agent(void)
251 const char *curl
= curl_version_info(CURLVERSION_NOW
)->version
;
252 return concat(user_agent
, " libcurl/", curl
, NULL
);
256 mh_oauth_new(mh_oauth_ctx
**result
, const char *svc_name
)
265 ctx
->cred_fn
= ctx
->sasl_client_res
= ctx
->err_formatted
= NULL
;
267 if (!mh_oauth_get_service_info(svc_name
, &ctx
->svc
, ctx
->err_buf
,
268 sizeof(ctx
->err_buf
))) {
269 set_err_details(ctx
, MH_OAUTH_BAD_PROFILE
, ctx
->err_buf
);
273 ctx
->curl
= curl_easy_init();
274 if (ctx
->curl
== NULL
) {
275 set_err(ctx
, MH_OAUTH_CURL_INIT
);
278 curl_easy_setopt(ctx
->curl
, CURLOPT_ERRORBUFFER
, ctx
->err_buf
);
280 ctx
->user_agent
= make_user_agent();
282 if (curl_easy_setopt(ctx
->curl
, CURLOPT_USERAGENT
,
283 ctx
->user_agent
) != CURLE_OK
) {
284 set_err_details(ctx
, MH_OAUTH_CURL_INIT
, ctx
->err_buf
);
292 mh_oauth_free(mh_oauth_ctx
*ctx
)
295 free(ctx
->svc
.scope
);
296 free(ctx
->svc
.client_id
);
297 free(ctx
->svc
.client_secret
);
298 free(ctx
->svc
.auth_endpoint
);
299 free(ctx
->svc
.token_endpoint
);
300 free(ctx
->svc
.redirect_uri
);
302 free(ctx
->sasl_client_res
);
303 free(ctx
->err_formatted
);
304 free(ctx
->user_agent
);
306 if (ctx
->curl
!= NULL
) {
307 curl_easy_cleanup(ctx
->curl
);
313 mh_oauth_svc_display_name(const mh_oauth_ctx
*ctx
)
315 return ctx
->svc
.display_name
;
319 mh_oauth_log_to(FILE *log
, mh_oauth_ctx
*ctx
)
325 mh_oauth_get_err_code(const mh_oauth_ctx
*ctx
)
327 return ctx
->err_code
;
331 mh_oauth_get_err_string(mh_oauth_ctx
*ctx
)
335 free(ctx
->err_formatted
);
337 switch (ctx
->err_code
) {
338 case MH_OAUTH_BAD_PROFILE
:
339 base
= "incomplete OAuth2 service definition";
341 case MH_OAUTH_CURL_INIT
:
342 base
= "error initializing libcurl";
344 case MH_OAUTH_REQUEST_INIT
:
345 base
= "local error initializing HTTP request";
348 base
= "error making HTTP request to OAuth2 authorization endpoint";
350 case MH_OAUTH_RESPONSE_TOO_BIG
:
351 base
= "refusing to process response body larger than 8192 bytes";
353 case MH_OAUTH_RESPONSE_BAD
:
354 base
= "invalid response";
356 case MH_OAUTH_BAD_GRANT
:
357 base
= "bad grant (authorization code or refresh token)";
359 case MH_OAUTH_REQUEST_BAD
:
360 base
= "bad OAuth request; re-run with -snoop and send REDACTED output"
363 case MH_OAUTH_NO_REFRESH
:
364 base
= "no refresh token";
366 case MH_OAUTH_CRED_USER_NOT_FOUND
:
367 base
= "user not found in cred file";
369 case MH_OAUTH_CRED_FILE
:
370 base
= "error loading cred file";
373 base
= "unknown error";
375 if (ctx
->err_details
== NULL
) {
376 return ctx
->err_formatted
= mh_xstrdup(base
);
379 ctx
->err_formatted
= concat(base
, ": ", ctx
->err_details
, NULL
);
380 return ctx
->err_formatted
;
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
)
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
);
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 bool success
= false;
621 char name
[NAMESZ
], value_buf
[BUFSIZ
];
623 m_getfld_state_t getfld_ctx
;
625 struct user_creds
*user_creds
;
627 user_creds
->alloc
= 4;
629 user_creds
->creds
= mh_xmalloc(user_creds
->alloc
* sizeof *user_creds
->creds
);
631 getfld_ctx
= m_getfld_state_init(fp
);
633 int size
= sizeof value_buf
;
634 switch (state
= m_getfld2(&getfld_ctx
, name
, value_buf
, &size
)) {
637 char **save
, *expire
;
638 time_t *expires_at
= NULL
;
639 if (has_prefix(name
, "access-")) {
640 const char *user
= name
+ 7;
641 mh_oauth_cred
*creds
= find_or_alloc_user_creds(user_creds
,
643 save
= &creds
->access_token
;
644 } else if (has_prefix(name
, "refresh-")) {
645 const char *user
= name
+ 8;
646 mh_oauth_cred
*creds
= find_or_alloc_user_creds(user_creds
,
648 save
= &creds
->refresh_token
;
649 } else if (has_prefix(name
, "expire-")) {
650 const char *user
= name
+ 7;
651 mh_oauth_cred
*creds
= find_or_alloc_user_creds(user_creds
,
653 expires_at
= &creds
->expires_at
;
656 set_err_details(ctx
, MH_OAUTH_CRED_FILE
, "unexpected field");
661 *save
= trimcpy(value_buf
);
663 char *tmp
= getcpy(value_buf
);
664 while (state
== FLDPLUS
) {
665 size
= sizeof value_buf
;
666 state
= m_getfld2(&getfld_ctx
, name
, value_buf
, &size
);
667 tmp
= add(value_buf
, tmp
);
669 *save
= trimcpy(tmp
);
672 if (expires_at
!= NULL
) {
674 *expires_at
= strtol(expire
, NULL
, 10);
677 set_err_details(ctx
, MH_OAUTH_CRED_FILE
,
678 "invalid expiration time");
692 /* Not adding details for LENERR/FMTERR because m_getfld2 already
693 * wrote advise message to stderr. */
694 set_err(ctx
, MH_OAUTH_CRED_FILE
);
699 m_getfld_state_destroy(&getfld_ctx
);
702 *result
= user_creds
;
704 free_user_creds(user_creds
);
711 save_user(FILE *fp
, const char *user
, const char *access
, const char *refresh
,
714 if (access
!= NULL
) {
715 if (fprintf(fp
, "access-%s: %s\n", user
, access
) < 0) return false;
717 if (refresh
!= NULL
) {
718 if (fprintf(fp
, "refresh-%s: %s\n", user
, refresh
) < 0) return false;
720 if (expires_at
> 0) {
721 if (fprintf(fp
, "expire-%s: %ld\n", user
, (long)expires_at
) < 0) {
729 mh_oauth_cred_save(FILE *fp
, mh_oauth_cred
*cred
, const char *user
)
731 struct user_creds
*user_creds
;
735 /* Load existing creds if any. */
736 if (!load_creds(&user_creds
, fp
, cred
->ctx
)) {
740 if (fchmod(fd
, S_IRUSR
| S_IWUSR
) < 0) goto err
;
741 if (ftruncate(fd
, 0) < 0) goto err
;
742 if (fseek(fp
, 0, SEEK_SET
) < 0) goto err
;
744 /* Write all creds except for this user. */
745 for (i
= 0; i
< user_creds
->len
; i
++) {
746 mh_oauth_cred
*c
= &user_creds
->creds
[i
];
747 if (strcmp(c
->user
, user
) == 0) continue;
748 if (!save_user(fp
, c
->user
, c
->access_token
, c
->refresh_token
,
754 /* Write updated creds for this user. */
755 if (!save_user(fp
, user
, cred
->access_token
, cred
->refresh_token
,
760 free_user_creds(user_creds
);
765 free_user_creds(user_creds
);
766 set_err(cred
->ctx
, MH_OAUTH_CRED_FILE
);
771 mh_oauth_cred_load(FILE *fp
, mh_oauth_ctx
*ctx
, const char *user
)
773 mh_oauth_cred
*creds
, *result
= NULL
;
774 struct user_creds
*user_creds
;
777 if (!load_creds(&user_creds
, fp
, ctx
)) {
781 /* Search user_creds for this user. If we don't find it, return NULL.
782 * If we do, free fields of all structs except this one, moving this one to
783 * the first struct if necessary. When we return it, it just looks like one
784 * struct to the caller, and the whole array is freed later. */
785 creds
= user_creds
->creds
;
786 for (i
= 0; i
< user_creds
->len
; i
++) {
787 if (strcmp(creds
[i
].user
, user
) == 0) {
790 result
->access_token
= creds
[i
].access_token
;
791 result
->refresh_token
= creds
[i
].refresh_token
;
792 result
->expires_at
= creds
[i
].expires_at
;
795 free(creds
[i
].access_token
);
796 free(creds
[i
].refresh_token
);
801 /* No longer need user_creds. result just uses its creds member. */
804 if (result
== NULL
) {
805 set_err_details(ctx
, MH_OAUTH_CRED_USER_NOT_FOUND
, user
);
816 mh_oauth_sasl_client_response(size_t *res_len
,
817 const char *user
, const mh_oauth_cred
*cred
)
821 p
= &cred
->ctx
->sasl_client_res
;
823 *p
= concat("user=", user
, "\1auth=Bearer ", cred
->access_token
, "\1\1", NULL
);
824 *res_len
= strlen(*p
);
828 /*******************************************************************************
829 * building URLs and making HTTP requests with libcurl
833 * Build null-terminated URL in the array pointed to by s. If the URL doesn't
834 * fit within size (including the terminating null byte), return false without *
835 * building the entire URL. Some of URL may already have been written into the
836 * result array in that case.
839 make_query_url(char *s
, size_t size
, CURL
*curl
, const char *base_url
, ...)
847 if (base_url
== NULL
) {
851 len
= strlen(base_url
);
852 if (len
> size
- 1) /* Less one for NUL. */
858 va_start(ap
, base_url
);
859 for (name
= va_arg(ap
, char *); name
!= NULL
; name
= va_arg(ap
, char *)) {
860 char *name_esc
= curl_easy_escape(curl
, name
, 0);
861 char *val_esc
= curl_easy_escape(curl
, va_arg(ap
, char *), 0);
862 /* prefix + name_esc + '=' + val_esc + '\0' must fit within size */
868 if (new_len
+ 1 > size
) {
873 sprintf(s
+ len
, "%s%s=%s", prefix
, name_esc
, val_esc
);
888 debug_callback(CURL
*handle
, curl_infotype type
, char *data
,
889 size_t size
, void *userptr
)
895 case CURLINFO_HEADER_IN
:
896 case CURLINFO_DATA_IN
:
899 case CURLINFO_HEADER_OUT
:
900 case CURLINFO_DATA_OUT
:
906 fwrite(data
, 1, size
, fp
);
907 if (data
[size
- 1] != '\n') {
915 write_callback(const char *ptr
, size_t size
, size_t nmemb
, void *userdata
)
917 struct curl_ctx
*ctx
= userdata
;
925 new_len
= ctx
->res_len
+ size
;
926 if (new_len
> sizeof ctx
->res_body
) {
931 memcpy(ctx
->res_body
+ ctx
->res_len
, ptr
, size
);
932 ctx
->res_len
= new_len
;
938 post(struct curl_ctx
*ctx
, const char *url
, const char *req_body
)
940 CURL
*curl
= ctx
->curl
;
943 ctx
->too_big
= false;
946 if (ctx
->log
!= NULL
) {
947 curl_easy_setopt(curl
, CURLOPT_VERBOSE
, (long)1);
948 curl_easy_setopt(curl
, CURLOPT_DEBUGFUNCTION
, debug_callback
);
949 curl_easy_setopt(curl
, CURLOPT_DEBUGDATA
, ctx
->log
);
952 if (curl_easy_setopt(curl
, CURLOPT_URL
, url
) != CURLE_OK
) {
956 curl_easy_setopt(curl
, CURLOPT_POSTFIELDS
, req_body
);
957 curl_easy_setopt(curl
, CURLOPT_WRITEFUNCTION
, write_callback
);
958 curl_easy_setopt(curl
, CURLOPT_WRITEDATA
, ctx
);
960 if (has_prefix(url
, "http://127.0.0.1:")) {
961 /* Hack: on Cygwin, curl doesn't fail to connect with ECONNREFUSED.
962 Instead, it waits to timeout. So set a really short timeout, but
963 just on localhost (for convenience of the user, and the test
965 curl_easy_setopt(curl
, CURLOPT_CONNECTTIMEOUT
, 2L);
968 status
= curl_easy_perform(curl
);
969 /* first check for error from callback */
974 if (status
!= CURLE_OK
) {
978 return curl_easy_getinfo(curl
,
979 CURLINFO_RESPONSE_CODE
, &ctx
->res_code
) == CURLE_OK
&&
980 curl_easy_getinfo(curl
,
981 CURLINFO_CONTENT_TYPE
, &ctx
->content_type
) == CURLE_OK
;
984 /*******************************************************************************
988 /* We need 2 for each key/value pair plus 1 for the enclosing object, which
989 * means we only need 9 for Gmail. Clients must not fail if the server returns
990 * more, though, e.g. for protocol extensions. */
991 #define JSMN_TOKENS 16
994 * Parse JSON, store pointer to array of jsmntok_t in tokens.
996 * Returns whether parsing is successful.
998 * Even in that case, tokens has been allocated and must be freed.
1001 parse_json(jsmntok_t
**tokens
, size_t *tokens_len
,
1002 const char *input
, size_t input_len
, FILE *log
)
1007 *tokens_len
= JSMN_TOKENS
;
1008 *tokens
= mh_xmalloc(*tokens_len
* sizeof **tokens
);
1011 while ((r
= jsmn_parse(&p
, input
, input_len
,
1012 *tokens
, *tokens_len
)) == JSMN_ERROR_NOMEM
) {
1013 *tokens_len
= 2 * *tokens_len
;
1015 fprintf(log
, "* need more jsmntok_t! allocating %ld\n",
1018 /* Don't need to limit how much we allocate; we already limited the size
1019 of the response body. */
1020 *tokens
= mh_xrealloc(*tokens
, *tokens_len
* sizeof **tokens
);
1027 * Search input and tokens for the value identified by null-terminated name.
1029 * If found, allocate a null-terminated copy of the value and store the address
1030 * in val. val is left untouched if not found.
1033 get_json_string(char **val
, const char *input
, const jsmntok_t
*tokens
,
1036 /* number of top-level tokens (not counting object/list children) */
1037 int token_count
= tokens
[0].size
* 2;
1038 /* number of tokens to skip when we encounter objects and lists */
1039 /* We only look for top-level strings. */
1040 int skip_tokens
= 0;
1041 /* whether the current token represents a field name */
1042 /* The next token will be the value. */
1046 for (i
= 1; i
<= token_count
; i
++) {
1049 if (tokens
[i
].type
== JSMN_ARRAY
|| tokens
[i
].type
== JSMN_OBJECT
) {
1050 /* We're not interested in any array or object children; skip. */
1051 int children
= tokens
[i
].size
;
1052 if (tokens
[i
].type
== JSMN_OBJECT
) {
1053 /* Object size counts key/value pairs, skip both. */
1056 /* Add children to token_count. */
1057 token_count
+= children
;
1058 if (skip_tokens
== 0) {
1059 /* This token not already skipped; skip it. */
1060 /* Would already be skipped if child of object or list. */
1063 /* Skip this token's children. */
1064 skip_tokens
+= children
;
1066 if (skip_tokens
> 0) {
1068 /* When we finish with the object or list, we'll have a key. */
1076 key
= input
+ tokens
[i
- 1].start
;
1077 key_len
= tokens
[i
- 1].end
- tokens
[i
- 1].start
;
1078 if (strncmp(key
, name
, key_len
) == 0) {
1079 int val_len
= tokens
[i
].end
- tokens
[i
].start
;
1080 *val
= mh_xmalloc(val_len
+ 1);
1081 memcpy(*val
, input
+ tokens
[i
].start
, val_len
);
1082 (*val
)[val_len
] = '\0';
1090 * Parse input as JSON, extracting specified string values.
1092 * Variadic arguments are pairs of null-terminated strings indicating the value
1093 * to extract from the JSON and addresses into which pointers to null-terminated
1094 * copies of the values are written. These must be followed by one NULL pointer
1095 * to indicate the end of pairs.
1097 * The extracted strings are copies which caller must free. If any name is not
1098 * found, the address to store the value is not touched.
1100 * Returns non-zero if parsing is successful.
1102 * When parsing failed, no strings have been copied.
1104 * log may be used for debug-logging if not NULL.
1107 get_json_strings(const char *input
, size_t input_len
, FILE *log
, ...)
1109 bool result
= false;
1115 if (!parse_json(&tokens
, &tokens_len
, input
, input_len
, log
)) {
1119 if (tokens
->type
!= JSMN_OBJECT
|| tokens
->size
== 0) {
1126 for (name
= va_arg(ap
, char *); name
!= NULL
; name
= va_arg(ap
, char *)) {
1127 get_json_string(va_arg(ap
, char **), input
, tokens
, name
);