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 30 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 * 30s 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 /* Maxium 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
, FILE *log
)
136 int failed_to_lock
= 0;
138 size_t client_res_len
;
140 char *client_res_b64
;
142 if (!mh_oauth_new (&ctx
, svc
)) adios(NULL
, mh_oauth_get_err_string(ctx
));
144 if (log
!= NULL
) mh_oauth_log_to(stderr
, ctx
);
146 fn
= getcpy(mh_oauth_cred_fn(svc
));
147 fp
= lkfopendata(fn
, "r+", &failed_to_lock
);
149 if (errno
== ENOENT
) {
150 adios(NULL
, "no credentials -- run mhlogin -saslmech xoauth2 -authservice %s", svc
);
152 adios(fn
, "failed to open");
154 if (failed_to_lock
) {
155 adios(fn
, "failed to lock");
158 if ((cred
= mh_oauth_cred_load(fp
, ctx
, user
)) == NULL
) {
159 adios(NULL
, mh_oauth_get_err_string(ctx
));
162 if (!mh_oauth_access_token_valid(time(NULL
), cred
)) {
163 if (!mh_oauth_refresh(cred
)) {
164 if (mh_oauth_get_err_code(ctx
) == MH_OAUTH_NO_REFRESH
) {
165 adios(NULL
, "no valid credentials -- run mhlogin -saslmech xoauth2 -authservice %s", svc
);
167 if (mh_oauth_get_err_code(ctx
) == MH_OAUTH_BAD_GRANT
) {
168 adios(NULL
, "credentials rejected -- run mhlogin -saslmech xoauth2 -authservice %s", svc
);
170 advise(NULL
, "error refreshing OAuth2 token");
171 adios(NULL
, mh_oauth_get_err_string(ctx
));
174 fseek(fp
, 0, SEEK_SET
);
175 if (!mh_oauth_cred_save(fp
, cred
, user
)) {
176 adios(NULL
, mh_oauth_get_err_string(ctx
));
180 if (lkfclosedata(fp
, fn
) < 0) {
181 adios(fn
, "failed to close");
185 /* XXX writeBase64raw modifies the source buffer! make a copy */
186 client_res
= getcpy(mh_oauth_sasl_client_response(&client_res_len
, user
,
188 mh_oauth_cred_free(cred
);
190 client_res_b64
= mh_xmalloc(((((client_res_len
) + 2) / 3 ) * 4) + 1);
191 if (writeBase64raw((unsigned char *)client_res
, client_res_len
,
192 (unsigned char *)client_res_b64
) != OK
) {
193 adios(NULL
, "base64 encoding of XOAUTH2 client response failed");
197 return client_res_b64
;
201 is_json(const char *content_type
)
203 return content_type
!= NULL
204 && strncasecmp(content_type
, JSON_TYPE
, sizeof JSON_TYPE
- 1) == 0;
208 set_err_details(mh_oauth_ctx
*ctx
, mh_oauth_err_code code
, const char *details
)
210 ctx
->err_code
= code
;
211 ctx
->err_details
= details
;
215 set_err(mh_oauth_ctx
*ctx
, mh_oauth_err_code code
)
217 set_err_details(ctx
, code
, NULL
);
221 set_err_http(mh_oauth_ctx
*ctx
, const struct curl_ctx
*curl_ctx
)
224 mh_oauth_err_code code
;
225 /* 5.2. Error Response says error response should use status code 400 and
226 * application/json body. If Content-Type matches, try to parse the body
227 * regardless of the status code. */
228 if (curl_ctx
->res_len
> 0
229 && is_json(curl_ctx
->content_type
)
230 && get_json_strings(curl_ctx
->res_body
, curl_ctx
->res_len
, ctx
->log
,
231 "error", &error
, (void *)NULL
)
233 if (strcmp(error
, "invalid_grant") == 0) {
234 code
= MH_OAUTH_BAD_GRANT
;
236 /* All other errors indicate a bug, not anything the user did. */
237 code
= MH_OAUTH_REQUEST_BAD
;
240 code
= MH_OAUTH_RESPONSE_BAD
;
249 const char *curl
= curl_version_info(CURLVERSION_NOW
)->version
;
250 char *s
= mh_xmalloc(strlen(user_agent
)
256 sprintf(s
, "%s libcurl/%s", user_agent
, curl
);
261 mh_oauth_new(mh_oauth_ctx
**result
, const char *svc_name
)
263 mh_oauth_ctx
*ctx
= *result
= mh_xmalloc(sizeof *ctx
);
268 ctx
->cred_fn
= ctx
->sasl_client_res
= ctx
->err_formatted
= NULL
;
270 if (!mh_oauth_get_service_info(svc_name
, &ctx
->svc
, ctx
->err_buf
,
271 sizeof(ctx
->err_buf
))) {
272 set_err_details(ctx
, MH_OAUTH_BAD_PROFILE
, ctx
->err_buf
);
276 ctx
->curl
= curl_easy_init();
277 if (ctx
->curl
== NULL
) {
278 set_err(ctx
, MH_OAUTH_CURL_INIT
);
281 curl_easy_setopt(ctx
->curl
, CURLOPT_ERRORBUFFER
, ctx
->err_buf
);
283 ctx
->user_agent
= make_user_agent();
285 if (curl_easy_setopt(ctx
->curl
, CURLOPT_USERAGENT
,
286 ctx
->user_agent
) != CURLE_OK
) {
287 set_err_details(ctx
, MH_OAUTH_CURL_INIT
, ctx
->err_buf
);
295 mh_oauth_free(mh_oauth_ctx
*ctx
)
298 free(ctx
->svc
.scope
);
299 free(ctx
->svc
.client_id
);
300 free(ctx
->svc
.client_secret
);
301 free(ctx
->svc
.auth_endpoint
);
302 free(ctx
->svc
.token_endpoint
);
303 free(ctx
->svc
.redirect_uri
);
305 free(ctx
->sasl_client_res
);
306 free(ctx
->err_formatted
);
307 free(ctx
->user_agent
);
309 if (ctx
->curl
!= NULL
) {
310 curl_easy_cleanup(ctx
->curl
);
316 mh_oauth_svc_display_name(const mh_oauth_ctx
*ctx
)
318 return ctx
->svc
.display_name
;
322 mh_oauth_log_to(FILE *log
, mh_oauth_ctx
*ctx
)
328 mh_oauth_get_err_code(const mh_oauth_ctx
*ctx
)
330 return ctx
->err_code
;
334 mh_oauth_get_err_string(mh_oauth_ctx
*ctx
)
339 free(ctx
->err_formatted
);
341 switch (ctx
->err_code
) {
342 case MH_OAUTH_BAD_PROFILE
:
343 base
= "incomplete OAuth2 service definition";
345 case MH_OAUTH_CURL_INIT
:
346 base
= "error initializing libcurl";
348 case MH_OAUTH_REQUEST_INIT
:
349 base
= "local error initializing HTTP request";
352 base
= "error making HTTP request to OAuth2 authorization endpoint";
354 case MH_OAUTH_RESPONSE_TOO_BIG
:
355 base
= "refusing to process response body larger than 8192 bytes";
357 case MH_OAUTH_RESPONSE_BAD
:
358 base
= "invalid response";
360 case MH_OAUTH_BAD_GRANT
:
361 base
= "bad grant (authorization code or refresh token)";
363 case MH_OAUTH_REQUEST_BAD
:
364 base
= "bad OAuth request; re-run with -snoop and send REDACTED output"
367 case MH_OAUTH_NO_REFRESH
:
368 base
= "no refresh token";
370 case MH_OAUTH_CRED_USER_NOT_FOUND
:
371 base
= "user not found in cred file";
373 case MH_OAUTH_CRED_FILE
:
374 base
= "error loading cred file";
377 base
= "unknown error";
379 if (ctx
->err_details
== NULL
) {
380 return ctx
->err_formatted
= getcpy(base
);
382 /* length of the two strings plus ": " and '\0' */
383 result
= mh_xmalloc(strlen(base
) + strlen(ctx
->err_details
) + 3);
384 sprintf(result
, "%s: %s", base
, ctx
->err_details
);
385 return ctx
->err_formatted
= result
;
389 mh_oauth_get_authorize_url(mh_oauth_ctx
*ctx
)
391 /* [1] 4.1.1 Authorization Request */
392 if (!make_query_url(ctx
->buf
, sizeof ctx
->buf
, ctx
->curl
,
393 ctx
->svc
.auth_endpoint
,
394 "response_type", "code",
395 "client_id", ctx
->svc
.client_id
,
396 "redirect_uri", ctx
->svc
.redirect_uri
,
397 "scope", ctx
->svc
.scope
,
399 set_err(ctx
, MH_OAUTH_REQUEST_INIT
);
406 cred_from_response(mh_oauth_cred
*cred
, const char *content_type
,
407 const char *input
, size_t input_len
)
409 boolean result
= FALSE
;
410 char *access_token
, *expires_in
, *refresh_token
;
411 const mh_oauth_ctx
*ctx
= cred
->ctx
;
413 if (!is_json(content_type
)) {
417 access_token
= expires_in
= refresh_token
= NULL
;
418 if (!get_json_strings(input
, input_len
, ctx
->log
,
419 "access_token", &access_token
,
420 "expires_in", &expires_in
,
421 "refresh_token", &refresh_token
,
426 if (access_token
== NULL
) {
427 /* Response is invalid, but if it has a refresh token, we can try. */
428 if (refresh_token
== NULL
) {
435 free(cred
->access_token
);
436 cred
->access_token
= access_token
;
439 cred
->expires_at
= 0;
440 if (expires_in
!= NULL
) {
443 e
= strtol(expires_in
, NULL
, 10);
446 cred
->expires_at
= time(NULL
) + e
;
448 } else if (ctx
->log
!= NULL
) {
449 fprintf(ctx
->log
, "* invalid expiration: %s\n", expires_in
);
453 /* [1] 6 Refreshing an Access Token says a new refresh token may be issued
454 * in refresh responses. */
455 if (refresh_token
!= NULL
) {
456 free(cred
->refresh_token
);
457 cred
->refresh_token
= refresh_token
;
458 refresh_token
= NULL
;
469 do_access_request(mh_oauth_cred
*cred
, const char *req_body
)
471 mh_oauth_ctx
*ctx
= cred
->ctx
;
472 struct curl_ctx curl_ctx
;
474 curl_ctx
.curl
= ctx
->curl
;
475 curl_ctx
.log
= ctx
->log
;
476 if (!post(&curl_ctx
, ctx
->svc
.token_endpoint
, req_body
)) {
477 if (curl_ctx
.too_big
) {
478 set_err(ctx
, MH_OAUTH_RESPONSE_TOO_BIG
);
480 set_err_details(ctx
, MH_OAUTH_POST
, ctx
->err_buf
);
485 if (curl_ctx
.res_code
!= 200) {
486 set_err_http(ctx
, &curl_ctx
);
490 if (!cred_from_response(cred
, curl_ctx
.content_type
, curl_ctx
.res_body
,
492 set_err(ctx
, MH_OAUTH_RESPONSE_BAD
);
500 mh_oauth_authorize(const char *code
, mh_oauth_ctx
*ctx
)
502 mh_oauth_cred
*result
;
504 if (!make_query_url(ctx
->buf
, sizeof ctx
->buf
, ctx
->curl
, NULL
,
506 "grant_type", "authorization_code",
507 "redirect_uri", ctx
->svc
.redirect_uri
,
508 "client_id", ctx
->svc
.client_id
,
509 "client_secret", ctx
->svc
.client_secret
,
511 set_err(ctx
, MH_OAUTH_REQUEST_INIT
);
515 result
= mh_xmalloc(sizeof *result
);
517 result
->access_token
= result
->refresh_token
= NULL
;
519 if (!do_access_request(result
, ctx
->buf
)) {
528 mh_oauth_refresh(mh_oauth_cred
*cred
)
531 mh_oauth_ctx
*ctx
= cred
->ctx
;
533 if (cred
->refresh_token
== NULL
) {
534 set_err(ctx
, MH_OAUTH_NO_REFRESH
);
538 if (!make_query_url(ctx
->buf
, sizeof ctx
->buf
, ctx
->curl
, NULL
,
539 "grant_type", "refresh_token",
540 "refresh_token", cred
->refresh_token
,
541 "client_id", ctx
->svc
.client_id
,
542 "client_secret", ctx
->svc
.client_secret
,
544 set_err(ctx
, MH_OAUTH_REQUEST_INIT
);
548 result
= do_access_request(cred
, ctx
->buf
);
550 if (result
&& cred
->access_token
== NULL
) {
551 set_err_details(ctx
, MH_OAUTH_RESPONSE_BAD
, "no access token");
559 mh_oauth_access_token_valid(time_t t
, const mh_oauth_cred
*cred
)
561 return cred
->access_token
!= NULL
&& t
+ EXPIRY_FUDGE
< cred
->expires_at
;
565 mh_oauth_cred_free(mh_oauth_cred
*cred
)
567 free(cred
->refresh_token
);
568 free(cred
->access_token
);
572 /* for loading multi-user cred files */
574 mh_oauth_cred
*creds
;
576 /* number of allocated mh_oauth_cred structs above points to */
579 /* number that are actually filled in and used */
583 /* If user has an entry in user_creds, return pointer to it. Else allocate a
584 * new struct in user_creds and return pointer to that. */
585 static mh_oauth_cred
*
586 find_or_alloc_user_creds(struct user_creds user_creds
[], const char *user
)
588 mh_oauth_cred
*creds
= user_creds
->creds
;
590 for (i
= 0; i
< user_creds
->len
; i
++) {
591 if (strcmp(creds
[i
].user
, user
) == 0) {
595 if (user_creds
->alloc
== user_creds
->len
) {
596 user_creds
->alloc
*= 2;
597 user_creds
->creds
= mh_xrealloc(user_creds
->creds
, user_creds
->alloc
);
599 creds
= user_creds
->creds
+user_creds
->len
;
601 creds
->user
= getcpy(user
);
602 creds
->access_token
= creds
->refresh_token
= NULL
;
603 creds
->expires_at
= 0;
608 free_user_creds(struct user_creds
*user_creds
)
612 cred
= user_creds
->creds
;
613 for (i
= 0; i
< user_creds
->len
; i
++) {
615 free(cred
[i
].access_token
);
616 free(cred
[i
].refresh_token
);
618 free(user_creds
->creds
);
623 load_creds(struct user_creds
**result
, FILE *fp
, mh_oauth_ctx
*ctx
)
625 boolean success
= FALSE
;
626 char name
[NAMESZ
], value_buf
[BUFSIZ
];
628 m_getfld_state_t getfld_ctx
= 0;
630 struct user_creds
*user_creds
= mh_xmalloc(sizeof *user_creds
);
631 user_creds
->alloc
= 4;
633 user_creds
->creds
= mh_xmalloc(user_creds
->alloc
* sizeof *user_creds
->creds
);
636 int size
= sizeof value_buf
;
637 switch (state
= m_getfld(&getfld_ctx
, name
, value_buf
, &size
, fp
)) {
640 char **save
, *expire
;
641 time_t *expires_at
= NULL
;
642 if (strncmp(name
, "access-", 7) == 0) {
643 const char *user
= name
+ 7;
644 mh_oauth_cred
*creds
= find_or_alloc_user_creds(user_creds
,
646 save
= &creds
->access_token
;
647 } else if (strncmp(name
, "refresh-", 8) == 0) {
648 const char *user
= name
+ 8;
649 mh_oauth_cred
*creds
= find_or_alloc_user_creds(user_creds
,
651 save
= &creds
->refresh_token
;
652 } else if (strncmp(name
, "expire-", 7) == 0) {
653 const char *user
= name
+ 7;
654 mh_oauth_cred
*creds
= find_or_alloc_user_creds(user_creds
,
656 expires_at
= &creds
->expires_at
;
659 set_err_details(ctx
, MH_OAUTH_CRED_FILE
, "unexpected field");
664 *save
= trimcpy(value_buf
);
666 char *tmp
= getcpy(value_buf
);
667 while (state
== FLDPLUS
) {
668 size
= sizeof value_buf
;
669 state
= m_getfld(&getfld_ctx
, name
, value_buf
, &size
, fp
);
670 tmp
= add(value_buf
, tmp
);
672 *save
= trimcpy(tmp
);
675 if (expires_at
!= NULL
) {
677 *expires_at
= strtol(expire
, NULL
, 10);
680 set_err_details(ctx
, MH_OAUTH_CRED_FILE
,
681 "invalid expiration time");
695 /* Not adding details for LENERR/FMTERR because m_getfld already
696 * wrote advise message to stderr. */
697 set_err(ctx
, MH_OAUTH_CRED_FILE
);
702 m_getfld_state_destroy(&getfld_ctx
);
705 *result
= user_creds
;
707 free_user_creds(user_creds
);
714 save_user(FILE *fp
, const char *user
, const char *access
, const char *refresh
,
717 if (access
!= NULL
) {
718 if (fprintf(fp
, "access-%s: %s\n", user
, access
) < 0) return FALSE
;
720 if (refresh
!= NULL
) {
721 if (fprintf(fp
, "refresh-%s: %s\n", user
, refresh
) < 0) return FALSE
;
723 if (expires_at
> 0) {
724 if (fprintf(fp
, "expire-%s: %ld\n", user
, (long)expires_at
) < 0) {
732 mh_oauth_cred_save(FILE *fp
, mh_oauth_cred
*cred
, const char *user
)
734 struct user_creds
*user_creds
;
738 /* Load existing creds if any. */
739 if (!load_creds(&user_creds
, fp
, cred
->ctx
)) {
743 if (fchmod(fd
, S_IRUSR
| S_IWUSR
) < 0) goto err
;
744 if (ftruncate(fd
, 0) < 0) goto err
;
745 if (fseek(fp
, 0, SEEK_SET
) < 0) goto err
;
747 /* Write all creds except for this user. */
748 for (i
= 0; i
< user_creds
->len
; i
++) {
749 mh_oauth_cred
*c
= &user_creds
->creds
[i
];
750 if (strcmp(c
->user
, user
) == 0) continue;
751 if (!save_user(fp
, c
->user
, c
->access_token
, c
->refresh_token
,
757 /* Write updated creds for this user. */
758 if (!save_user(fp
, user
, cred
->access_token
, cred
->refresh_token
,
763 free_user_creds(user_creds
);
768 free_user_creds(user_creds
);
769 set_err(cred
->ctx
, MH_OAUTH_CRED_FILE
);
774 mh_oauth_cred_load(FILE *fp
, mh_oauth_ctx
*ctx
, const char *user
)
776 mh_oauth_cred
*creds
, *result
= NULL
;
777 struct user_creds
*user_creds
;
780 if (!load_creds(&user_creds
, fp
, ctx
)) {
784 /* Search user_creds for this user. If we don't find it, return NULL.
785 * If we do, free fields of all structs except this one, moving this one to
786 * the first struct if necessary. When we return it, it just looks like one
787 * struct to the caller, and the whole array is freed later. */
788 creds
= user_creds
->creds
;
789 for (i
= 0; i
< user_creds
->len
; i
++) {
790 if (strcmp(creds
[i
].user
, user
) == 0) {
793 result
->access_token
= creds
[i
].access_token
;
794 result
->refresh_token
= creds
[i
].refresh_token
;
795 result
->expires_at
= creds
[i
].expires_at
;
798 free(creds
[i
].access_token
);
799 free(creds
[i
].refresh_token
);
804 /* No longer need user_creds. result just uses its creds member. */
807 if (result
== NULL
) {
808 set_err_details(ctx
, MH_OAUTH_CRED_USER_NOT_FOUND
, user
);
819 mh_oauth_sasl_client_response(size_t *res_len
,
820 const char *user
, const mh_oauth_cred
*cred
)
822 size_t len
= sizeof "user=" - 1
824 + sizeof "\1auth=Bearer " - 1
825 + strlen(cred
->access_token
)
827 free(cred
->ctx
->sasl_client_res
);
828 cred
->ctx
->sasl_client_res
= mh_xmalloc(len
+ 1);
830 sprintf(cred
->ctx
->sasl_client_res
, "user=%s\1auth=Bearer %s\1\1",
831 user
, cred
->access_token
);
832 return cred
->ctx
->sasl_client_res
;
835 /*******************************************************************************
836 * building URLs and making HTTP requests with libcurl
840 * Build null-terminated URL in the array pointed to by s. If the URL doesn't
841 * fit within size (including the terminating null byte), return FALSE without *
842 * building the entire URL. Some of URL may already have been written into the
843 * result array in that case.
846 make_query_url(char *s
, size_t size
, CURL
*curl
, const char *base_url
, ...)
848 boolean result
= FALSE
;
854 if (base_url
== NULL
) {
858 len
= sprintf(s
, "%s", base_url
);
862 va_start(ap
, base_url
);
863 for (name
= va_arg(ap
, char *); name
!= NULL
; name
= va_arg(ap
, char *)) {
864 char *name_esc
= curl_easy_escape(curl
, name
, 0);
865 char *val_esc
= curl_easy_escape(curl
, va_arg(ap
, char *), 0);
866 /* prefix + name_esc + '=' + val_esc + '\0' must fit within size */
872 if (new_len
+ 1 > size
) {
877 sprintf(s
+ len
, "%s%s=%s", prefix
, name_esc
, val_esc
);
892 debug_callback(const CURL
*handle
, curl_infotype type
, const char *data
,
893 size_t size
, void *userptr
)
899 case CURLINFO_HEADER_IN
:
900 case CURLINFO_DATA_IN
:
903 case CURLINFO_HEADER_OUT
:
904 case CURLINFO_DATA_OUT
:
910 fwrite(data
, 1, size
, fp
);
911 if (data
[size
- 1] != '\n') {
919 write_callback(const char *ptr
, size_t size
, size_t nmemb
, void *userdata
)
921 struct curl_ctx
*ctx
= userdata
;
929 new_len
= ctx
->res_len
+ size
;
930 if (new_len
> sizeof ctx
->res_body
) {
935 memcpy(ctx
->res_body
+ ctx
->res_len
, ptr
, size
);
936 ctx
->res_len
= new_len
;
942 post(struct curl_ctx
*ctx
, const char *url
, const char *req_body
)
944 CURL
*curl
= ctx
->curl
;
947 ctx
->too_big
= FALSE
;
950 if (ctx
->log
!= NULL
) {
951 curl_easy_setopt(curl
, CURLOPT_VERBOSE
, (long)1);
952 curl_easy_setopt(curl
, CURLOPT_DEBUGFUNCTION
, debug_callback
);
953 curl_easy_setopt(curl
, CURLOPT_DEBUGDATA
, ctx
->log
);
956 if ((status
= curl_easy_setopt(curl
, CURLOPT_URL
, url
)) != CURLE_OK
) {
960 curl_easy_setopt(curl
, CURLOPT_POSTFIELDS
, req_body
);
961 curl_easy_setopt(curl
, CURLOPT_WRITEFUNCTION
, write_callback
);
962 curl_easy_setopt(curl
, CURLOPT_WRITEDATA
, ctx
);
964 status
= curl_easy_perform(curl
);
965 /* first check for error from callback */
970 if (status
!= CURLE_OK
) {
974 if ((status
= curl_easy_getinfo(curl
, CURLINFO_RESPONSE_CODE
,
975 &ctx
->res_code
)) != CURLE_OK
976 || (status
= curl_easy_getinfo(curl
, CURLINFO_CONTENT_TYPE
,
977 &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
);
1030 * Search input and tokens for the value identified by null-terminated name.
1032 * If found, allocate a null-terminated copy of the value and store the address
1033 * in val. val is left untouched if not found.
1036 get_json_string(char **val
, const char *input
, const jsmntok_t
*tokens
,
1039 /* number of top-level tokens (not counting object/list children) */
1040 int token_count
= tokens
[0].size
* 2;
1041 /* number of tokens to skip when we encounter objects and lists */
1042 /* We only look for top-level strings. */
1043 int skip_tokens
= 0;
1044 /* whether the current token represents a field name */
1045 /* The next token will be the value. */
1046 boolean is_key
= TRUE
;
1049 for (i
= 1; i
<= token_count
; i
++) {
1052 if (tokens
[i
].type
== JSMN_ARRAY
|| tokens
[i
].type
== JSMN_OBJECT
) {
1053 /* We're not interested in any array or object children; skip. */
1054 int children
= tokens
[i
].size
;
1055 if (tokens
[i
].type
== JSMN_OBJECT
) {
1056 /* Object size counts key/value pairs, skip both. */
1059 /* Add children to token_count. */
1060 token_count
+= children
;
1061 if (skip_tokens
== 0) {
1062 /* This token not already skipped; skip it. */
1063 /* Would already be skipped if child of object or list. */
1066 /* Skip this token's children. */
1067 skip_tokens
+= children
;
1069 if (skip_tokens
> 0) {
1071 /* When we finish with the object or list, we'll have a key. */
1079 key
= input
+ tokens
[i
- 1].start
;
1080 key_len
= tokens
[i
- 1].end
- tokens
[i
- 1].start
;
1081 if (strncmp(key
, name
, key_len
) == 0) {
1082 int val_len
= tokens
[i
].end
- tokens
[i
].start
;
1083 *val
= mh_xmalloc(val_len
+ 1);
1084 memcpy(*val
, input
+ tokens
[i
].start
, val_len
);
1085 (*val
)[val_len
] = '\0';
1093 * Parse input as JSON, extracting specified string values.
1095 * Variadic arguments are pairs of null-terminated strings indicating the value
1096 * to extract from the JSON and addresses into which pointers to null-terminated
1097 * copies of the values are written. These must be followed by one NULL pointer
1098 * to indicate the end of pairs.
1100 * The extracted strings are copies which caller must free. If any name is not
1101 * found, the address to store the value is not touched.
1103 * Returns non-zero if parsing is successful.
1105 * When parsing failed, no strings have been copied.
1107 * log may be used for debug-logging if not NULL.
1110 get_json_strings(const char *input
, size_t input_len
, FILE *log
, ...)
1112 boolean result
= FALSE
;
1118 if (!parse_json(&tokens
, &tokens_len
, input
, input_len
, log
)) {
1122 if (tokens
->type
!= JSMN_OBJECT
|| tokens
->size
== 0) {
1129 for (name
= va_arg(ap
, char *); name
!= NULL
; name
= va_arg(ap
, char *)) {
1130 get_json_string(va_arg(ap
, char **), input
, tokens
, name
);