]> diplodocus.org Git - nmh/blob - sbr/oauth.c
2ed2b77aedc83f94323466c5f627a1c54a7d3167
[nmh] / sbr / oauth.c
1 /* oauth.c -- OAuth 2.0 implementation for XOAUTH2 in SMTP and POP3.
2 *
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.
6 */
7
8 #include "h/mh.h"
9 #include "concat.h"
10 #include "trimcpy.h"
11 #include "getcpy.h"
12 #include "error.h"
13
14 #ifdef OAUTH_SUPPORT
15
16 #include <sys/stat.h>
17
18 #include <stdarg.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <strings.h>
23 #include <time.h>
24 #include <unistd.h>
25
26 #include <curl/curl.h>
27 #include "thirdparty/jsmn/jsmn.h"
28
29 #include "h/oauth.h"
30 #include "h/utils.h"
31 #include "lock_file.h"
32
33 #define JSON_TYPE "application/json"
34
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.
40 *
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
46 * unlikely. */
47 #define EXPIRY_FUDGE 60
48
49 /* maximum size for HTTP response bodies
50 * (not counting header and not null-terminated) */
51 #define RESPONSE_BODY_MAX 8192
52
53 /* Maximum size for URLs and URI-encoded query strings, null-terminated.
54 *
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?
60 */
61 #define URL_MAX 8192
62
63 struct mh_oauth_cred {
64 mh_oauth_ctx *ctx;
65
66 /* opaque access token ([1] 1.4) in null-terminated string */
67 char *access_token;
68 /* opaque refresh token ([1] 1.5) in null-terminated string */
69 char *refresh_token;
70
71 /* time at which the access token expires, or 0 if unknown */
72 time_t expires_at;
73
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". */
77
78 /* only filled while loading cred files, otherwise NULL */
79 char *user;
80 };
81
82 struct mh_oauth_ctx {
83 struct mh_oauth_service_info svc;
84 CURL *curl;
85 FILE *log;
86
87 char buf[URL_MAX];
88
89 char *cred_fn;
90 char *sasl_client_res;
91 char *user_agent;
92
93 mh_oauth_err_code err_code;
94
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;
98
99 /* Pointer to buffer mh_oauth_err_get_string allocates. */
100 char *err_formatted;
101
102 /* Ask libcurl to store errors here. */
103 char err_buf[CURL_ERROR_SIZE];
104 };
105
106 struct curl_ctx {
107 /* inputs */
108
109 CURL *curl;
110 /* NULL or a file handle to have curl log diagnostics to */
111 FILE *log;
112
113 /* outputs */
114
115 /* Whether the response was too big; if so, the rest of the output fields
116 * are undefined. */
117 bool too_big;
118
119 /* HTTP response code */
120 long res_code;
121
122 /* NULL or null-terminated value of Content-Type response header field */
123 const char *content_type;
124
125 /* number of bytes in the response body */
126 size_t res_len;
127
128 /* response body; NOT null-terminated */
129 char res_body[RESPONSE_BODY_MAX];
130 };
131
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 *);
135
136 int
137 mh_oauth_do_xoauth(const char *user, const char *svc, unsigned char **oauth_res,
138 size_t *oauth_res_len, FILE *log)
139 {
140 mh_oauth_ctx *ctx;
141 mh_oauth_cred *cred;
142 char *fn;
143 int failed_to_lock = 0;
144 FILE *fp;
145 char *client_res;
146
147 if (!mh_oauth_new (&ctx, svc))
148 die("%s", mh_oauth_get_err_string(ctx));
149
150 if (log != NULL) mh_oauth_log_to(stderr, ctx);
151
152 fn = mh_oauth_cred_fn(svc);
153 fp = lkfopendata(fn, "r+", &failed_to_lock);
154 if (fp == NULL) {
155 if (errno == ENOENT) {
156 die("no credentials -- run mhlogin -saslmech xoauth2 -authservice %s", svc);
157 }
158 adios(fn, "failed to open");
159 }
160 if (failed_to_lock) {
161 adios(fn, "failed to lock");
162 }
163
164 if ((cred = mh_oauth_cred_load(fp, ctx, user)) == NULL) {
165 die("%s", mh_oauth_get_err_string(ctx));
166 }
167
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);
172 }
173 if (mh_oauth_get_err_code(ctx) == MH_OAUTH_BAD_GRANT) {
174 die("credentials rejected -- run mhlogin -saslmech xoauth2 -authservice %s", svc);
175 }
176 inform("error refreshing OAuth2 token");
177 die("%s", mh_oauth_get_err_string(ctx));
178 }
179
180 fseek(fp, 0, SEEK_SET);
181 if (!mh_oauth_cred_save(fp, cred, user)) {
182 die("%s", mh_oauth_get_err_string(ctx));
183 }
184 }
185
186 if (lkfclosedata(fp, fn) < 0) {
187 adios(fn, "failed to close");
188 }
189 free(fn);
190
191 /* XXX writeBase64raw modifies the source buffer! make a copy */
192 client_res = mh_xstrdup(mh_oauth_sasl_client_response(oauth_res_len, user,
193 cred));
194 mh_oauth_cred_free(cred);
195 mh_oauth_free(ctx);
196
197 *oauth_res = (unsigned char *) client_res;
198
199 return OK;
200 }
201
202 static bool
203 is_json(const char *content_type)
204 {
205 return content_type != NULL
206 && strncasecmp(content_type, JSON_TYPE, LEN(JSON_TYPE)) == 0;
207 }
208
209 static void
210 set_err_details(mh_oauth_ctx *ctx, mh_oauth_err_code code, const char *details)
211 {
212 ctx->err_code = code;
213 ctx->err_details = details;
214 }
215
216 static void
217 set_err(mh_oauth_ctx *ctx, mh_oauth_err_code code)
218 {
219 set_err_details(ctx, code, NULL);
220 }
221
222 static void
223 set_err_http(mh_oauth_ctx *ctx, const struct curl_ctx *curl_ctx)
224 {
225 char *error = NULL;
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)
234 && error != NULL) {
235 if (strcmp(error, "invalid_grant") == 0) {
236 code = MH_OAUTH_BAD_GRANT;
237 } else {
238 /* All other errors indicate a bug, not anything the user did. */
239 code = MH_OAUTH_REQUEST_BAD;
240 }
241 } else {
242 code = MH_OAUTH_RESPONSE_BAD;
243 }
244 set_err(ctx, code);
245 free(error);
246 }
247
248 static char *
249 make_user_agent(void)
250 {
251 const char *curl = curl_version_info(CURLVERSION_NOW)->version;
252 return concat(user_agent, " libcurl/", curl, NULL);
253 }
254
255 bool
256 mh_oauth_new(mh_oauth_ctx **result, const char *svc_name)
257 {
258 mh_oauth_ctx *ctx;
259
260 NEW(ctx);
261 *result = ctx;
262 ctx->curl = NULL;
263
264 ctx->log = NULL;
265 ctx->cred_fn = ctx->sasl_client_res = ctx->err_formatted = NULL;
266
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);
270 return false;
271 }
272
273 ctx->curl = curl_easy_init();
274 if (ctx->curl == NULL) {
275 set_err(ctx, MH_OAUTH_CURL_INIT);
276 return false;
277 }
278 curl_easy_setopt(ctx->curl, CURLOPT_ERRORBUFFER, ctx->err_buf);
279
280 ctx->user_agent = make_user_agent();
281
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);
285 return false;
286 }
287
288 return true;
289 }
290
291 void
292 mh_oauth_free(mh_oauth_ctx *ctx)
293 {
294 free(ctx->svc.name);
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);
301 free(ctx->cred_fn);
302 free(ctx->sasl_client_res);
303 free(ctx->err_formatted);
304 free(ctx->user_agent);
305
306 if (ctx->curl != NULL) {
307 curl_easy_cleanup(ctx->curl);
308 }
309 free(ctx);
310 }
311
312 const char *
313 mh_oauth_svc_display_name(const mh_oauth_ctx *ctx)
314 {
315 return ctx->svc.display_name;
316 }
317
318 void
319 mh_oauth_log_to(FILE *log, mh_oauth_ctx *ctx)
320 {
321 ctx->log = log;
322 }
323
324 mh_oauth_err_code
325 mh_oauth_get_err_code(const mh_oauth_ctx *ctx)
326 {
327 return ctx->err_code;
328 }
329
330 const char *
331 mh_oauth_get_err_string(mh_oauth_ctx *ctx)
332 {
333 const char *base;
334
335 free(ctx->err_formatted);
336
337 switch (ctx->err_code) {
338 case MH_OAUTH_BAD_PROFILE:
339 base = "incomplete OAuth2 service definition";
340 break;
341 case MH_OAUTH_CURL_INIT:
342 base = "error initializing libcurl";
343 break;
344 case MH_OAUTH_REQUEST_INIT:
345 base = "local error initializing HTTP request";
346 break;
347 case MH_OAUTH_POST:
348 base = "error making HTTP request to OAuth2 authorization endpoint";
349 break;
350 case MH_OAUTH_RESPONSE_TOO_BIG:
351 base = "refusing to process response body larger than 8192 bytes";
352 break;
353 case MH_OAUTH_RESPONSE_BAD:
354 base = "invalid response";
355 break;
356 case MH_OAUTH_BAD_GRANT:
357 base = "bad grant (authorization code or refresh token)";
358 break;
359 case MH_OAUTH_REQUEST_BAD:
360 base = "bad OAuth request; re-run with -snoop and send REDACTED output"
361 " to nmh-workers";
362 break;
363 case MH_OAUTH_NO_REFRESH:
364 base = "no refresh token";
365 break;
366 case MH_OAUTH_CRED_USER_NOT_FOUND:
367 base = "user not found in cred file";
368 break;
369 case MH_OAUTH_CRED_FILE:
370 base = "error loading cred file";
371 break;
372 default:
373 base = "unknown error";
374 }
375 if (ctx->err_details == NULL) {
376 return ctx->err_formatted = mh_xstrdup(base);
377 }
378
379 ctx->err_formatted = concat(base, ": ", ctx->err_details, NULL);
380 return ctx->err_formatted;
381 }
382
383 const char *
384 mh_oauth_get_authorize_url(mh_oauth_ctx *ctx)
385 {
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,
393 NULL)) {
394 set_err(ctx, MH_OAUTH_REQUEST_INIT);
395 return NULL;
396 }
397 return ctx->buf;
398 }
399
400 static bool
401 cred_from_response(mh_oauth_cred *cred, const char *content_type,
402 const char *input, size_t input_len)
403 {
404 bool result = false;
405 char *access_token, *expires_in, *refresh_token;
406 const mh_oauth_ctx *ctx = cred->ctx;
407
408 if (!is_json(content_type)) {
409 return false;
410 }
411
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,
417 NULL)) {
418 goto out;
419 }
420
421 if (access_token == NULL) {
422 /* Response is invalid, but if it has a refresh token, we can try. */
423 if (refresh_token == NULL) {
424 goto out;
425 }
426 }
427
428 result = true;
429
430 free(cred->access_token);
431 cred->access_token = access_token;
432 access_token = NULL;
433
434 cred->expires_at = 0;
435 if (expires_in != NULL) {
436 long e;
437 errno = 0;
438 e = strtol(expires_in, NULL, 10);
439 if (errno == 0) {
440 if (e > 0) {
441 cred->expires_at = time(NULL) + e;
442 }
443 } else if (ctx->log != NULL) {
444 fprintf(ctx->log, "* invalid expiration: %s\n", expires_in);
445 }
446 }
447
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;
454 }
455
456 out:
457 free(refresh_token);
458 free(expires_in);
459 free(access_token);
460 return result;
461 }
462
463 static bool
464 do_access_request(mh_oauth_cred *cred, const char *req_body)
465 {
466 mh_oauth_ctx *ctx = cred->ctx;
467 struct curl_ctx curl_ctx;
468
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);
474 } else {
475 set_err_details(ctx, MH_OAUTH_POST, ctx->err_buf);
476 }
477 return false;
478 }
479
480 if (curl_ctx.res_code != 200) {
481 set_err_http(ctx, &curl_ctx);
482 return false;
483 }
484
485 if (!cred_from_response(cred, curl_ctx.content_type, curl_ctx.res_body,
486 curl_ctx.res_len)) {
487 set_err(ctx, MH_OAUTH_RESPONSE_BAD);
488 return false;
489 }
490
491 return true;
492 }
493
494 mh_oauth_cred *
495 mh_oauth_authorize(const char *code, mh_oauth_ctx *ctx)
496 {
497 mh_oauth_cred *result;
498
499 if (!make_query_url(ctx->buf, sizeof ctx->buf, ctx->curl, NULL,
500 "code", code,
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,
505 NULL)) {
506 set_err(ctx, MH_OAUTH_REQUEST_INIT);
507 return NULL;
508 }
509
510 NEW(result);
511 result->ctx = ctx;
512 result->access_token = result->refresh_token = NULL;
513
514 if (!do_access_request(result, ctx->buf)) {
515 free(result);
516 return NULL;
517 }
518
519 return result;
520 }
521
522 bool
523 mh_oauth_refresh(mh_oauth_cred *cred)
524 {
525 bool result;
526 mh_oauth_ctx *ctx = cred->ctx;
527
528 if (cred->refresh_token == NULL) {
529 set_err(ctx, MH_OAUTH_NO_REFRESH);
530 return false;
531 }
532
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,
538 NULL)) {
539 set_err(ctx, MH_OAUTH_REQUEST_INIT);
540 return false;
541 }
542
543 result = do_access_request(cred, ctx->buf);
544
545 if (result && cred->access_token == NULL) {
546 set_err_details(ctx, MH_OAUTH_RESPONSE_BAD, "no access token");
547 return false;
548 }
549
550 return result;
551 }
552
553 bool
554 mh_oauth_access_token_valid(time_t t, const mh_oauth_cred *cred)
555 {
556 return cred->access_token != NULL && t + EXPIRY_FUDGE < cred->expires_at;
557 }
558
559 void
560 mh_oauth_cred_free(mh_oauth_cred *cred)
561 {
562 free(cred->refresh_token);
563 free(cred->access_token);
564 free(cred);
565 }
566
567 /* for loading multi-user cred files */
568 struct user_creds {
569 mh_oauth_cred *creds;
570
571 /* number of allocated mh_oauth_cred structs above points to */
572 size_t alloc;
573
574 /* number that are actually filled in and used */
575 size_t len;
576 };
577
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)
582 {
583 mh_oauth_cred *creds = user_creds->creds;
584 size_t i;
585 for (i = 0; i < user_creds->len; i++) {
586 if (strcmp(creds[i].user, user) == 0) {
587 return &creds[i];
588 }
589 }
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);
593 }
594 creds = user_creds->creds+user_creds->len;
595 user_creds->len++;
596 creds->user = getcpy(user);
597 creds->access_token = creds->refresh_token = NULL;
598 creds->expires_at = 0;
599 return creds;
600 }
601
602 static void
603 free_user_creds(struct user_creds *user_creds)
604 {
605 mh_oauth_cred *cred;
606 size_t i;
607 cred = user_creds->creds;
608 for (i = 0; i < user_creds->len; i++) {
609 free(cred[i].user);
610 free(cred[i].access_token);
611 free(cred[i].refresh_token);
612 }
613 free(user_creds->creds);
614 free(user_creds);
615 }
616
617 static bool
618 load_creds(struct user_creds **result, FILE *fp, mh_oauth_ctx *ctx)
619 {
620 bool success = false;
621 char name[NAMESZ], value_buf[BUFSIZ];
622 int state;
623 m_getfld_state_t getfld_ctx;
624
625 struct user_creds *user_creds;
626 NEW(user_creds);
627 user_creds->alloc = 4;
628 user_creds->len = 0;
629 user_creds->creds = mh_xmalloc(user_creds->alloc * sizeof *user_creds->creds);
630
631 getfld_ctx = m_getfld_state_init(fp);
632 for (;;) {
633 int size = sizeof value_buf;
634 switch (state = m_getfld2(&getfld_ctx, name, value_buf, &size)) {
635 case FLD:
636 case FLDPLUS: {
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,
642 user);
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,
647 user);
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,
652 user);
653 expires_at = &creds->expires_at;
654 save = &expire;
655 } else {
656 set_err_details(ctx, MH_OAUTH_CRED_FILE, "unexpected field");
657 break;
658 }
659
660 if (state == FLD) {
661 *save = trimcpy(value_buf);
662 } else {
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);
668 }
669 *save = trimcpy(tmp);
670 free(tmp);
671 }
672 if (expires_at != NULL) {
673 errno = 0;
674 *expires_at = strtol(expire, NULL, 10);
675 free(expire);
676 if (errno != 0) {
677 set_err_details(ctx, MH_OAUTH_CRED_FILE,
678 "invalid expiration time");
679 break;
680 }
681 expires_at = NULL;
682 }
683 continue;
684 }
685
686 case BODY:
687 case FILEEOF:
688 success = true;
689 break;
690
691 default:
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);
695 break;
696 }
697 break;
698 }
699 m_getfld_state_destroy(&getfld_ctx);
700
701 if (success) {
702 *result = user_creds;
703 } else {
704 free_user_creds(user_creds);
705 }
706
707 return success;
708 }
709
710 static bool
711 save_user(FILE *fp, const char *user, const char *access, const char *refresh,
712 long expires_at)
713 {
714 if (access != NULL) {
715 if (fprintf(fp, "access-%s: %s\n", user, access) < 0) return false;
716 }
717 if (refresh != NULL) {
718 if (fprintf(fp, "refresh-%s: %s\n", user, refresh) < 0) return false;
719 }
720 if (expires_at > 0) {
721 if (fprintf(fp, "expire-%s: %ld\n", user, (long)expires_at) < 0) {
722 return false;
723 }
724 }
725 return true;
726 }
727
728 bool
729 mh_oauth_cred_save(FILE *fp, mh_oauth_cred *cred, const char *user)
730 {
731 struct user_creds *user_creds;
732 int fd = fileno(fp);
733 size_t i;
734
735 /* Load existing creds if any. */
736 if (!load_creds(&user_creds, fp, cred->ctx)) {
737 return false;
738 }
739
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;
743
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,
749 c->expires_at)) {
750 goto err;
751 }
752 }
753
754 /* Write updated creds for this user. */
755 if (!save_user(fp, user, cred->access_token, cred->refresh_token,
756 cred->expires_at)) {
757 goto err;
758 }
759
760 free_user_creds(user_creds);
761
762 return true;
763
764 err:
765 free_user_creds(user_creds);
766 set_err(cred->ctx, MH_OAUTH_CRED_FILE);
767 return false;
768 }
769
770 mh_oauth_cred *
771 mh_oauth_cred_load(FILE *fp, mh_oauth_ctx *ctx, const char *user)
772 {
773 mh_oauth_cred *creds, *result = NULL;
774 struct user_creds *user_creds;
775 size_t i;
776
777 if (!load_creds(&user_creds, fp, ctx)) {
778 return NULL;
779 }
780
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) {
788 result = creds;
789 if (i > 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;
793 }
794 } else {
795 free(creds[i].access_token);
796 free(creds[i].refresh_token);
797 }
798 free(creds[i].user);
799 }
800
801 /* No longer need user_creds. result just uses its creds member. */
802 free(user_creds);
803
804 if (result == NULL) {
805 set_err_details(ctx, MH_OAUTH_CRED_USER_NOT_FOUND, user);
806 return NULL;
807 }
808
809 result->ctx = ctx;
810 result->user = NULL;
811
812 return result;
813 }
814
815 const char *
816 mh_oauth_sasl_client_response(size_t *res_len,
817 const char *user, const mh_oauth_cred *cred)
818 {
819 char **p;
820
821 p = &cred->ctx->sasl_client_res;
822 free(*p);
823 *p = concat("user=", user, "\1auth=Bearer ", cred->access_token, "\1\1", NULL);
824 *res_len = strlen(*p);
825 return *p;
826 }
827
828 /*******************************************************************************
829 * building URLs and making HTTP requests with libcurl
830 */
831
832 /*
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.
837 */
838 static bool
839 make_query_url(char *s, size_t size, CURL *curl, const char *base_url, ...)
840 {
841 bool result = false;
842 size_t len;
843 char *prefix;
844 va_list ap;
845 const char *name;
846
847 if (base_url == NULL) {
848 len = 0;
849 prefix = "";
850 } else {
851 len = strlen(base_url);
852 if (len > size - 1) /* Less one for NUL. */
853 return false;
854 strcpy(s, base_url);
855 prefix = "?";
856 }
857
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 */
863 size_t new_len = len
864 + strlen(prefix)
865 + strlen(name_esc)
866 + 1 /* '=' */
867 + strlen(val_esc);
868 if (new_len + 1 > size) {
869 free(name_esc);
870 free(val_esc);
871 goto out;
872 }
873 sprintf(s + len, "%s%s=%s", prefix, name_esc, val_esc);
874 free(name_esc);
875 free(val_esc);
876 len = new_len;
877 prefix = "&";
878 }
879
880 result = true;
881
882 out:
883 va_end(ap);
884 return result;
885 }
886
887 static int
888 debug_callback(CURL *handle, curl_infotype type, char *data,
889 size_t size, void *userptr)
890 {
891 FILE *fp = userptr;
892 NMH_UNUSED(handle);
893
894 switch (type) {
895 case CURLINFO_HEADER_IN:
896 case CURLINFO_DATA_IN:
897 fputs("< ", fp);
898 break;
899 case CURLINFO_HEADER_OUT:
900 case CURLINFO_DATA_OUT:
901 fputs("> ", fp);
902 break;
903 default:
904 return 0;
905 }
906 fwrite(data, 1, size, fp);
907 if (data[size - 1] != '\n') {
908 putc('\n', fp);
909 }
910 fflush(fp);
911 return 0;
912 }
913
914 static size_t
915 write_callback(const char *ptr, size_t size, size_t nmemb, void *userdata)
916 {
917 struct curl_ctx *ctx = userdata;
918 size_t new_len;
919
920 if (ctx->too_big) {
921 return 0;
922 }
923
924 size *= nmemb;
925 new_len = ctx->res_len + size;
926 if (new_len > sizeof ctx->res_body) {
927 ctx->too_big = true;
928 return 0;
929 }
930
931 memcpy(ctx->res_body + ctx->res_len, ptr, size);
932 ctx->res_len = new_len;
933
934 return size;
935 }
936
937 static bool
938 post(struct curl_ctx *ctx, const char *url, const char *req_body)
939 {
940 CURL *curl = ctx->curl;
941 CURLcode status;
942
943 ctx->too_big = false;
944 ctx->res_len = 0;
945
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);
950 }
951
952 if (curl_easy_setopt(curl, CURLOPT_URL, url) != CURLE_OK) {
953 return false;
954 }
955
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);
959
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
964 suite). */
965 curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 2L);
966 }
967
968 status = curl_easy_perform(curl);
969 /* first check for error from callback */
970 if (ctx->too_big) {
971 return false;
972 }
973 /* now from curl */
974 if (status != CURLE_OK) {
975 return false;
976 }
977
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;
982 }
983
984 /*******************************************************************************
985 * JSON processing
986 */
987
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
992
993 /*
994 * Parse JSON, store pointer to array of jsmntok_t in tokens.
995 *
996 * Returns whether parsing is successful.
997 *
998 * Even in that case, tokens has been allocated and must be freed.
999 */
1000 static bool
1001 parse_json(jsmntok_t **tokens, size_t *tokens_len,
1002 const char *input, size_t input_len, FILE *log)
1003 {
1004 jsmn_parser p;
1005 jsmnerr_t r;
1006
1007 *tokens_len = JSMN_TOKENS;
1008 *tokens = mh_xmalloc(*tokens_len * sizeof **tokens);
1009
1010 jsmn_init(&p);
1011 while ((r = jsmn_parse(&p, input, input_len,
1012 *tokens, *tokens_len)) == JSMN_ERROR_NOMEM) {
1013 *tokens_len = 2 * *tokens_len;
1014 if (log != NULL) {
1015 fprintf(log, "* need more jsmntok_t! allocating %ld\n",
1016 (long)*tokens_len);
1017 }
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);
1021 }
1022
1023 return r > 0;
1024 }
1025
1026 /*
1027 * Search input and tokens for the value identified by null-terminated name.
1028 *
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.
1031 */
1032 static void
1033 get_json_string(char **val, const char *input, const jsmntok_t *tokens,
1034 const char *name)
1035 {
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. */
1043 bool is_key = true;
1044
1045 int i;
1046 for (i = 1; i <= token_count; i++) {
1047 const char *key;
1048 int key_len;
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. */
1054 children *= 2;
1055 }
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. */
1061 skip_tokens++;
1062 }
1063 /* Skip this token's children. */
1064 skip_tokens += children;
1065 }
1066 if (skip_tokens > 0) {
1067 skip_tokens--;
1068 /* When we finish with the object or list, we'll have a key. */
1069 is_key = true;
1070 continue;
1071 }
1072 if (is_key) {
1073 is_key = false;
1074 continue;
1075 }
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';
1083 return;
1084 }
1085 is_key = true;
1086 }
1087 }
1088
1089 /*
1090 * Parse input as JSON, extracting specified string values.
1091 *
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.
1096 *
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.
1099 *
1100 * Returns non-zero if parsing is successful.
1101 *
1102 * When parsing failed, no strings have been copied.
1103 *
1104 * log may be used for debug-logging if not NULL.
1105 */
1106 static bool
1107 get_json_strings(const char *input, size_t input_len, FILE *log, ...)
1108 {
1109 bool result = false;
1110 jsmntok_t *tokens;
1111 size_t tokens_len;
1112 va_list ap;
1113 const char *name;
1114
1115 if (!parse_json(&tokens, &tokens_len, input, input_len, log)) {
1116 goto out;
1117 }
1118
1119 if (tokens->type != JSMN_OBJECT || tokens->size == 0) {
1120 goto out;
1121 }
1122
1123 result = true;
1124
1125 va_start(ap, log);
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);
1128 }
1129
1130 out:
1131 va_end(ap);
1132 free(tokens);
1133 return result;
1134 }
1135 #endif