interplane.Get Omega
Read in your language

git

[Ported from github.com/git/git] Sync with Git 2.56.1

Brought by drakestapleton

branch master Branches Tags History

git / imap-send.c

1913 lines · 46281 bytes Raw Blame History
1/*
2 * git-imap-send - drops patches into an imap Drafts folder
3 * derived from isync/mbsync - mailbox synchronizer
4 *
5 * Copyright (C) 2000-2002 Michael R. Elkins <me@mutt.org>
6 * Copyright (C) 2002-2004 Oswald Buddenhagen <ossi@users.sf.net>
7 * Copyright (C) 2004 Theodore Y. Ts'o <tytso@mit.edu>
8 * Copyright (C) 2006 Mike McCormack
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, see <https://www.gnu.org/licenses/>.
22 */
23
24#define USE_THE_REPOSITORY_VARIABLE
25#define DISABLE_SIGN_COMPARE_WARNINGS
26
27#include "git-compat-util.h"
28#include "advice.h"
29#include "config.h"
30#include "credential.h"
31#include "environment.h"
32#include "gettext.h"
33#include "run-command.h"
34#include "parse-options.h"
35#include "setup.h"
36#include "strbuf.h"
37#ifdef USE_CURL_FOR_IMAP_SEND
38#include "git-curl-compat.h"
39#include "http.h"
40#endif
41
42#if defined(USE_CURL_FOR_IMAP_SEND)
43/* Always default to curl if it's available. */
44#define USE_CURL_DEFAULT 1
45#else
46/* We don't have curl, so continue to use the historical implementation */
47#define USE_CURL_DEFAULT 0
48#endif
49
50static int verbosity;
51static int list_folders;
52static int use_curl = USE_CURL_DEFAULT;
53static int opt_draft;
54static char *opt_folder;
55
56static char const * const imap_send_usage[] = {
57 N_("git imap-send [-v] [-q] [--[no-]curl] [--[no-]draft] [(--folder|-f) <folder>] < <mbox>"),
58 "git imap-send --list",
59 NULL
60};
61
62static struct option imap_send_options[] = {
63 OPT__VERBOSITY(&verbosity),
64 OPT_BOOL(0, "curl", &use_curl, "use libcurl to communicate with the IMAP server"),
65 OPT_BOOL(0, "draft", &opt_draft, "mark uploaded messages with the IMAP \\Draft flag"),
66 OPT_STRING('f', "folder", &opt_folder, "folder", "specify the IMAP folder"),
67 OPT_BOOL(0, "list", &list_folders, "list all folders on the IMAP server"),
68 OPT_END()
69};
70
71#undef DRV_OK
72#define DRV_OK 0
73#define DRV_MSG_BAD -1
74#define DRV_BOX_BAD -2
75#define DRV_STORE_BAD -3
76
77__attribute__((format (printf, 1, 2)))
78static void imap_info(const char *, ...);
79__attribute__((format (printf, 1, 2)))
80static void imap_warn(const char *, ...);
81
82static char *next_arg(char **);
83
84struct imap_server_conf {
85 char *tunnel;
86 char *host;
87 int port;
88 char *folder;
89 char *user;
90 char *pass;
91 int use_ssl;
92 int ssl_verify;
93 int use_html;
94 char *auth_method;
95};
96
97struct imap_socket {
98 int fd[2];
99#if defined(NO_OPENSSL) && !defined(HAVE_OPENSSL_CSPRNG)
100 void *ssl;
101#else
102 SSL *ssl;
103#endif
104};
105
106struct imap_buffer {
107 struct imap_socket sock;
108 int bytes;
109 int offset;
110 char buf[1024];
111};
112
113struct imap_cmd;
114
115struct imap {
116 int uidnext; /* from SELECT responses */
117 unsigned caps, rcaps; /* CAPABILITY results */
118 /* command queue */
119 int nexttag, num_in_progress, literal_pending;
120 struct imap_cmd *in_progress, **in_progress_append;
121 struct imap_buffer buf; /* this is BIG, so put it last */
122};
123
124struct imap_store {
125 const struct imap_server_conf *cfg;
126 /* currently open mailbox */
127 const char *name; /* foreign! maybe preset? */
128 int uidvalidity;
129 struct imap *imap;
130 const char *prefix;
131};
132
133struct imap_cmd_cb {
134 int (*cont)(struct imap_store *ctx, const char *prompt);
135 void *ctx;
136 char *data;
137 int dlen;
138};
139
140struct imap_cmd {
141 struct imap_cmd *next;
142 struct imap_cmd_cb cb;
143 char *cmd;
144 int tag;
145};
146
147#define CAP(cap) (imap->caps & (1 << (cap)))
148
149enum CAPABILITY {
150 NOLOGIN = 0,
151 UIDPLUS,
152 LITERALPLUS,
153 NAMESPACE,
154 STARTTLS,
155 AUTH_PLAIN,
156 AUTH_CRAM_MD5,
157 AUTH_OAUTHBEARER,
158 AUTH_XOAUTH2,
159};
160
161static const char *cap_list[] = {
162 "LOGINDISABLED",
163 "UIDPLUS",
164 "LITERAL+",
165 "NAMESPACE",
166 "STARTTLS",
167 "AUTH=PLAIN",
168 "AUTH=CRAM-MD5",
169 "AUTH=OAUTHBEARER",
170 "AUTH=XOAUTH2",
171};
172
173#define RESP_OK 0
174#define RESP_NO 1
175#define RESP_BAD 2
176
177static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd);
178
179
180#ifndef NO_OPENSSL
181static void ssl_socket_perror(const char *func)
182{
183 fprintf(stderr, "%s: %s\n", func, ERR_error_string(ERR_get_error(), NULL));
184}
185#endif
186
187static void socket_perror(const char *func, struct imap_socket *sock, int ret)
188{
189#ifndef NO_OPENSSL
190 if (sock->ssl) {
191 int sslerr = SSL_get_error(sock->ssl, ret);
192 switch (sslerr) {
193 case SSL_ERROR_NONE:
194 break;
195 case SSL_ERROR_SYSCALL:
196 perror("SSL_connect");
197 break;
198 default:
199 ssl_socket_perror("SSL_connect");
200 break;
201 }
202 } else
203#endif
204 {
205 if (ret < 0)
206 perror(func);
207 else
208 fprintf(stderr, "%s: unexpected EOF\n", func);
209 }
210 /* mark as used to appease -Wunused-parameter with NO_OPENSSL */
211 (void)sock;
212}
213
214#ifdef NO_OPENSSL
215static int ssl_socket_connect(struct imap_socket *sock UNUSED,
216 const struct imap_server_conf *cfg UNUSED,
217 int use_tls_only UNUSED)
218{
219 fprintf(stderr, "SSL requested, but SSL support is not compiled in\n");
220 return -1;
221}
222
223#else
224
225static int host_matches(const char *host, const ASN1_STRING *asn1_str)
226{
227 const char *pattern = (const char *)ASN1_STRING_get0_data(asn1_str);
228
229 /* embedded NUL characters may open a security hole */
230 if (memchr(pattern, '\0', ASN1_STRING_length(asn1_str)))
231 return 0;
232
233 if (pattern[0] == '*' && pattern[1] == '.') {
234 pattern += 2;
235 if (!(host = strchr(host, '.')))
236 return 0;
237 host++;
238 }
239
240 return *host && *pattern && !strcasecmp(host, pattern);
241}
242
243static int verify_hostname(X509 *cert, const char *hostname)
244{
245#if (OPENSSL_VERSION_NUMBER >= 0x40000000L)
246 const X509_NAME *subj;
247#else
248 X509_NAME *subj;
249#endif
250 const X509_NAME_ENTRY *cname_entry;
251 const ASN1_STRING *cname;
252 int i, found;
253 STACK_OF(GENERAL_NAME) *subj_alt_names;
254
255 /* try the DNS subjectAltNames */
256 found = 0;
257 if ((subj_alt_names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL))) {
258 int num_subj_alt_names = sk_GENERAL_NAME_num(subj_alt_names);
259 for (i = 0; !found && i < num_subj_alt_names; i++) {
260 int ntype;
261 GENERAL_NAME *subj_alt_name = sk_GENERAL_NAME_value(subj_alt_names, i);
262 ASN1_STRING *subj_alt_str = GENERAL_NAME_get0_value(subj_alt_name, &ntype);
263
264 if (ntype == GEN_DNS && host_matches(hostname, subj_alt_str))
265 found = 1;
266 }
267 sk_GENERAL_NAME_pop_free(subj_alt_names, GENERAL_NAME_free);
268 }
269 if (found)
270 return 0;
271
272 /* try the common name */
273 if (!(subj = X509_get_subject_name(cert)))
274 return error("cannot get certificate subject");
275 if ((i = X509_NAME_get_index_by_NID(subj, NID_commonName, -1)) < 0 ||
276 (cname_entry = X509_NAME_get_entry(subj, i)) == NULL ||
277 (cname = X509_NAME_ENTRY_get_data(cname_entry)) == NULL)
278 return error("cannot get certificate common name");
279 if (host_matches(hostname, cname))
280 return 0;
281 return error("certificate owner '%s' does not match hostname '%s'",
282 ASN1_STRING_get0_data(cname), hostname);
283}
284
285static int ssl_socket_connect(struct imap_socket *sock,
286 const struct imap_server_conf *cfg,
287 int use_tls_only)
288{
289#if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
290 const SSL_METHOD *meth;
291#else
292 SSL_METHOD *meth;
293#endif
294 SSL_CTX *ctx;
295 int ret;
296 X509 *cert;
297
298 SSL_library_init();
299 SSL_load_error_strings();
300
301 meth = SSLv23_method();
302 if (!meth) {
303 ssl_socket_perror("SSLv23_method");
304 return -1;
305 }
306
307 ctx = SSL_CTX_new(meth);
308 if (!ctx) {
309 ssl_socket_perror("SSL_CTX_new");
310 return -1;
311 }
312
313 if (use_tls_only)
314 SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
315
316 if (cfg->ssl_verify)
317 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
318
319 if (!SSL_CTX_set_default_verify_paths(ctx)) {
320 ssl_socket_perror("SSL_CTX_set_default_verify_paths");
321 return -1;
322 }
323 sock->ssl = SSL_new(ctx);
324 if (!sock->ssl) {
325 ssl_socket_perror("SSL_new");
326 return -1;
327 }
328 if (!SSL_set_rfd(sock->ssl, sock->fd[0])) {
329 ssl_socket_perror("SSL_set_rfd");
330 return -1;
331 }
332 if (!SSL_set_wfd(sock->ssl, sock->fd[1])) {
333 ssl_socket_perror("SSL_set_wfd");
334 return -1;
335 }
336
337#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
338 /*
339 * SNI (RFC4366)
340 * OpenSSL does not document this function, but the implementation
341 * returns 1 on success, 0 on failure after calling SSLerr().
342 */
343 ret = SSL_set_tlsext_host_name(sock->ssl, cfg->host);
344 if (ret != 1)
345 warning("SSL_set_tlsext_host_name(%s) failed.", cfg->host);
346#endif
347
348 ret = SSL_connect(sock->ssl);
349 if (ret <= 0) {
350 socket_perror("SSL_connect", sock, ret);
351 return -1;
352 }
353
354 if (cfg->ssl_verify) {
355 /* make sure the hostname matches that of the certificate */
356 cert = SSL_get_peer_certificate(sock->ssl);
357 if (!cert)
358 return error("unable to get peer certificate.");
359 if (SSL_get_verify_result(sock->ssl) != X509_V_OK)
360 return error("unable to verify peer certificate");
361 if (verify_hostname(cert, cfg->host) < 0)
362 return -1;
363 }
364
365 return 0;
366}
367#endif
368
369static int socket_read(struct imap_socket *sock, char *buf, int len)
370{
371 ssize_t n;
372#ifndef NO_OPENSSL
373 if (sock->ssl)
374 n = SSL_read(sock->ssl, buf, len);
375 else
376#endif
377 n = xread(sock->fd[0], buf, len);
378 if (n <= 0) {
379 socket_perror("read", sock, n);
380 close(sock->fd[0]);
381 close(sock->fd[1]);
382 sock->fd[0] = sock->fd[1] = -1;
383 }
384 return n;
385}
386
387static int socket_write(struct imap_socket *sock, const char *buf, int len)
388{
389 int n;
390#ifndef NO_OPENSSL
391 if (sock->ssl)
392 n = SSL_write(sock->ssl, buf, len);
393 else
394#endif
395 n = write_in_full(sock->fd[1], buf, len);
396 if (n != len) {
397 socket_perror("write", sock, n);
398 close(sock->fd[0]);
399 close(sock->fd[1]);
400 sock->fd[0] = sock->fd[1] = -1;
401 }
402 return n;
403}
404
405static void socket_shutdown(struct imap_socket *sock)
406{
407#ifndef NO_OPENSSL
408 if (sock->ssl) {
409 SSL_shutdown(sock->ssl);
410 SSL_free(sock->ssl);
411 }
412#endif
413 close(sock->fd[0]);
414 close(sock->fd[1]);
415}
416
417/* simple line buffering */
418static int buffer_gets(struct imap_buffer *b, char **s)
419{
420 int n;
421 int start = b->offset;
422
423 *s = b->buf + start;
424
425 for (;;) {
426 /* make sure we have enough data to read the \r\n sequence */
427 if (b->offset + 1 >= b->bytes) {
428 if (start) {
429 /* shift down used bytes */
430 *s = b->buf;
431
432 assert(start <= b->bytes);
433 n = b->bytes - start;
434
435 if (n)
436 memmove(b->buf, b->buf + start, n);
437 b->offset -= start;
438 b->bytes = n;
439 start = 0;
440 }
441
442 n = socket_read(&b->sock, b->buf + b->bytes,
443 sizeof(b->buf) - b->bytes);
444
445 if (n <= 0)
446 return -1;
447
448 b->bytes += n;
449 }
450
451 if (b->buf[b->offset] == '\r') {
452 assert(b->offset + 1 < b->bytes);
453 if (b->buf[b->offset + 1] == '\n') {
454 b->buf[b->offset] = 0; /* terminate the string */
455 b->offset += 2; /* next line */
456 if ((0 < verbosity) || (list_folders && strstr(*s, "* LIST")))
457 puts(*s);
458 return 0;
459 }
460 }
461
462 b->offset++;
463 }
464 /* not reached */
465}
466
467__attribute__((format (printf, 1, 2)))
468static void imap_info(const char *msg, ...)
469{
470 va_list va;
471
472 if (0 <= verbosity) {
473 va_start(va, msg);
474 vprintf(msg, va);
475 va_end(va);
476 fflush(stdout);
477 }
478}
479
480__attribute__((format (printf, 1, 2)))
481static void imap_warn(const char *msg, ...)
482{
483 va_list va;
484
485 if (-2 < verbosity) {
486 va_start(va, msg);
487 vfprintf(stderr, msg, va);
488 va_end(va);
489 }
490}
491
492static char *next_arg(char **s)
493{
494 char *ret;
495
496 if (!s || !*s)
497 return NULL;
498 while (isspace((unsigned char) **s))
499 (*s)++;
500 if (!**s) {
501 *s = NULL;
502 return NULL;
503 }
504 if (**s == '"') {
505 ++*s;
506 ret = *s;
507 *s = strchr(*s, '"');
508 } else {
509 ret = *s;
510 while (**s && !isspace((unsigned char) **s))
511 (*s)++;
512 }
513 if (*s) {
514 if (**s)
515 *(*s)++ = 0;
516 if (!**s)
517 *s = NULL;
518 }
519 return ret;
520}
521
522static struct imap_cmd *issue_imap_cmd(struct imap_store *ctx,
523 struct imap_cmd_cb *cb,
524 const char *fmt, va_list ap)
525{
526 struct imap *imap = ctx->imap;
527 struct imap_cmd *cmd;
528 int n;
529 struct strbuf buf = STRBUF_INIT;
530
531 cmd = xmalloc(sizeof(struct imap_cmd));
532 cmd->cmd = xstrvfmt(fmt, ap);
533 cmd->tag = ++imap->nexttag;
534
535 if (cb)
536 cmd->cb = *cb;
537 else
538 memset(&cmd->cb, 0, sizeof(cmd->cb));
539
540 while (imap->literal_pending)
541 get_cmd_result(ctx, NULL);
542
543 if (!cmd->cb.data)
544 strbuf_addf(&buf, "%d %s\r\n", cmd->tag, cmd->cmd);
545 else
546 strbuf_addf(&buf, "%d %s{%d%s}\r\n", cmd->tag, cmd->cmd,
547 cmd->cb.dlen, CAP(LITERALPLUS) ? "+" : "");
548 if (buf.len > INT_MAX)
549 die("imap command overflow!");
550
551 if (0 < verbosity) {
552 if (imap->num_in_progress)
553 printf("(%d in progress) ", imap->num_in_progress);
554 if (!starts_with(cmd->cmd, "LOGIN"))
555 printf(">>> %s", buf.buf);
556 else
557 printf(">>> %d LOGIN <user> <pass>\n", cmd->tag);
558 }
559 if (socket_write(&imap->buf.sock, buf.buf, buf.len) != buf.len) {
560 free(cmd->cmd);
561 free(cmd);
562 if (cb)
563 free(cb->data);
564 strbuf_release(&buf);
565 return NULL;
566 }
567 strbuf_release(&buf);
568 if (cmd->cb.data) {
569 if (CAP(LITERALPLUS)) {
570 n = socket_write(&imap->buf.sock, cmd->cb.data, cmd->cb.dlen);
571 free(cmd->cb.data);
572 if (n != cmd->cb.dlen ||
573 socket_write(&imap->buf.sock, "\r\n", 2) != 2) {
574 free(cmd->cmd);
575 free(cmd);
576 return NULL;
577 }
578 cmd->cb.data = NULL;
579 } else
580 imap->literal_pending = 1;
581 } else if (cmd->cb.cont)
582 imap->literal_pending = 1;
583 cmd->next = NULL;
584 *imap->in_progress_append = cmd;
585 imap->in_progress_append = &cmd->next;
586 imap->num_in_progress++;
587 return cmd;
588}
589
590__attribute__((format (printf, 3, 4)))
591static int imap_exec(struct imap_store *ctx, struct imap_cmd_cb *cb,
592 const char *fmt, ...)
593{
594 va_list ap;
595 struct imap_cmd *cmdp;
596
597 va_start(ap, fmt);
598 cmdp = issue_imap_cmd(ctx, cb, fmt, ap);
599 va_end(ap);
600 if (!cmdp)
601 return RESP_BAD;
602
603 return get_cmd_result(ctx, cmdp);
604}
605
606__attribute__((format (printf, 3, 4)))
607static int imap_exec_m(struct imap_store *ctx, struct imap_cmd_cb *cb,
608 const char *fmt, ...)
609{
610 va_list ap;
611 struct imap_cmd *cmdp;
612
613 va_start(ap, fmt);
614 cmdp = issue_imap_cmd(ctx, cb, fmt, ap);
615 va_end(ap);
616 if (!cmdp)
617 return DRV_STORE_BAD;
618
619 switch (get_cmd_result(ctx, cmdp)) {
620 case RESP_BAD: return DRV_STORE_BAD;
621 case RESP_NO: return DRV_MSG_BAD;
622 default: return DRV_OK;
623 }
624}
625
626static int skip_imap_list_l(char **sp, int level)
627{
628 char *s = *sp;
629
630 for (;;) {
631 while (isspace((unsigned char)*s))
632 s++;
633 if (level && *s == ')') {
634 s++;
635 break;
636 }
637 if (*s == '(') {
638 /* sublist */
639 s++;
640 if (skip_imap_list_l(&s, level + 1))
641 goto bail;
642 } else if (*s == '"') {
643 /* quoted string */
644 s++;
645 for (; *s != '"'; s++)
646 if (!*s)
647 goto bail;
648 s++;
649 } else {
650 /* atom */
651 for (; *s && !isspace((unsigned char)*s); s++)
652 if (level && *s == ')')
653 break;
654 }
655
656 if (!level)
657 break;
658 if (!*s)
659 goto bail;
660 }
661 *sp = s;
662 return 0;
663
664bail:
665 return -1;
666}
667
668static void skip_list(char **sp)
669{
670 skip_imap_list_l(sp, 0);
671}
672
673static void parse_capability(struct imap *imap, char *cmd)
674{
675 char *arg;
676 unsigned i;
677
678 imap->caps = 0x80000000;
679 while ((arg = next_arg(&cmd)))
680 for (i = 0; i < ARRAY_SIZE(cap_list); i++)
681 if (!strcmp(cap_list[i], arg))
682 imap->caps |= 1 << i;
683 imap->rcaps = imap->caps;
684}
685
686static int parse_response_code(struct imap_store *ctx, struct imap_cmd_cb *cb,
687 char *s)
688{
689 struct imap *imap = ctx->imap;
690 char *arg, *p;
691
692 if (!s || *s != '[')
693 return RESP_OK; /* no response code */
694 s++;
695 if (!(p = strchr(s, ']'))) {
696 fprintf(stderr, "IMAP error: malformed response code\n");
697 return RESP_BAD;
698 }
699 *p++ = 0;
700 arg = next_arg(&s);
701 if (!arg) {
702 fprintf(stderr, "IMAP error: empty response code\n");
703 return RESP_BAD;
704 }
705 if (!strcmp("UIDVALIDITY", arg)) {
706 if (!(arg = next_arg(&s)) || strtol_i(arg, 10, &ctx->uidvalidity) || !ctx->uidvalidity) {
707 fprintf(stderr, "IMAP error: malformed UIDVALIDITY status\n");
708 return RESP_BAD;
709 }
710 } else if (!strcmp("UIDNEXT", arg)) {
711 if (!(arg = next_arg(&s)) || strtol_i(arg, 10, &imap->uidnext) || !imap->uidnext) {
712 fprintf(stderr, "IMAP error: malformed NEXTUID status\n");
713 return RESP_BAD;
714 }
715 } else if (!strcmp("CAPABILITY", arg)) {
716 parse_capability(imap, s);
717 } else if (!strcmp("ALERT", arg)) {
718 /* RFC2060 says that these messages MUST be displayed
719 * to the user
720 */
721 for (; isspace((unsigned char)*p); p++);
722 fprintf(stderr, "*** IMAP ALERT *** %s\n", p);
723 } else if (cb && cb->ctx && !strcmp("APPENDUID", arg)) {
724 if (!(arg = next_arg(&s)) || strtol_i(arg, 10, &ctx->uidvalidity) || !ctx->uidvalidity ||
725 !(arg = next_arg(&s)) || strtol_i(arg, 10, (int *)cb->ctx) || !cb->ctx) {
726 fprintf(stderr, "IMAP error: malformed APPENDUID status\n");
727 return RESP_BAD;
728 }
729 }
730 return RESP_OK;
731}
732
733static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd)
734{
735 struct imap *imap = ctx->imap;
736 struct imap_cmd *cmdp, **pcmdp;
737 char *cmd;
738 const char *arg, *arg1;
739 int n, resp, resp2, tag;
740
741 for (;;) {
742 if (buffer_gets(&imap->buf, &cmd))
743 return RESP_BAD;
744
745 arg = next_arg(&cmd);
746 if (!arg) {
747 fprintf(stderr, "IMAP error: empty response\n");
748 return RESP_BAD;
749 }
750 if (*arg == '*') {
751 arg = next_arg(&cmd);
752 if (!arg) {
753 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
754 return RESP_BAD;
755 }
756
757 if (!strcmp("NAMESPACE", arg)) {
758 /* rfc2342 NAMESPACE response. */
759 skip_list(&cmd); /* Personal mailboxes */
760 skip_list(&cmd); /* Others' mailboxes */
761 skip_list(&cmd); /* Shared mailboxes */
762 } else if (!strcmp("OK", arg) || !strcmp("BAD", arg) ||
763 !strcmp("NO", arg) || !strcmp("BYE", arg)) {
764 if ((resp = parse_response_code(ctx, NULL, cmd)) != RESP_OK)
765 return resp;
766 } else if (!strcmp("CAPABILITY", arg)) {
767 parse_capability(imap, cmd);
768 } else if ((arg1 = next_arg(&cmd))) {
769 ; /*
770 * Unhandled response-data with at least two words.
771 * Ignore it.
772 *
773 * NEEDSWORK: Previously this case handled '<num> EXISTS'
774 * and '<num> RECENT' but as a probably-unintended side
775 * effect it ignores other unrecognized two-word
776 * responses. imap-send doesn't ever try to read
777 * messages or mailboxes these days, so consider
778 * eliminating this case.
779 */
780 } else {
781 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
782 return RESP_BAD;
783 }
784 } else if (!imap->in_progress) {
785 fprintf(stderr, "IMAP error: unexpected reply: %s %s\n", arg, cmd ? cmd : "");
786 return RESP_BAD;
787 } else if (*arg == '+') {
788 /* This can happen only with the last command underway, as
789 it enforces a round-trip. */
790 cmdp = (struct imap_cmd *)((char *)imap->in_progress_append -
791 offsetof(struct imap_cmd, next));
792 if (cmdp->cb.data) {
793 n = socket_write(&imap->buf.sock, cmdp->cb.data, cmdp->cb.dlen);
794 FREE_AND_NULL(cmdp->cb.data);
795 if (n != (int)cmdp->cb.dlen)
796 return RESP_BAD;
797 } else if (cmdp->cb.cont) {
798 if (cmdp->cb.cont(ctx, cmd))
799 return RESP_BAD;
800 } else {
801 fprintf(stderr, "IMAP error: unexpected command continuation request\n");
802 return RESP_BAD;
803 }
804 if (socket_write(&imap->buf.sock, "\r\n", 2) != 2)
805 return RESP_BAD;
806 if (!cmdp->cb.cont)
807 imap->literal_pending = 0;
808 if (!tcmd)
809 return DRV_OK;
810 } else {
811 if (strtol_i(arg, 10, &tag)) {
812 fprintf(stderr, "IMAP error: malformed tag %s\n", arg);
813 return RESP_BAD;
814 }
815 for (pcmdp = &imap->in_progress; (cmdp = *pcmdp); pcmdp = &cmdp->next)
816 if (cmdp->tag == tag)
817 goto gottag;
818 fprintf(stderr, "IMAP error: unexpected tag %s\n", arg);
819 return RESP_BAD;
820 gottag:
821 if (!(*pcmdp = cmdp->next))
822 imap->in_progress_append = pcmdp;
823 imap->num_in_progress--;
824 if (cmdp->cb.cont || cmdp->cb.data)
825 imap->literal_pending = 0;
826 arg = next_arg(&cmd);
827 if (!arg)
828 arg = "";
829 if (!strcmp("OK", arg))
830 resp = DRV_OK;
831 else {
832 if (!strcmp("NO", arg))
833 resp = RESP_NO;
834 else /*if (!strcmp("BAD", arg))*/
835 resp = RESP_BAD;
836 fprintf(stderr, "IMAP command '%s' returned response (%s) - %s\n",
837 !starts_with(cmdp->cmd, "LOGIN") ?
838 cmdp->cmd : "LOGIN <user> <pass>",
839 arg, cmd ? cmd : "");
840 }
841 if ((resp2 = parse_response_code(ctx, &cmdp->cb, cmd)) > resp)
842 resp = resp2;
843 free(cmdp->cb.data);
844 free(cmdp->cmd);
845 free(cmdp);
846 if (!tcmd || tcmd == cmdp)
847 return resp;
848 }
849 }
850 /* not reached */
851}
852
853static void imap_close_server(struct imap_store *ictx)
854{
855 struct imap *imap = ictx->imap;
856
857 if (imap->buf.sock.fd[0] != -1) {
858 imap_exec(ictx, NULL, "LOGOUT");
859 socket_shutdown(&imap->buf.sock);
860 }
861 free(imap);
862}
863
864static void imap_close_store(struct imap_store *ctx)
865{
866 imap_close_server(ctx);
867 free(ctx);
868}
869
870#ifndef NO_OPENSSL
871
872/*
873 * hexchar() and cram() functions are based on the code from the isync
874 * project (https://isync.sourceforge.io/).
875 */
876static char hexchar(unsigned int b)
877{
878 return b < 10 ? '0' + b : 'a' + (b - 10);
879}
880
881#define ENCODED_SIZE(n) (4 * DIV_ROUND_UP((n), 3))
882static char *plain_base64(const char *user, const char *pass)
883{
884 struct strbuf raw = STRBUF_INIT;
885 int b64_len;
886 char *b64;
887
888 /*
889 * Compose the PLAIN string
890 *
891 * The username and password are combined to one string and base64 encoded.
892 * "\0user\0pass"
893 *
894 * The method has been described in RFC4616.
895 *
896 * https://datatracker.ietf.org/doc/html/rfc4616
897 */
898 strbuf_addch(&raw, '\0');
899 strbuf_addstr(&raw, user);
900 strbuf_addch(&raw, '\0');
901 strbuf_addstr(&raw, pass);
902
903 b64 = xmallocz(ENCODED_SIZE(raw.len));
904 b64_len = EVP_EncodeBlock((unsigned char *)b64, (unsigned char *)raw.buf, raw.len);
905 strbuf_release(&raw);
906
907 if (b64_len < 0) {
908 free(b64);
909 return NULL;
910 }
911 return b64;
912}
913
914static char *cram(const char *challenge_64, const char *user, const char *pass)
915{
916 int i, resp_len, encoded_len, decoded_len;
917 unsigned char hash[16];
918 char hex[33];
919 char *response, *response_64, *challenge;
920
921 /*
922 * length of challenge_64 (i.e. base-64 encoded string) is a good
923 * enough upper bound for challenge (decoded result).
924 */
925 encoded_len = strlen(challenge_64);
926 challenge = xmalloc(encoded_len);
927 decoded_len = EVP_DecodeBlock((unsigned char *)challenge,
928 (unsigned char *)challenge_64, encoded_len);
929 if (decoded_len < 0)
930 die("invalid challenge %s", challenge_64);
931 if (!HMAC(EVP_md5(), pass, strlen(pass), (unsigned char *)challenge, decoded_len, hash, NULL))
932 die("HMAC error");
933
934 hex[32] = 0;
935 for (i = 0; i < 16; i++) {
936 hex[2 * i] = hexchar((hash[i] >> 4) & 0xf);
937 hex[2 * i + 1] = hexchar(hash[i] & 0xf);
938 }
939
940 /* response: "<user> <digest in hex>" */
941 response = xstrfmt("%s %s", user, hex);
942 resp_len = strlen(response);
943
944 response_64 = xmallocz(ENCODED_SIZE(resp_len));
945 encoded_len = EVP_EncodeBlock((unsigned char *)response_64,
946 (unsigned char *)response, resp_len);
947 if (encoded_len < 0)
948 die("EVP_EncodeBlock error");
949 return (char *)response_64;
950}
951
952static char *oauthbearer_base64(const char *user, const char *access_token)
953{
954 int b64_len;
955 char *raw, *b64;
956
957 /*
958 * Compose the OAUTHBEARER string
959 *
960 * "n,a=" {User} ",^Ahost=" {Host} "^Aport=" {Port} "^Aauth=Bearer " {Access Token} "^A^A
961 *
962 * The first part `n,a=" {User} ",` is the gs2 header described in RFC5801.
963 * * gs2-cb-flag `n` -> client does not support CB
964 * * gs2-authzid `a=" {User} "`
965 *
966 * The second part are key value pairs containing host, port and auth as
967 * described in RFC7628.
968 *
969 * https://datatracker.ietf.org/doc/html/rfc5801
970 * https://datatracker.ietf.org/doc/html/rfc7628
971 */
972 raw = xstrfmt("n,a=%s,\001auth=Bearer %s\001\001", user, access_token);
973
974 /* Base64 encode */
975 b64 = xmallocz(ENCODED_SIZE(strlen(raw)));
976 b64_len = EVP_EncodeBlock((unsigned char *)b64, (unsigned char *)raw, strlen(raw));
977 free(raw);
978
979 if (b64_len < 0) {
980 free(b64);
981 return NULL;
982 }
983 return b64;
984}
985
986static char *xoauth2_base64(const char *user, const char *access_token)
987{
988 int b64_len;
989 char *raw, *b64;
990
991 /*
992 * Compose the XOAUTH2 string
993 * "user=" {User} "^Aauth=Bearer " {Access Token} "^A^A"
994 * https://developers.google.com/workspace/gmail/imap/xoauth2-protocol#initial_client_response
995 */
996 raw = xstrfmt("user=%s\001auth=Bearer %s\001\001", user, access_token);
997
998 /* Base64 encode */
999 b64 = xmallocz(ENCODED_SIZE(strlen(raw)));
1000 b64_len = EVP_EncodeBlock((unsigned char *)b64, (unsigned char *)raw, strlen(raw));
1001 free(raw);
1002
1003 if (b64_len < 0) {
1004 free(b64);
1005 return NULL;
1006 }
1007 return b64;
1008}
1009
1010static int auth_plain(struct imap_store *ctx, const char *prompt UNUSED)
1011{
1012 int ret;
1013 char *b64;
1014
1015 b64 = plain_base64(ctx->cfg->user, ctx->cfg->pass);
1016 if (!b64)
1017 return error("PLAIN: base64 encoding failed");
1018
1019 /* Send the base64-encoded response */
1020 ret = socket_write(&ctx->imap->buf.sock, b64, strlen(b64));
1021 if (ret != (int)strlen(b64)) {
1022 free(b64);
1023 return error("IMAP error: sending PLAIN response failed");
1024 }
1025
1026 free(b64);
1027 return 0;
1028}
1029
1030static int auth_cram_md5(struct imap_store *ctx, const char *prompt)
1031{
1032 int ret;
1033 char *response;
1034
1035 response = cram(prompt, ctx->cfg->user, ctx->cfg->pass);
1036
1037 ret = socket_write(&ctx->imap->buf.sock, response, strlen(response));
1038 if (ret != strlen(response)) {
1039 free(response);
1040 return error("IMAP error: sending CRAM-MD5 response failed");
1041 }
1042
1043 free(response);
1044
1045 return 0;
1046}
1047
1048static int auth_oauthbearer(struct imap_store *ctx, const char *prompt UNUSED)
1049{
1050 int ret;
1051 char *b64;
1052
1053 b64 = oauthbearer_base64(ctx->cfg->user, ctx->cfg->pass);
1054 if (!b64)
1055 return error("OAUTHBEARER: base64 encoding failed");
1056
1057 /* Send the base64-encoded response */
1058 ret = socket_write(&ctx->imap->buf.sock, b64, strlen(b64));
1059 if (ret != (int)strlen(b64)) {
1060 free(b64);
1061 return error("IMAP error: sending OAUTHBEARER response failed");
1062 }
1063
1064 free(b64);
1065 return 0;
1066}
1067
1068static int auth_xoauth2(struct imap_store *ctx, const char *prompt UNUSED)
1069{
1070 int ret;
1071 char *b64;
1072
1073 b64 = xoauth2_base64(ctx->cfg->user, ctx->cfg->pass);
1074 if (!b64)
1075 return error("XOAUTH2: base64 encoding failed");
1076
1077 /* Send the base64-encoded response */
1078 ret = socket_write(&ctx->imap->buf.sock, b64, strlen(b64));
1079 if (ret != (int)strlen(b64)) {
1080 free(b64);
1081 return error("IMAP error: sending XOAUTH2 response failed");
1082 }
1083
1084 free(b64);
1085 return 0;
1086}
1087
1088#else
1089
1090#define auth_plain NULL
1091#define auth_cram_md5 NULL
1092#define auth_oauthbearer NULL
1093#define auth_xoauth2 NULL
1094
1095#endif
1096
1097static void server_fill_credential(struct imap_server_conf *srvc, struct credential *cred)
1098{
1099 if (srvc->user && srvc->pass)
1100 return;
1101
1102 cred->protocol = xstrdup(srvc->use_ssl ? "imaps" : "imap");
1103 cred->host = xstrfmt("%s:%d", srvc->host, srvc->port);
1104
1105 cred->username = xstrdup_or_null(srvc->user);
1106 cred->password = xstrdup_or_null(srvc->pass);
1107
1108 credential_fill(the_repository, cred, 1);
1109
1110 if (!srvc->user)
1111 srvc->user = xstrdup(cred->username);
1112 if (!srvc->pass)
1113 srvc->pass = xstrdup(cred->password);
1114}
1115
1116static int try_auth_method(struct imap_server_conf *srvc,
1117 struct imap_store *ctx,
1118 struct imap *imap,
1119 const char *auth_method,
1120 enum CAPABILITY cap,
1121 int (*fn)(struct imap_store *, const char *))
1122{
1123 struct imap_cmd_cb cb = {0};
1124
1125 if (!CAP(cap)) {
1126 fprintf(stderr, "You specified "
1127 "%s as authentication method, "
1128 "but %s doesn't support it.\n",
1129 auth_method, srvc->host);
1130 return -1;
1131 }
1132 cb.cont = fn;
1133
1134 if (NOT_CONSTANT(!cb.cont)) {
1135 fprintf(stderr, "If you want to use %s authentication mechanism, "
1136 "you have to build git-imap-send with OpenSSL library.",
1137 auth_method);
1138 return -1;
1139 }
1140 if (imap_exec(ctx, &cb, "AUTHENTICATE %s", auth_method) != RESP_OK) {
1141 fprintf(stderr, "IMAP error: AUTHENTICATE %s failed\n",
1142 auth_method);
1143 return -1;
1144 }
1145 return 0;
1146}
1147
1148static struct imap_store *imap_open_store(struct imap_server_conf *srvc, const char *folder)
1149{
1150 struct credential cred = CREDENTIAL_INIT;
1151 struct imap_store *ctx;
1152 struct imap *imap;
1153 char *arg, *rsp;
1154 int s = -1, preauth;
1155
1156 CALLOC_ARRAY(ctx, 1);
1157
1158 ctx->cfg = srvc;
1159 ctx->imap = CALLOC_ARRAY(imap, 1);
1160 imap->buf.sock.fd[0] = imap->buf.sock.fd[1] = -1;
1161 imap->in_progress_append = &imap->in_progress;
1162
1163 /* open connection to IMAP server */
1164
1165 if (srvc->tunnel) {
1166 struct child_process tunnel = CHILD_PROCESS_INIT;
1167
1168 imap_info("Starting tunnel '%s'... ", srvc->tunnel);
1169
1170 strvec_push(&tunnel.args, srvc->tunnel);
1171 tunnel.use_shell = 1;
1172 tunnel.in = -1;
1173 tunnel.out = -1;
1174 if (start_command(&tunnel))
1175 die("cannot start proxy %s", srvc->tunnel);
1176
1177 imap->buf.sock.fd[0] = tunnel.out;
1178 imap->buf.sock.fd[1] = tunnel.in;
1179
1180 imap_info("OK\n");
1181 } else {
1182#ifndef NO_IPV6
1183 struct addrinfo hints, *ai0, *ai;
1184 int gai;
1185 char portstr[6];
1186
1187 xsnprintf(portstr, sizeof(portstr), "%d", srvc->port);
1188
1189 memset(&hints, 0, sizeof(hints));
1190 hints.ai_socktype = SOCK_STREAM;
1191 hints.ai_protocol = IPPROTO_TCP;
1192
1193 imap_info("Resolving %s... ", srvc->host);
1194 gai = getaddrinfo(srvc->host, portstr, &hints, &ai);
1195 if (gai) {
1196 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai));
1197 goto bail;
1198 }
1199 imap_info("OK\n");
1200
1201 for (ai0 = ai; ai; ai = ai->ai_next) {
1202 char addr[NI_MAXHOST];
1203
1204 s = socket(ai->ai_family, ai->ai_socktype,
1205 ai->ai_protocol);
1206 if (s < 0)
1207 continue;
1208
1209 getnameinfo(ai->ai_addr, ai->ai_addrlen, addr,
1210 sizeof(addr), NULL, 0, NI_NUMERICHOST);
1211 imap_info("Connecting to [%s]:%s... ", addr, portstr);
1212
1213 if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0) {
1214 close(s);
1215 s = -1;
1216 perror("connect");
1217 continue;
1218 }
1219
1220 break;
1221 }
1222 freeaddrinfo(ai0);
1223#else /* NO_IPV6 */
1224 struct hostent *he;
1225 struct sockaddr_in addr;
1226
1227 memset(&addr, 0, sizeof(addr));
1228 addr.sin_port = htons(srvc->port);
1229 addr.sin_family = AF_INET;
1230
1231 imap_info("Resolving %s... ", srvc->host);
1232 he = gethostbyname(srvc->host);
1233 if (!he) {
1234 perror("gethostbyname");
1235 goto bail;
1236 }
1237 imap_info("OK\n");
1238
1239 addr.sin_addr.s_addr = *((int *) he->h_addr_list[0]);
1240
1241 s = socket(PF_INET, SOCK_STREAM, 0);
1242
1243 imap_info("Connecting to %s:%hu... ", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
1244 if (connect(s, (struct sockaddr *)&addr, sizeof(addr))) {
1245 close(s);
1246 s = -1;
1247 perror("connect");
1248 }
1249#endif
1250 if (s < 0) {
1251 fputs("error: unable to connect to server\n", stderr);
1252 goto bail;
1253 }
1254
1255 imap->buf.sock.fd[0] = s;
1256 imap->buf.sock.fd[1] = dup(s);
1257
1258 if (srvc->use_ssl &&
1259 ssl_socket_connect(&imap->buf.sock, srvc, 0)) {
1260 close(s);
1261 goto bail;
1262 }
1263 imap_info("OK\n");
1264 }
1265
1266 /* read the greeting string */
1267 if (buffer_gets(&imap->buf, &rsp)) {
1268 fprintf(stderr, "IMAP error: no greeting response\n");
1269 goto bail;
1270 }
1271 arg = next_arg(&rsp);
1272 if (!arg || *arg != '*' || (arg = next_arg(&rsp)) == NULL) {
1273 fprintf(stderr, "IMAP error: invalid greeting response\n");
1274 goto bail;
1275 }
1276 preauth = 0;
1277 if (!strcmp("PREAUTH", arg))
1278 preauth = 1;
1279 else if (strcmp("OK", arg) != 0) {
1280 fprintf(stderr, "IMAP error: unknown greeting response\n");
1281 goto bail;
1282 }
1283 parse_response_code(ctx, NULL, rsp);
1284 if (!imap->caps && imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1285 goto bail;
1286
1287 if (!preauth) {
1288#ifndef NO_OPENSSL
1289 if (!srvc->use_ssl && CAP(STARTTLS)) {
1290 if (imap_exec(ctx, NULL, "STARTTLS") != RESP_OK)
1291 goto bail;
1292 if (ssl_socket_connect(&imap->buf.sock, srvc, 1))
1293 goto bail;
1294 /* capabilities may have changed, so get the new capabilities */
1295 if (imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1296 goto bail;
1297 }
1298#endif
1299 imap_info("Logging in...\n");
1300 server_fill_credential(srvc, &cred);
1301
1302 if (srvc->auth_method) {
1303 if (!strcmp(srvc->auth_method, "PLAIN")) {
1304 if (try_auth_method(srvc, ctx, imap, "PLAIN", AUTH_PLAIN, auth_plain))
1305 goto bail;
1306 } else if (!strcmp(srvc->auth_method, "CRAM-MD5")) {
1307 if (try_auth_method(srvc, ctx, imap, "CRAM-MD5", AUTH_CRAM_MD5, auth_cram_md5))
1308 goto bail;
1309 } else if (!strcmp(srvc->auth_method, "OAUTHBEARER")) {
1310 if (try_auth_method(srvc, ctx, imap, "OAUTHBEARER", AUTH_OAUTHBEARER, auth_oauthbearer))
1311 goto bail;
1312 } else if (!strcmp(srvc->auth_method, "XOAUTH2")) {
1313 if (try_auth_method(srvc, ctx, imap, "XOAUTH2", AUTH_XOAUTH2, auth_xoauth2))
1314 goto bail;
1315 } else {
1316 fprintf(stderr, "unknown authentication mechanism: %s\n", srvc->auth_method);
1317 goto bail;
1318 }
1319 } else {
1320 if (CAP(NOLOGIN)) {
1321 fprintf(stderr, "skipping account %s@%s, server forbids LOGIN\n",
1322 srvc->user, srvc->host);
1323 goto bail;
1324 }
1325 if (!imap->buf.sock.ssl)
1326 imap_warn("*** IMAP Warning *** Password is being "
1327 "sent in the clear\n");
1328 if (imap_exec(ctx, NULL, "LOGIN \"%s\" \"%s\"", srvc->user, srvc->pass) != RESP_OK) {
1329 fprintf(stderr, "IMAP error: LOGIN failed\n");
1330 goto bail;
1331 }
1332 }
1333 } /* !preauth */
1334
1335 if (cred.username)
1336 credential_approve(the_repository, &cred);
1337 credential_clear(&cred);
1338
1339 /* check the target mailbox exists */
1340 ctx->name = folder;
1341 switch (imap_exec(ctx, NULL, "EXAMINE \"%s\"", ctx->name)) {
1342 case RESP_OK:
1343 /* ok */
1344 break;
1345 case RESP_BAD:
1346 fprintf(stderr, "IMAP error: could not check mailbox\n");
1347 goto out;
1348 case RESP_NO:
1349 if (imap_exec(ctx, NULL, "CREATE \"%s\"", ctx->name) == RESP_OK) {
1350 imap_info("Created missing mailbox\n");
1351 } else {
1352 fprintf(stderr, "IMAP error: could not create missing mailbox\n");
1353 goto out;
1354 }
1355 break;
1356 }
1357
1358 ctx->prefix = "";
1359 return ctx;
1360
1361bail:
1362 if (cred.username)
1363 credential_reject(the_repository, &cred);
1364 credential_clear(&cred);
1365
1366 out:
1367 imap_close_store(ctx);
1368 return NULL;
1369}
1370
1371/*
1372 * Insert CR characters as necessary in *msg to ensure that every LF
1373 * character in *msg is preceded by a CR.
1374 */
1375static void lf_to_crlf(struct strbuf *msg)
1376{
1377 char *new_msg;
1378 size_t i, j;
1379 char lastc;
1380
1381 /* First pass: tally, in j, the size of the new_msg string: */
1382 for (i = j = 0, lastc = '\0'; i < msg->len; i++) {
1383 if (msg->buf[i] == '\n' && lastc != '\r')
1384 j++; /* a CR will need to be added here */
1385 lastc = msg->buf[i];
1386 j++;
1387 }
1388
1389 new_msg = xmallocz(j);
1390
1391 /*
1392 * Second pass: write the new_msg string. Note that this loop is
1393 * otherwise identical to the first pass.
1394 */
1395 for (i = j = 0, lastc = '\0'; i < msg->len; i++) {
1396 if (msg->buf[i] == '\n' && lastc != '\r')
1397 new_msg[j++] = '\r';
1398 lastc = new_msg[j++] = msg->buf[i];
1399 }
1400 strbuf_attach(msg, new_msg, j, j + 1);
1401}
1402
1403/*
1404 * Store msg to IMAP. Also detach and free the data from msg->data,
1405 * leaving msg->data empty.
1406 */
1407static int imap_store_msg(struct imap_store *ctx, struct strbuf *msg)
1408{
1409 struct imap *imap = ctx->imap;
1410 struct imap_cmd_cb cb;
1411 const char *prefix, *box;
1412 int ret;
1413
1414 lf_to_crlf(msg);
1415 memset(&cb, 0, sizeof(cb));
1416
1417 cb.dlen = msg->len;
1418 cb.data = strbuf_detach(msg, NULL);
1419
1420 box = ctx->name;
1421 prefix = !strcmp(box, "INBOX") ? "" : ctx->prefix;
1422 ret = imap_exec_m(ctx, &cb, "APPEND \"%s%s\" %s", prefix, box,
1423 opt_draft ? "(\\Draft) " : "");
1424 imap->caps = imap->rcaps;
1425 if (ret != DRV_OK)
1426 return ret;
1427
1428 return DRV_OK;
1429}
1430
1431static void wrap_in_html(struct strbuf *msg)
1432{
1433 struct strbuf buf = STRBUF_INIT;
1434 static const char *content_type = "Content-Type: text/html;\n";
1435 static const char *pre_open = "<pre>\n";
1436 static const char *pre_close = "</pre>\n";
1437 const char *body = strstr(msg->buf, "\n\n");
1438
1439 if (!body)
1440 return; /* Headers but no body; no wrapping needed */
1441
1442 body += 2;
1443
1444 strbuf_add(&buf, msg->buf, body - msg->buf - 1);
1445 strbuf_addstr(&buf, content_type);
1446 strbuf_addch(&buf, '\n');
1447 strbuf_addstr(&buf, pre_open);
1448 strbuf_addstr_xml_quoted(&buf, body);
1449 strbuf_addstr(&buf, pre_close);
1450
1451 strbuf_release(msg);
1452 *msg = buf;
1453}
1454
1455static int count_messages(struct strbuf *all_msgs)
1456{
1457 int count = 0;
1458 char *p = all_msgs->buf;
1459
1460 while (1) {
1461 if (starts_with(p, "From ")) {
1462 if (starts_with(p, "From git-send-email")) {
1463 p = strstr(p+5, "\nFrom: ");
1464 if (!p) break;
1465 p += 7;
1466 p = strstr(p, "\nTo: ");
1467 if (!p) break;
1468 p += 5;
1469 count++;
1470 } else {
1471 p = strstr(p+5, "\nFrom: ");
1472 if (!p) break;
1473 p = strstr(p+7, "\nDate: ");
1474 if (!p) break;
1475 p = strstr(p+7, "\nSubject: ");
1476 if (!p) break;
1477 p += 10;
1478 count++;
1479 }
1480 }
1481 p = strstr(p+5, "\nFrom ");
1482 if (!p)
1483 break;
1484 p++;
1485 }
1486 return count;
1487}
1488
1489/*
1490 * Copy the next message from all_msgs, starting at offset *ofs, to
1491 * msg. Update *ofs to the start of the following message. Return
1492 * true iff a message was successfully copied.
1493 */
1494static int split_msg(struct strbuf *all_msgs, struct strbuf *msg, int *ofs)
1495{
1496 char *p, *data;
1497 size_t len;
1498
1499 if (*ofs >= all_msgs->len)
1500 return 0;
1501
1502 data = &all_msgs->buf[*ofs];
1503 len = all_msgs->len - *ofs;
1504
1505 if (len < 5 || !starts_with(data, "From "))
1506 return 0;
1507
1508 p = strchr(data, '\n');
1509 if (p) {
1510 p++;
1511 len -= p - data;
1512 *ofs += p - data;
1513 data = p;
1514 }
1515
1516 p = strstr(data, "\nFrom ");
1517 if (p)
1518 len = &p[1] - data;
1519
1520 strbuf_add(msg, data, len);
1521 *ofs += len;
1522 return 1;
1523}
1524
1525static int git_imap_config(const char *var, const char *val,
1526 const struct config_context *ctx, void *cb)
1527{
1528 struct imap_server_conf *cfg = cb;
1529
1530 if (!strcmp("imap.sslverify", var)) {
1531 cfg->ssl_verify = git_config_bool(var, val);
1532 } else if (!strcmp("imap.preformattedhtml", var)) {
1533 cfg->use_html = git_config_bool(var, val);
1534 } else if (!strcmp("imap.folder", var)) {
1535 FREE_AND_NULL(cfg->folder);
1536 return git_config_string(&cfg->folder, var, val);
1537 } else if (!strcmp("imap.user", var)) {
1538 FREE_AND_NULL(cfg->user);
1539 return git_config_string(&cfg->user, var, val);
1540 } else if (!strcmp("imap.pass", var)) {
1541 FREE_AND_NULL(cfg->pass);
1542 return git_config_string(&cfg->pass, var, val);
1543 } else if (!strcmp("imap.tunnel", var)) {
1544 FREE_AND_NULL(cfg->tunnel);
1545 return git_config_string(&cfg->tunnel, var, val);
1546 } else if (!strcmp("imap.authmethod", var)) {
1547 FREE_AND_NULL(cfg->auth_method);
1548 return git_config_string(&cfg->auth_method, var, val);
1549 } else if (!strcmp("imap.port", var)) {
1550 cfg->port = git_config_int(var, val, ctx->kvi);
1551 } else if (!strcmp("imap.host", var)) {
1552 if (!val) {
1553 return config_error_nonbool(var);
1554 } else {
1555 if (starts_with(val, "imap:"))
1556 val += 5;
1557 else if (starts_with(val, "imaps:")) {
1558 val += 6;
1559 cfg->use_ssl = 1;
1560 }
1561 if (starts_with(val, "//"))
1562 val += 2;
1563 cfg->host = xstrdup(val);
1564 }
1565 } else {
1566 return git_default_config(var, val, ctx, cb);
1567 }
1568
1569 return 0;
1570}
1571
1572static int append_msgs_to_imap(struct imap_server_conf *server,
1573 struct strbuf* all_msgs, int total)
1574{
1575 struct strbuf msg = STRBUF_INIT;
1576 struct imap_store *ctx = NULL;
1577 int ofs = 0;
1578 int r;
1579 int n = 0;
1580
1581 ctx = imap_open_store(server, server->folder);
1582 if (!ctx) {
1583 fprintf(stderr, "failed to open store\n");
1584 return 1;
1585 }
1586 ctx->name = server->folder;
1587
1588 fprintf(stderr, "Sending %d message%s to %s folder...\n",
1589 total, (total != 1) ? "s" : "", server->folder);
1590 while (1) {
1591 unsigned percent = n * 100 / total;
1592
1593 fprintf(stderr, "%4u%% (%d/%d) done\r", percent, n, total);
1594
1595 if (!split_msg(all_msgs, &msg, &ofs))
1596 break;
1597 if (server->use_html)
1598 wrap_in_html(&msg);
1599 r = imap_store_msg(ctx, &msg);
1600 if (r != DRV_OK)
1601 break;
1602 n++;
1603 }
1604 fprintf(stderr, "\n");
1605
1606 imap_close_store(ctx);
1607
1608 return 0;
1609}
1610
1611static int list_imap_folders(struct imap_server_conf *server)
1612{
1613 struct imap_store *ctx = imap_open_store(server, "INBOX");
1614 if (!ctx) {
1615 fprintf(stderr, "failed to connect to IMAP server\n");
1616 return 1;
1617 }
1618
1619 fprintf(stderr, "Fetching the list of available folders...\n");
1620 /* Issue the LIST command and print the results */
1621 if (imap_exec(ctx, NULL, "LIST \"\" \"*\"") != RESP_OK) {
1622 fprintf(stderr, "failed to list folders\n");
1623 imap_close_store(ctx);
1624 return 1;
1625 }
1626
1627 imap_close_store(ctx);
1628 return 0;
1629}
1630
1631#ifdef USE_CURL_FOR_IMAP_SEND
1632static CURL *setup_curl(struct imap_server_conf *srvc, struct credential *cred)
1633{
1634 CURL *curl;
1635 struct strbuf path = STRBUF_INIT;
1636 char *uri_encoded_folder;
1637
1638 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
1639 die("curl_global_init failed");
1640
1641 curl = curl_easy_init();
1642
1643 if (!curl)
1644 die("curl_easy_init failed");
1645
1646 server_fill_credential(srvc, cred);
1647 curl_easy_setopt(curl, CURLOPT_USERNAME, srvc->user);
1648
1649 /*
1650 * Use CURLOPT_PASSWORD irrespective of whether there is
1651 * an auth method specified or not, unless it's OAuth2.0,
1652 * where we use CURLOPT_XOAUTH2_BEARER.
1653 */
1654 if (!srvc->auth_method ||
1655 (strcmp(srvc->auth_method, "XOAUTH2") &&
1656 strcmp(srvc->auth_method, "OAUTHBEARER")))
1657 curl_easy_setopt(curl, CURLOPT_PASSWORD, srvc->pass);
1658
1659 strbuf_addstr(&path, srvc->use_ssl ? "imaps://" : "imap://");
1660 strbuf_addstr(&path, srvc->host);
1661 if (!path.len || path.buf[path.len - 1] != '/')
1662 strbuf_addch(&path, '/');
1663
1664 if (!list_folders) {
1665 uri_encoded_folder = curl_easy_escape(curl, srvc->folder, 0);
1666 if (!uri_encoded_folder)
1667 die("failed to encode server folder");
1668 strbuf_addstr(&path, uri_encoded_folder);
1669 curl_free(uri_encoded_folder);
1670 }
1671
1672 curl_easy_setopt(curl, CURLOPT_URL, path.buf);
1673 strbuf_release(&path);
1674 curl_easy_setopt(curl, CURLOPT_PORT, (long)srvc->port);
1675
1676 if (srvc->auth_method) {
1677 if (!strcmp(srvc->auth_method, "XOAUTH2") ||
1678 !strcmp(srvc->auth_method, "OAUTHBEARER")) {
1679
1680 /*
1681 * While CURLOPT_XOAUTH2_BEARER looks as if it only supports XOAUTH2,
1682 * upon debugging, it has been found that it is capable of detecting
1683 * the best option out of OAUTHBEARER and XOAUTH2.
1684 */
1685 curl_easy_setopt(curl, CURLOPT_XOAUTH2_BEARER, srvc->pass);
1686 } else {
1687 struct strbuf auth = STRBUF_INIT;
1688 strbuf_addstr(&auth, "AUTH=");
1689 strbuf_addstr(&auth, srvc->auth_method);
1690 curl_easy_setopt(curl, CURLOPT_LOGIN_OPTIONS, auth.buf);
1691 strbuf_release(&auth);
1692 }
1693 }
1694
1695 if (!srvc->use_ssl)
1696 curl_easy_setopt(curl, CURLOPT_USE_SSL, (long)CURLUSESSL_TRY);
1697
1698 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, (long)srvc->ssl_verify);
1699 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, (long)srvc->ssl_verify);
1700
1701 if (0 < verbosity || getenv("GIT_CURL_VERBOSE"))
1702 http_trace_curl_no_data();
1703 setup_curl_trace(curl);
1704
1705 return curl;
1706}
1707
1708static int curl_append_msgs_to_imap(struct imap_server_conf *server,
1709 struct strbuf* all_msgs, int total)
1710{
1711 int ofs = 0;
1712 int n = 0;
1713 struct buffer msgbuf = { STRBUF_INIT, 0 };
1714 CURL *curl;
1715 CURLcode res = CURLE_OK;
1716 struct credential cred = CREDENTIAL_INIT;
1717
1718 curl = setup_curl(server, &cred);
1719
1720 curl_easy_setopt(curl, CURLOPT_READFUNCTION, fread_buffer);
1721 curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
1722
1723 curl_easy_setopt(curl, CURLOPT_READDATA, &msgbuf);
1724
1725 if (opt_draft) {
1726#ifdef GIT_CURL_HAVE_CURLOPT_UPLOAD_FLAGS
1727 curl_easy_setopt(curl, CURLOPT_UPLOAD_FLAGS, CURLULFLAG_DRAFT);
1728#else
1729 warning("--draft requires libcurl 8.13.0 or later");
1730#endif
1731 }
1732 fprintf(stderr, "Sending %d message%s to %s folder...\n",
1733 total, (total != 1) ? "s" : "", server->folder);
1734 while (1) {
1735 unsigned percent = n * 100 / total;
1736 int prev_len;
1737
1738 fprintf(stderr, "%4u%% (%d/%d) done\r", percent, n, total);
1739
1740 prev_len = msgbuf.buf.len;
1741 if (!split_msg(all_msgs, &msgbuf.buf, &ofs))
1742 break;
1743 if (server->use_html)
1744 wrap_in_html(&msgbuf.buf);
1745 lf_to_crlf(&msgbuf.buf);
1746
1747 curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE,
1748 cast_size_t_to_curl_off_t(msgbuf.buf.len-prev_len));
1749
1750 res = curl_easy_perform(curl);
1751
1752 if(res != CURLE_OK) {
1753 fprintf(stderr, "curl_easy_perform() failed: %s\n",
1754 curl_easy_strerror(res));
1755 break;
1756 }
1757
1758 n++;
1759 }
1760 fprintf(stderr, "\n");
1761
1762 curl_easy_cleanup(curl);
1763 curl_global_cleanup();
1764 strbuf_release(&msgbuf.buf);
1765
1766 if (cred.username) {
1767 if (res == CURLE_OK)
1768 credential_approve(the_repository, &cred);
1769 else if (res == CURLE_LOGIN_DENIED)
1770 credential_reject(the_repository, &cred);
1771 }
1772
1773 credential_clear(&cred);
1774
1775 return res != CURLE_OK;
1776}
1777
1778static int curl_list_imap_folders(struct imap_server_conf *server)
1779{
1780 CURL *curl;
1781 CURLcode res = CURLE_OK;
1782 struct credential cred = CREDENTIAL_INIT;
1783
1784 fprintf(stderr, "Fetching the list of available folders...\n");
1785 curl = setup_curl(server, &cred);
1786 res = curl_easy_perform(curl);
1787
1788 curl_easy_cleanup(curl);
1789 curl_global_cleanup();
1790
1791 if (cred.username) {
1792 if (res == CURLE_OK)
1793 credential_approve(the_repository, &cred);
1794 else if (res == CURLE_LOGIN_DENIED)
1795 credential_reject(the_repository, &cred);
1796 }
1797
1798 credential_clear(&cred);
1799
1800 return res != CURLE_OK;
1801}
1802#endif
1803
1804int cmd_main(int argc, const char **argv)
1805{
1806 struct imap_server_conf server = {
1807 .ssl_verify = 1,
1808 };
1809 struct strbuf all_msgs = STRBUF_INIT;
1810 int total;
1811 int nongit_ok;
1812 int ret;
1813
1814 setup_git_directory_gently(the_repository, &nongit_ok);
1815 repo_config(the_repository, git_imap_config, &server);
1816
1817 argc = parse_options(argc, (const char **)argv, "", imap_send_options, imap_send_usage, 0);
1818
1819 if (opt_folder) {
1820 free(server.folder);
1821 server.folder = xstrdup(opt_folder);
1822 }
1823
1824 if (argc)
1825 usage_with_options(imap_send_usage, imap_send_options);
1826
1827#ifndef USE_CURL_FOR_IMAP_SEND
1828 if (use_curl) {
1829 warning("--curl not supported in this build");
1830 use_curl = 0;
1831 }
1832#elif defined(NO_OPENSSL)
1833 if (!use_curl) {
1834 warning("--no-curl not supported in this build");
1835 use_curl = 1;
1836 }
1837#endif
1838
1839 if (!server.port)
1840 server.port = server.use_ssl ? 993 : 143;
1841
1842 if (!server.host) {
1843 if (!server.tunnel) {
1844 error(_("no IMAP host specified"));
1845 advise(_("set the IMAP host with 'git config imap.host <host>'.\n"
1846 "(e.g., 'git config imap.host imaps://imap.example.com')"));
1847 ret = 1;
1848 goto out;
1849 }
1850 server.host = xstrdup("tunnel");
1851 }
1852
1853 if (list_folders) {
1854 if (server.tunnel)
1855 ret = list_imap_folders(&server);
1856#ifdef USE_CURL_FOR_IMAP_SEND
1857 else if (use_curl)
1858 ret = curl_list_imap_folders(&server);
1859#endif
1860 else
1861 ret = list_imap_folders(&server);
1862 goto out;
1863 }
1864
1865 if (!server.folder) {
1866 error(_("no IMAP folder specified"));
1867 advise(_("set the target folder with 'git config imap.folder <folder>'.\n"
1868 "(e.g., 'git config imap.folder Drafts')"));
1869 ret = 1;
1870 goto out;
1871 }
1872
1873 /* read the messages */
1874 if (strbuf_read(&all_msgs, 0, 0) < 0) {
1875 error_errno(_("could not read from stdin"));
1876 ret = 1;
1877 goto out;
1878 }
1879
1880 if (all_msgs.len == 0) {
1881 fprintf(stderr, "nothing to send\n");
1882 ret = 1;
1883 goto out;
1884 }
1885
1886 total = count_messages(&all_msgs);
1887 if (!total) {
1888 fprintf(stderr, "no messages found to send\n");
1889 ret = 1;
1890 goto out;
1891 }
1892
1893 /* write it to the imap server */
1894
1895 if (server.tunnel)
1896 ret = append_msgs_to_imap(&server, &all_msgs, total);
1897#ifdef USE_CURL_FOR_IMAP_SEND
1898 else if (use_curl)
1899 ret = curl_append_msgs_to_imap(&server, &all_msgs, total);
1900#endif
1901 else
1902 ret = append_msgs_to_imap(&server, &all_msgs, total);
1903
1904out:
1905 free(server.tunnel);
1906 free(server.host);
1907 free(server.folder);
1908 free(server.user);
1909 free(server.pass);
1910 free(server.auth_method);
1911 strbuf_release(&all_msgs);
1912 return ret;
1913}