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.
23 #include <curl/curl.h>
24 #include "thirdparty/jsmn/jsmn.h"
28 #include "lock_file.h"
30 #define JSON_TYPE "application/json"
32 /* We pretend access tokens expire 60 seconds earlier than they actually do to
33 * allow for separate processes to use and refresh access tokens. The process
34 * that uses the access token (post) has an error if the token is expired; the
35 * process that refreshes the access token (send) must have already refreshed if
36 * the expiration is close.
38 * 60s is arbitrary, and hopefully is enough to allow for clock skew.
39 * Currently only Gmail supports XOAUTH2, and seems to always use a token
40 * life-time of 3600s, but that is not guaranteed. It is possible for Gmail to
41 * issue an access token with a life-time so short that even after send
42 * refreshes it, it's already expired when post tries to use it, but that seems
44 #define EXPIRY_FUDGE 60
46 /* maximum size for HTTP response bodies
47 * (not counting header and not null-terminated) */
48 #define RESPONSE_BODY_MAX 8192
50 /* Maximum size for URLs and URI-encoded query strings, null-terminated.
52 * Actual maximum we need is based on the size of tokens (limited by
53 * RESPONSE_BODY_MAX), code user copies from a web page (arbitrarily large), and
54 * various service parameters (all arbitrarily large). In practice, all these
55 * are just tens of bytes. It's not hard to change this to realloc as needed,
56 * but we should still have some limit, so why not this one?
60 struct mh_oauth_cred
{
63 /* opaque access token ([1] 1.4) in null-terminated string */
65 /* opaque refresh token ([1] 1.5) in null-terminated string */
68 /* time at which the access token expires, or 0 if unknown */
71 /* Ignoring token_type ([1] 7.1) because
72 * https://developers.google.com/accounts/docs/OAuth2InstalledApp says
73 * "Currently, this field always has the value Bearer". */
75 /* only filled while loading cred files, otherwise NULL */
80 struct mh_oauth_service_info svc
;
87 char *sasl_client_res
;
90 mh_oauth_err_code err_code
;
92 /* If any detailed message about the error is available, this points to it.
93 * May point to err_buf, or something else. */
94 const char *err_details
;
96 /* Pointer to buffer mh_oauth_err_get_string allocates. */
99 /* Ask libcurl to store errors here. */
100 char err_buf
[CURL_ERROR_SIZE
];
107 /* NULL or a file handle to have curl log diagnostics to */
112 /* Whether the response was too big; if so, the rest of the output fields
116 /* HTTP response code */
119 /* NULL or null-terminated value of Content-Type response header field */
120 const char *content_type
;
122 /* number of bytes in the response body */
125 /* response body; NOT null-terminated */
126 char res_body
[RESPONSE_BODY_MAX
];
129 static bool get_json_strings(const char *, size_t, FILE *, ...) ENDNULL
;
130 static bool make_query_url(char *, size_t, CURL
*, const char *, ...) ENDNULL
;
131 static bool post(struct curl_ctx
*, const char *, const char *);
134 mh_oauth_do_xoauth(const char *user
, const char *svc
, unsigned char **oauth_res
,
135 size_t *oauth_res_len
, FILE *log
)
140 int failed_to_lock
= 0;
144 if (!mh_oauth_new (&ctx
, svc
))
145 die("%s", mh_oauth_get_err_string(ctx
));
147 if (log
!= NULL
) mh_oauth_log_to(stderr
, ctx
);
149 fn
= mh_oauth_cred_fn(svc
);
150 fp
= lkfopendata(fn
, "r+", &failed_to_lock
);
152 if (errno
== ENOENT
) {
153 die("no credentials -- run mhlogin -saslmech xoauth2 -authservice %s", svc
);
155 adios(fn
, "failed to open");
157 if (failed_to_lock
) {
158 adios(fn
, "failed to lock");
161 if ((cred
= mh_oauth_cred_load(fp
, ctx
, user
)) == NULL
) {
162 die("%s", mh_oauth_get_err_string(ctx
));
165 if (!mh_oauth_access_token_valid(time(NULL
), cred
)) {
166 if (!mh_oauth_refresh(cred
)) {
167 if (mh_oauth_get_err_code(ctx
) == MH_OAUTH_NO_REFRESH
) {
168 die("no valid credentials -- run mhlogin -saslmech xoauth2 -authservice %s", svc
);
170 if (mh_oauth_get_err_code(ctx
) == MH_OAUTH_BAD_GRANT
) {
171 die("credentials rejected -- run mhlogin -saslmech xoauth2 -authservice %s", svc
);
173 inform("error refreshing OAuth2 token");
174 die("%s", mh_oauth_get_err_string(ctx
));
177 fseek(fp
, 0, SEEK_SET
);
178 if (!mh_oauth_cred_save(fp
, cred
, user
)) {
179 die("%s", mh_oauth_get_err_string(ctx
));
183 if (lkfclosedata(fp
, fn
) < 0) {
184 adios(fn
, "failed to close");
188 /* XXX writeBase64raw modifies the source buffer! make a copy */
189 client_res
= mh_xstrdup(mh_oauth_sasl_client_response(oauth_res_len
, user
,
191 mh_oauth_cred_free(cred
);
194 *oauth_res
= (unsigned char *) client_res
;
200 is_json(const char *content_type
)
202 return content_type
!= NULL
203 && strncasecmp(content_type
, JSON_TYPE
, LEN(JSON_TYPE
)) == 0;
207 set_err_details(mh_oauth_ctx
*ctx
, mh_oauth_err_code code
, const char *details
)
209 ctx
->err_code
= code
;
210 ctx
->err_details
= details
;
214 set_err(mh_oauth_ctx
*ctx
, mh_oauth_err_code code
)
216 set_err_details(ctx
, code
, NULL
);
220 set_err_http(mh_oauth_ctx
*ctx
, const struct curl_ctx
*curl_ctx
)
223 mh_oauth_err_code code
;
224 /* 5.2. Error Response says error response should use status code 400 and
225 * application/json body. If Content-Type matches, try to parse the body
226 * regardless of the status code. */
227 if (curl_ctx
->res_len
> 0
228 && is_json(curl_ctx
->content_type
)
229 && get_json_strings(curl_ctx
->res_body
, curl_ctx
->res_len
, ctx
->log
,
230 "error", &error
, NULL
)
232 if (strcmp(error
, "invalid_grant") == 0) {
233 code
= MH_OAUTH_BAD_GRANT
;
235 /* All other errors indicate a bug, not anything the user did. */
236 code
= MH_OAUTH_REQUEST_BAD
;
239 code
= MH_OAUTH_RESPONSE_BAD
;
246 make_user_agent(void)
248 const char *curl
= curl_version_info(CURLVERSION_NOW
)->version
;
249 return concat(user_agent
, " libcurl/", curl
, NULL
);
253 mh_oauth_new(mh_oauth_ctx
**result
, const char *svc_name
)
262 ctx
->cred_fn
= ctx
->sasl_client_res
= ctx
->err_formatted
= NULL
;
264 if (!mh_oauth_get_service_info(svc_name
, &ctx
->svc
, ctx
->err_buf
,
265 sizeof(ctx
->err_buf
))) {
266 set_err_details(ctx
, MH_OAUTH_BAD_PROFILE
, ctx
->err_buf
);
270 ctx
->curl
= curl_easy_init();
271 if (ctx
->curl
== NULL
) {
272 set_err(ctx
, MH_OAUTH_CURL_INIT
);
275 curl_easy_setopt(ctx
->curl
, CURLOPT_ERRORBUFFER
, ctx
->err_buf
);
277 ctx
->user_agent
= make_user_agent();
279 if (curl_easy_setopt(ctx
->curl
, CURLOPT_USERAGENT
,
280 ctx
->user_agent
) != CURLE_OK
) {
281 set_err_details(ctx
, MH_OAUTH_CURL_INIT
, ctx
->err_buf
);
289 mh_oauth_free(mh_oauth_ctx
*ctx
)
292 free(ctx
->svc
.scope
);
293 free(ctx
->svc
.client_id
);
294 free(ctx
->svc
.client_secret
);
295 free(ctx
->svc
.auth_endpoint
);
296 free(ctx
->svc
.token_endpoint
);
297 free(ctx
->svc
.redirect_uri
);
299 free(ctx
->sasl_client_res
);
300 free(ctx
->err_formatted
);
301 free(ctx
->user_agent
);
303 if (ctx
->curl
!= NULL
) {
304 curl_easy_cleanup(ctx
->curl
);
310 mh_oauth_svc_display_name(const mh_oauth_ctx
*ctx
)
312 return ctx
->svc
.display_name
;
316 mh_oauth_log_to(FILE *log
, mh_oauth_ctx
*ctx
)
322 mh_oauth_get_err_code(const mh_oauth_ctx
*ctx
)
324 return ctx
->err_code
;
328 mh_oauth_get_err_string(mh_oauth_ctx
*ctx
)
332 free(ctx
->err_formatted
);
334 switch (ctx
->err_code
) {
335 case MH_OAUTH_BAD_PROFILE
:
336 base
= "incomplete OAuth2 service definition";
338 case MH_OAUTH_CURL_INIT
:
339 base
= "error initializing libcurl";
341 case MH_OAUTH_REQUEST_INIT
:
342 base
= "local error initializing HTTP request";
345 base
= "error making HTTP request to OAuth2 authorization endpoint";
347 case MH_OAUTH_RESPONSE_TOO_BIG
:
348 base
= "refusing to process response body larger than 8192 bytes";
350 case MH_OAUTH_RESPONSE_BAD
:
351 base
= "invalid response";
353 case MH_OAUTH_BAD_GRANT
:
354 base
= "bad grant (authorization code or refresh token)";
356 case MH_OAUTH_REQUEST_BAD
:
357 base
= "bad OAuth request; re-run with -snoop and send REDACTED output"
360 case MH_OAUTH_NO_REFRESH
:
361 base
= "no refresh token";
363 case MH_OAUTH_CRED_USER_NOT_FOUND
:
364 base
= "user not found in cred file";
366 case MH_OAUTH_CRED_FILE
:
367 base
= "error loading cred file";
370 base
= "unknown error";
372 if (ctx
->err_details
== NULL
) {
373 return ctx
->err_formatted
= mh_xstrdup(base
);
376 ctx
->err_formatted
= concat(base
, ": ", ctx
->err_details
, NULL
);
377 return ctx
->err_formatted
;
381 mh_oauth_get_authorize_url(mh_oauth_ctx
*ctx
)
383 /* [1] 4.1.1 Authorization Request */
384 if (!make_query_url(ctx
->buf
, sizeof ctx
->buf
, ctx
->curl
,
385 ctx
->svc
.auth_endpoint
,
386 "response_type", "code",
387 "client_id", ctx
->svc
.client_id
,
388 "redirect_uri", ctx
->svc
.redirect_uri
,
389 "scope", ctx
->svc
.scope
,
391 set_err(ctx
, MH_OAUTH_REQUEST_INIT
);
398 cred_from_response(mh_oauth_cred
*cred
, const char *content_type
,
399 const char *input
, size_t input_len
)
402 char *access_token
, *expires_in
, *refresh_token
;
403 const mh_oauth_ctx
*ctx
= cred
->ctx
;
405 if (!is_json(content_type
)) {
409 access_token
= expires_in
= refresh_token
= NULL
;
410 if (!get_json_strings(input
, input_len
, ctx
->log
,
411 "access_token", &access_token
,
412 "expires_in", &expires_in
,
413 "refresh_token", &refresh_token
,
418 if (access_token
== NULL
) {
419 /* Response is invalid, but if it has a refresh token, we can try. */
420 if (refresh_token
== NULL
) {
427 free(cred
->access_token
);
428 cred
->access_token
= access_token
;
431 cred
->expires_at
= 0;
432 if (expires_in
!= NULL
) {
435 e
= strtol(expires_in
, NULL
, 10);
438 cred
->expires_at
= time(NULL
) + e
;
440 } else if (ctx
->log
!= NULL
) {
441 fprintf(ctx
->log
, "* invalid expiration: %s\n", expires_in
);
445 /* [1] 6 Refreshing an Access Token says a new refresh token may be issued
446 * in refresh responses. */
447 if (refresh_token
!= NULL
) {
448 free(cred
->refresh_token
);
449 cred
->refresh_token
= refresh_token
;
450 refresh_token
= NULL
;
461 do_access_request(mh_oauth_cred
*cred
, const char *req_body
)
463 mh_oauth_ctx
*ctx
= cred
->ctx
;
464 struct curl_ctx curl_ctx
;
466 curl_ctx
.curl
= ctx
->curl
;
467 curl_ctx
.log
= ctx
->log
;
468 if (!post(&curl_ctx
, ctx
->svc
.token_endpoint
, req_body
)) {
469 if (curl_ctx
.too_big
) {
470 set_err(ctx
, MH_OAUTH_RESPONSE_TOO_BIG
);
472 set_err_details(ctx
, MH_OAUTH_POST
, ctx
->err_buf
);
477 if (curl_ctx
.res_code
!= 200) {
478 set_err_http(ctx
, &curl_ctx
);
482 if (!cred_from_response(cred
, curl_ctx
.content_type
, curl_ctx
.res_body
,
484 set_err(ctx
, MH_OAUTH_RESPONSE_BAD
);
492 mh_oauth_authorize(const char *code
, mh_oauth_ctx
*ctx
)
494 mh_oauth_cred
*result
;
496 if (!make_query_url(ctx
->buf
, sizeof ctx
->buf
, ctx
->curl
, NULL
,
498 "grant_type", "authorization_code",
499 "redirect_uri", ctx
->svc
.redirect_uri
,
500 "client_id", ctx
->svc
.client_id
,
501 "client_secret", ctx
->svc
.client_secret
,
503 set_err(ctx
, MH_OAUTH_REQUEST_INIT
);
509 result
->access_token
= result
->refresh_token
= NULL
;
511 if (!do_access_request(result
, ctx
->buf
)) {
520 mh_oauth_refresh(mh_oauth_cred
*cred
)
523 mh_oauth_ctx
*ctx
= cred
->ctx
;
525 if (cred
->refresh_token
== NULL
) {
526 set_err(ctx
, MH_OAUTH_NO_REFRESH
);
530 if (!make_query_url(ctx
->buf
, sizeof ctx
->buf
, ctx
->curl
, NULL
,
531 "grant_type", "refresh_token",
532 "refresh_token", cred
->refresh_token
,
533 "client_id", ctx
->svc
.client_id
,
534 "client_secret", ctx
->svc
.client_secret
,
536 set_err(ctx
, MH_OAUTH_REQUEST_INIT
);
540 result
= do_access_request(cred
, ctx
->buf
);
542 if (result
&& cred
->access_token
== NULL
) {
543 set_err_details(ctx
, MH_OAUTH_RESPONSE_BAD
, "no access token");
551 mh_oauth_access_token_valid(time_t t
, const mh_oauth_cred
*cred
)
553 return cred
->access_token
!= NULL
&& t
+ EXPIRY_FUDGE
< cred
->expires_at
;
557 mh_oauth_cred_free(mh_oauth_cred
*cred
)
559 free(cred
->refresh_token
);
560 free(cred
->access_token
);
564 /* for loading multi-user cred files */
566 mh_oauth_cred
*creds
;
568 /* number of allocated mh_oauth_cred structs above points to */
571 /* number that are actually filled in and used */
575 /* If user has an entry in user_creds, return pointer to it. Else allocate a
576 * new struct in user_creds and return pointer to that. */
577 static mh_oauth_cred
*
578 find_or_alloc_user_creds(struct user_creds user_creds
[], const char *user
)
580 mh_oauth_cred
*creds
= user_creds
->creds
;
582 for (i
= 0; i
< user_creds
->len
; i
++) {
583 if (strcmp(creds
[i
].user
, user
) == 0) {
587 if (user_creds
->alloc
== user_creds
->len
) {
588 user_creds
->alloc
*= 2;
589 user_creds
->creds
= mh_xrealloc(user_creds
->creds
, user_creds
->alloc
);
591 creds
= user_creds
->creds
+user_creds
->len
;
593 creds
->user
= getcpy(user
);
594 creds
->access_token
= creds
->refresh_token
= NULL
;
595 creds
->expires_at
= 0;
600 free_user_creds(struct user_creds
*user_creds
)
604 cred
= user_creds
->creds
;
605 for (i
= 0; i
< user_creds
->len
; i
++) {
607 free(cred
[i
].access_token
);
608 free(cred
[i
].refresh_token
);
610 free(user_creds
->creds
);
615 load_creds(struct user_creds
**result
, FILE *fp
, mh_oauth_ctx
*ctx
)
617 bool success
= false;
618 char name
[NAMESZ
], value_buf
[BUFSIZ
];
620 m_getfld_state_t getfld_ctx
;
622 struct user_creds
*user_creds
;
624 user_creds
->alloc
= 4;
626 user_creds
->creds
= mh_xmalloc(user_creds
->alloc
* sizeof *user_creds
->creds
);
628 getfld_ctx
= m_getfld_state_init(fp
);
630 int size
= sizeof value_buf
;
631 switch (state
= m_getfld2(&getfld_ctx
, name
, value_buf
, &size
)) {
634 char **save
, *expire
;
635 time_t *expires_at
= NULL
;
636 if (has_prefix(name
, "access-")) {
637 const char *user
= name
+ 7;
638 mh_oauth_cred
*creds
= find_or_alloc_user_creds(user_creds
,
640 save
= &creds
->access_token
;
641 } else if (has_prefix(name
, "refresh-")) {
642 const char *user
= name
+ 8;
643 mh_oauth_cred
*creds
= find_or_alloc_user_creds(user_creds
,
645 save
= &creds
->refresh_token
;
646 } else if (has_prefix(name
, "expire-")) {
647 const char *user
= name
+ 7;
648 mh_oauth_cred
*creds
= find_or_alloc_user_creds(user_creds
,
650 expires_at
= &creds
->expires_at
;
653 set_err_details(ctx
, MH_OAUTH_CRED_FILE
, "unexpected field");
658 *save
= trimcpy(value_buf
);
660 char *tmp
= getcpy(value_buf
);
661 while (state
== FLDPLUS
) {
662 size
= sizeof value_buf
;
663 state
= m_getfld2(&getfld_ctx
, name
, value_buf
, &size
);
664 tmp
= add(value_buf
, tmp
);
666 *save
= trimcpy(tmp
);
669 if (expires_at
!= NULL
) {
671 *expires_at
= strtol(expire
, NULL
, 10);
674 set_err_details(ctx
, MH_OAUTH_CRED_FILE
,
675 "invalid expiration time");
689 /* Not adding details for LENERR/FMTERR because m_getfld2 already
690 * wrote advise message to stderr. */
691 set_err(ctx
, MH_OAUTH_CRED_FILE
);
696 m_getfld_state_destroy(&getfld_ctx
);
699 *result
= user_creds
;
701 free_user_creds(user_creds
);
708 save_user(FILE *fp
, const char *user
, const char *access
, const char *refresh
,
711 if (access
!= NULL
) {
712 if (fprintf(fp
, "access-%s: %s\n", user
, access
) < 0) return false;
714 if (refresh
!= NULL
) {
715 if (fprintf(fp
, "refresh-%s: %s\n", user
, refresh
) < 0) return false;
717 if (expires_at
> 0) {
718 if (fprintf(fp
, "expire-%s: %ld\n", user
, (long)expires_at
) < 0) {
726 mh_oauth_cred_save(FILE *fp
, mh_oauth_cred
*cred
, const char *user
)
728 struct user_creds
*user_creds
;
732 /* Load existing creds if any. */
733 if (!load_creds(&user_creds
, fp
, cred
->ctx
)) {
737 if (fchmod(fd
, S_IRUSR
| S_IWUSR
) < 0) goto err
;
738 if (ftruncate(fd
, 0) < 0) goto err
;
739 if (fseek(fp
, 0, SEEK_SET
) < 0) goto err
;
741 /* Write all creds except for this user. */
742 for (i
= 0; i
< user_creds
->len
; i
++) {
743 mh_oauth_cred
*c
= &user_creds
->creds
[i
];
744 if (strcmp(c
->user
, user
) == 0) continue;
745 if (!save_user(fp
, c
->user
, c
->access_token
, c
->refresh_token
,
751 /* Write updated creds for this user. */
752 if (!save_user(fp
, user
, cred
->access_token
, cred
->refresh_token
,
757 free_user_creds(user_creds
);
762 free_user_creds(user_creds
);
763 set_err(cred
->ctx
, MH_OAUTH_CRED_FILE
);
768 mh_oauth_cred_load(FILE *fp
, mh_oauth_ctx
*ctx
, const char *user
)
770 mh_oauth_cred
*creds
, *result
= NULL
;
771 struct user_creds
*user_creds
;
774 if (!load_creds(&user_creds
, fp
, ctx
)) {
778 /* Search user_creds for this user. If we don't find it, return NULL.
779 * If we do, free fields of all structs except this one, moving this one to
780 * the first struct if necessary. When we return it, it just looks like one
781 * struct to the caller, and the whole array is freed later. */
782 creds
= user_creds
->creds
;
783 for (i
= 0; i
< user_creds
->len
; i
++) {
784 if (strcmp(creds
[i
].user
, user
) == 0) {
787 result
->access_token
= creds
[i
].access_token
;
788 result
->refresh_token
= creds
[i
].refresh_token
;
789 result
->expires_at
= creds
[i
].expires_at
;
792 free(creds
[i
].access_token
);
793 free(creds
[i
].refresh_token
);
798 /* No longer need user_creds. result just uses its creds member. */
801 if (result
== NULL
) {
802 set_err_details(ctx
, MH_OAUTH_CRED_USER_NOT_FOUND
, user
);
813 mh_oauth_sasl_client_response(size_t *res_len
,
814 const char *user
, const mh_oauth_cred
*cred
)
818 p
= &cred
->ctx
->sasl_client_res
;
820 *p
= concat("user=", user
, "\1auth=Bearer ", cred
->access_token
, "\1\1", NULL
);
821 *res_len
= strlen(*p
);
825 /*******************************************************************************
826 * building URLs and making HTTP requests with libcurl
830 * Build null-terminated URL in the array pointed to by s. If the URL doesn't
831 * fit within size (including the terminating null byte), return false without *
832 * building the entire URL. Some of URL may already have been written into the
833 * result array in that case.
836 make_query_url(char *s
, size_t size
, CURL
*curl
, const char *base_url
, ...)
844 if (base_url
== NULL
) {
848 len
= strlen(base_url
);
849 if (len
> size
- 1) /* Less one for NUL. */
855 va_start(ap
, base_url
);
856 for (name
= va_arg(ap
, char *); name
!= NULL
; name
= va_arg(ap
, char *)) {
857 char *name_esc
= curl_easy_escape(curl
, name
, 0);
858 char *val_esc
= curl_easy_escape(curl
, va_arg(ap
, char *), 0);
859 /* prefix + name_esc + '=' + val_esc + '\0' must fit within size */
865 if (new_len
+ 1 > size
) {
870 sprintf(s
+ len
, "%s%s=%s", prefix
, name_esc
, val_esc
);
885 debug_callback(CURL
*handle
, curl_infotype type
, char *data
,
886 size_t size
, void *userptr
)
892 case CURLINFO_HEADER_IN
:
893 case CURLINFO_DATA_IN
:
896 case CURLINFO_HEADER_OUT
:
897 case CURLINFO_DATA_OUT
:
903 fwrite(data
, 1, size
, fp
);
904 if (data
[size
- 1] != '\n') {
912 write_callback(const char *ptr
, size_t size
, size_t nmemb
, void *userdata
)
914 struct curl_ctx
*ctx
= userdata
;
922 new_len
= ctx
->res_len
+ size
;
923 if (new_len
> sizeof ctx
->res_body
) {
928 memcpy(ctx
->res_body
+ ctx
->res_len
, ptr
, size
);
929 ctx
->res_len
= new_len
;
935 post(struct curl_ctx
*ctx
, const char *url
, const char *req_body
)
937 CURL
*curl
= ctx
->curl
;
940 ctx
->too_big
= false;
943 if (ctx
->log
!= NULL
) {
944 curl_easy_setopt(curl
, CURLOPT_VERBOSE
, (long)1);
945 curl_easy_setopt(curl
, CURLOPT_DEBUGFUNCTION
, debug_callback
);
946 curl_easy_setopt(curl
, CURLOPT_DEBUGDATA
, ctx
->log
);
949 if (curl_easy_setopt(curl
, CURLOPT_URL
, url
) != CURLE_OK
) {
953 curl_easy_setopt(curl
, CURLOPT_POSTFIELDS
, req_body
);
954 curl_easy_setopt(curl
, CURLOPT_WRITEFUNCTION
, write_callback
);
955 curl_easy_setopt(curl
, CURLOPT_WRITEDATA
, ctx
);
957 if (has_prefix(url
, "http://127.0.0.1:")) {
958 /* Hack: on Cygwin, curl doesn't fail to connect with ECONNREFUSED.
959 Instead, it waits to timeout. So set a really short timeout, but
960 just on localhost (for convenience of the user, and the test
962 curl_easy_setopt(curl
, CURLOPT_CONNECTTIMEOUT
, 2L);
965 status
= curl_easy_perform(curl
);
966 /* first check for error from callback */
971 if (status
!= CURLE_OK
) {
975 return curl_easy_getinfo(curl
,
976 CURLINFO_RESPONSE_CODE
, &ctx
->res_code
) == CURLE_OK
&&
977 curl_easy_getinfo(curl
,
978 CURLINFO_CONTENT_TYPE
, &ctx
->content_type
) == CURLE_OK
;
981 /*******************************************************************************
985 /* We need 2 for each key/value pair plus 1 for the enclosing object, which
986 * means we only need 9 for Gmail. Clients must not fail if the server returns
987 * more, though, e.g. for protocol extensions. */
988 #define JSMN_TOKENS 16
991 * Parse JSON, store pointer to array of jsmntok_t in tokens.
993 * Returns whether parsing is successful.
995 * Even in that case, tokens has been allocated and must be freed.
998 parse_json(jsmntok_t
**tokens
, size_t *tokens_len
,
999 const char *input
, size_t input_len
, FILE *log
)
1004 *tokens_len
= JSMN_TOKENS
;
1005 *tokens
= mh_xmalloc(*tokens_len
* sizeof **tokens
);
1008 while ((r
= jsmn_parse(&p
, input
, input_len
,
1009 *tokens
, *tokens_len
)) == JSMN_ERROR_NOMEM
) {
1010 *tokens_len
= 2 * *tokens_len
;
1012 fprintf(log
, "* need more jsmntok_t! allocating %ld\n",
1015 /* Don't need to limit how much we allocate; we already limited the size
1016 of the response body. */
1017 *tokens
= mh_xrealloc(*tokens
, *tokens_len
* sizeof **tokens
);
1024 * Search input and tokens for the value identified by null-terminated name.
1026 * If found, allocate a null-terminated copy of the value and store the address
1027 * in val. val is left untouched if not found.
1030 get_json_string(char **val
, const char *input
, const jsmntok_t
*tokens
,
1033 /* number of top-level tokens (not counting object/list children) */
1034 int token_count
= tokens
[0].size
* 2;
1035 /* number of tokens to skip when we encounter objects and lists */
1036 /* We only look for top-level strings. */
1037 int skip_tokens
= 0;
1038 /* whether the current token represents a field name */
1039 /* The next token will be the value. */
1043 for (i
= 1; i
<= token_count
; i
++) {
1046 if (tokens
[i
].type
== JSMN_ARRAY
|| tokens
[i
].type
== JSMN_OBJECT
) {
1047 /* We're not interested in any array or object children; skip. */
1048 int children
= tokens
[i
].size
;
1049 if (tokens
[i
].type
== JSMN_OBJECT
) {
1050 /* Object size counts key/value pairs, skip both. */
1053 /* Add children to token_count. */
1054 token_count
+= children
;
1055 if (skip_tokens
== 0) {
1056 /* This token not already skipped; skip it. */
1057 /* Would already be skipped if child of object or list. */
1060 /* Skip this token's children. */
1061 skip_tokens
+= children
;
1063 if (skip_tokens
> 0) {
1065 /* When we finish with the object or list, we'll have a key. */
1073 key
= input
+ tokens
[i
- 1].start
;
1074 key_len
= tokens
[i
- 1].end
- tokens
[i
- 1].start
;
1075 if (strncmp(key
, name
, key_len
) == 0) {
1076 int val_len
= tokens
[i
].end
- tokens
[i
].start
;
1077 *val
= mh_xmalloc(val_len
+ 1);
1078 memcpy(*val
, input
+ tokens
[i
].start
, val_len
);
1079 (*val
)[val_len
] = '\0';
1087 * Parse input as JSON, extracting specified string values.
1089 * Variadic arguments are pairs of null-terminated strings indicating the value
1090 * to extract from the JSON and addresses into which pointers to null-terminated
1091 * copies of the values are written. These must be followed by one NULL pointer
1092 * to indicate the end of pairs.
1094 * The extracted strings are copies which caller must free. If any name is not
1095 * found, the address to store the value is not touched.
1097 * Returns non-zero if parsing is successful.
1099 * When parsing failed, no strings have been copied.
1101 * log may be used for debug-logging if not NULL.
1104 get_json_strings(const char *input
, size_t input_len
, FILE *log
, ...)
1106 bool result
= false;
1112 if (!parse_json(&tokens
, &tokens_len
, input
, input_len
, log
)) {
1116 if (tokens
->type
!= JSMN_OBJECT
|| tokens
->size
== 0) {
1123 for (name
= va_arg(ap
, char *); name
!= NULL
; name
= va_arg(ap
, char *)) {
1124 get_json_string(va_arg(ap
, char **), input
, tokens
, name
);