Merge branch 'bc/hash-independent-tests-part-5'
[git/git.git] / imap-send.c
CommitLineData
f2561fda
MM
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
48425792 21 * along with this program; if not, see <http://www.gnu.org/licenses/>.
f2561fda
MM
22 */
23
24#include "cache.h"
b2141fc1 25#include "config.h"
791643a8 26#include "credential.h"
d807c4a0 27#include "exec-cmd.h"
c94d2dd0 28#include "run-command.h"
f1a35295 29#include "parse-options.h"
684ec6c6
RS
30#ifdef NO_OPENSSL
31typedef void *SSL;
32#endif
1e16b255
BR
33#ifdef USE_CURL_FOR_IMAP_SEND
34#include "http.h"
35#endif
f2561fda 36
dbba42bb
NMC
37#if defined(USE_CURL_FOR_IMAP_SEND)
38/* Always default to curl if it's available. */
dcd01ea1
KM
39#define USE_CURL_DEFAULT 1
40#else
dbba42bb 41/* We don't have curl, so continue to use the historical implementation */
dcd01ea1
KM
42#define USE_CURL_DEFAULT 0
43#endif
44
f1a35295 45static int verbosity;
dcd01ea1 46static int use_curl = USE_CURL_DEFAULT;
f1a35295 47
1e16b255 48static const char * const imap_send_usage[] = { "git imap-send [-v] [-q] [--[no-]curl] < <mbox>", NULL };
f1a35295
BR
49
50static struct option imap_send_options[] = {
51 OPT__VERBOSITY(&verbosity),
1e16b255 52 OPT_BOOL(0, "curl", &use_curl, "use libcurl to communicate with the IMAP server"),
f1a35295
BR
53 OPT_END()
54};
f2561fda 55
d23b1ecf 56#undef DRV_OK
f2561fda
MM
57#define DRV_OK 0
58#define DRV_MSG_BAD -1
59#define DRV_BOX_BAD -2
60#define DRV_STORE_BAD -3
61
28bea9e5 62__attribute__((format (printf, 1, 2)))
95c53908 63static void imap_info(const char *, ...);
28bea9e5 64__attribute__((format (printf, 1, 2)))
95c53908 65static void imap_warn(const char *, ...);
f2561fda 66
95c53908 67static char *next_arg(char **);
f2561fda 68
28bea9e5 69__attribute__((format (printf, 3, 4)))
95c53908 70static int nfsnprintf(char *buf, int blen, const char *fmt, ...);
f2561fda 71
19247e55
PH
72static int nfvasprintf(char **strp, const char *fmt, va_list ap)
73{
74 int len;
75 char tmp[8192];
76
77 len = vsnprintf(tmp, sizeof(tmp), fmt, ap);
78 if (len < 0)
d7530708 79 die("Fatal: Out of memory");
19247e55 80 if (len >= sizeof(tmp))
d7530708 81 die("imap command overflow!");
19247e55
PH
82 *strp = xmemdupz(tmp, len);
83 return len;
84}
f2561fda 85
9f1ad541 86struct imap_server_conf {
f2561fda
MM
87 char *name;
88 char *tunnel;
89 char *host;
90 int port;
39180571 91 char *folder;
f2561fda
MM
92 char *user;
93 char *pass;
684ec6c6
RS
94 int use_ssl;
95 int ssl_verify;
c64d84f1 96 int use_html;
ae9c606e
HM
97 char *auth_method;
98};
99
100static struct imap_server_conf server = {
101 NULL, /* name */
102 NULL, /* tunnel */
103 NULL, /* host */
104 0, /* port */
39180571 105 NULL, /* folder */
ae9c606e
HM
106 NULL, /* user */
107 NULL, /* pass */
108 0, /* use_ssl */
109 1, /* ssl_verify */
110 0, /* use_html */
111 NULL, /* auth_method */
9f1ad541 112};
f2561fda 113
9f1ad541 114struct imap_socket {
7a7796e9 115 int fd[2];
684ec6c6 116 SSL *ssl;
9f1ad541 117};
f2561fda 118
9f1ad541
JH
119struct imap_buffer {
120 struct imap_socket sock;
f2561fda
MM
121 int bytes;
122 int offset;
123 char buf[1024];
9f1ad541 124};
f2561fda
MM
125
126struct imap_cmd;
127
9f1ad541 128struct imap {
f2561fda 129 int uidnext; /* from SELECT responses */
f2561fda
MM
130 unsigned caps, rcaps; /* CAPABILITY results */
131 /* command queue */
132 int nexttag, num_in_progress, literal_pending;
133 struct imap_cmd *in_progress, **in_progress_append;
9f1ad541
JH
134 struct imap_buffer buf; /* this is BIG, so put it last */
135};
f2561fda 136
9f1ad541 137struct imap_store {
636fd66b
MH
138 /* currently open mailbox */
139 const char *name; /* foreign! maybe preset? */
140 int uidvalidity;
9f1ad541 141 struct imap *imap;
f2561fda 142 const char *prefix;
9f1ad541 143};
f2561fda
MM
144
145struct imap_cmd_cb {
9f1ad541
JH
146 int (*cont)(struct imap_store *ctx, struct imap_cmd *cmd, const char *prompt);
147 void (*done)(struct imap_store *ctx, struct imap_cmd *cmd, int response);
f2561fda
MM
148 void *ctx;
149 char *data;
150 int dlen;
151 int uid;
f2561fda
MM
152};
153
154struct imap_cmd {
155 struct imap_cmd *next;
156 struct imap_cmd_cb cb;
157 char *cmd;
158 int tag;
159};
160
161#define CAP(cap) (imap->caps & (1 << (cap)))
162
163enum CAPABILITY {
164 NOLOGIN = 0,
165 UIDPLUS,
166 LITERALPLUS,
167 NAMESPACE,
684ec6c6 168 STARTTLS,
4b05548f 169 AUTH_CRAM_MD5
f2561fda
MM
170};
171
172static const char *cap_list[] = {
173 "LOGINDISABLED",
174 "UIDPLUS",
175 "LITERAL+",
176 "NAMESPACE",
684ec6c6 177 "STARTTLS",
ae9c606e 178 "AUTH=CRAM-MD5",
f2561fda
MM
179};
180
181#define RESP_OK 0
182#define RESP_NO 1
183#define RESP_BAD 2
184
9f1ad541 185static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd);
f2561fda
MM
186
187
684ec6c6
RS
188#ifndef NO_OPENSSL
189static void ssl_socket_perror(const char *func)
190{
2af202be 191 fprintf(stderr, "%s: %s\n", func, ERR_error_string(ERR_get_error(), NULL));
684ec6c6
RS
192}
193#endif
194
9f1ad541 195static void socket_perror(const char *func, struct imap_socket *sock, int ret)
f2561fda 196{
684ec6c6
RS
197#ifndef NO_OPENSSL
198 if (sock->ssl) {
199 int sslerr = SSL_get_error(sock->ssl, ret);
200 switch (sslerr) {
201 case SSL_ERROR_NONE:
202 break;
203 case SSL_ERROR_SYSCALL:
204 perror("SSL_connect");
205 break;
206 default:
207 ssl_socket_perror("SSL_connect");
208 break;
209 }
210 } else
211#endif
212 {
213 if (ret < 0)
214 perror(func);
215 else
216 fprintf(stderr, "%s: unexpected EOF\n", func);
217 }
218}
219
1e1fe529 220#ifdef NO_OPENSSL
9f1ad541 221static int ssl_socket_connect(struct imap_socket *sock, int use_tls_only, int verify)
684ec6c6 222{
684ec6c6
RS
223 fprintf(stderr, "SSL requested but SSL support not compiled in\n");
224 return -1;
1e1fe529
JH
225}
226
1e380ddc 227#else
1e1fe529 228
b62fb077
OB
229static int host_matches(const char *host, const char *pattern)
230{
231 if (pattern[0] == '*' && pattern[1] == '.') {
232 pattern += 2;
233 if (!(host = strchr(host, '.')))
234 return 0;
235 host++;
236 }
237
238 return *host && *pattern && !strcasecmp(host, pattern);
239}
240
241static int verify_hostname(X509 *cert, const char *hostname)
242{
243 int len;
244 X509_NAME *subj;
245 char cname[1000];
e174744a
OB
246 int i, found;
247 STACK_OF(GENERAL_NAME) *subj_alt_names;
248
249 /* try the DNS subjectAltNames */
250 found = 0;
251 if ((subj_alt_names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL))) {
252 int num_subj_alt_names = sk_GENERAL_NAME_num(subj_alt_names);
253 for (i = 0; !found && i < num_subj_alt_names; i++) {
254 GENERAL_NAME *subj_alt_name = sk_GENERAL_NAME_value(subj_alt_names, i);
255 if (subj_alt_name->type == GEN_DNS &&
256 strlen((const char *)subj_alt_name->d.ia5->data) == (size_t)subj_alt_name->d.ia5->length &&
257 host_matches(hostname, (const char *)(subj_alt_name->d.ia5->data)))
258 found = 1;
259 }
260 sk_GENERAL_NAME_pop_free(subj_alt_names, GENERAL_NAME_free);
261 }
262 if (found)
263 return 0;
b62fb077
OB
264
265 /* try the common name */
266 if (!(subj = X509_get_subject_name(cert)))
267 return error("cannot get certificate subject");
268 if ((len = X509_NAME_get_text_by_NID(subj, NID_commonName, cname, sizeof(cname))) < 0)
269 return error("cannot get certificate common name");
270 if (strlen(cname) == (size_t)len && host_matches(hostname, cname))
271 return 0;
272 return error("certificate owner '%s' does not match hostname '%s'",
273 cname, hostname);
274}
275
1e1fe529
JH
276static int ssl_socket_connect(struct imap_socket *sock, int use_tls_only, int verify)
277{
1e380ddc
VL
278#if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
279 const SSL_METHOD *meth;
684ec6c6
RS
280#else
281 SSL_METHOD *meth;
1e380ddc 282#endif
684ec6c6
RS
283 SSL_CTX *ctx;
284 int ret;
b62fb077 285 X509 *cert;
684ec6c6
RS
286
287 SSL_library_init();
288 SSL_load_error_strings();
289
b51c0d4b 290 meth = SSLv23_method();
684ec6c6
RS
291 if (!meth) {
292 ssl_socket_perror("SSLv23_method");
293 return -1;
294 }
295
296 ctx = SSL_CTX_new(meth);
6738a33b
KY
297 if (!ctx) {
298 ssl_socket_perror("SSL_CTX_new");
299 return -1;
300 }
684ec6c6 301
b51c0d4b
KY
302 if (use_tls_only)
303 SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
684ec6c6
RS
304
305 if (verify)
306 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
307
308 if (!SSL_CTX_set_default_verify_paths(ctx)) {
309 ssl_socket_perror("SSL_CTX_set_default_verify_paths");
310 return -1;
311 }
312 sock->ssl = SSL_new(ctx);
313 if (!sock->ssl) {
314 ssl_socket_perror("SSL_new");
315 return -1;
316 }
7a7796e9
EFL
317 if (!SSL_set_rfd(sock->ssl, sock->fd[0])) {
318 ssl_socket_perror("SSL_set_rfd");
319 return -1;
320 }
321 if (!SSL_set_wfd(sock->ssl, sock->fd[1])) {
322 ssl_socket_perror("SSL_set_wfd");
684ec6c6
RS
323 return -1;
324 }
325
698a1ec4
JH
326#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
327 /*
328 * SNI (RFC4366)
329 * OpenSSL does not document this function, but the implementation
330 * returns 1 on success, 0 on failure after calling SSLerr().
331 */
332 ret = SSL_set_tlsext_host_name(sock->ssl, server.host);
333 if (ret != 1)
334 warning("SSL_set_tlsext_host_name(%s) failed.", server.host);
335#endif
336
684ec6c6
RS
337 ret = SSL_connect(sock->ssl);
338 if (ret <= 0) {
339 socket_perror("SSL_connect", sock, ret);
340 return -1;
341 }
342
b62fb077
OB
343 if (verify) {
344 /* make sure the hostname matches that of the certificate */
345 cert = SSL_get_peer_certificate(sock->ssl);
346 if (!cert)
347 return error("unable to get peer certificate.");
348 if (verify_hostname(cert, server.host) < 0)
349 return -1;
350 }
351
684ec6c6 352 return 0;
f2561fda 353}
1e1fe529 354#endif
f2561fda 355
9f1ad541 356static int socket_read(struct imap_socket *sock, char *buf, int len)
f2561fda 357{
684ec6c6
RS
358 ssize_t n;
359#ifndef NO_OPENSSL
360 if (sock->ssl)
361 n = SSL_read(sock->ssl, buf, len);
362 else
363#endif
7a7796e9 364 n = xread(sock->fd[0], buf, len);
f2561fda 365 if (n <= 0) {
95c53908 366 socket_perror("read", sock, n);
7a7796e9
EFL
367 close(sock->fd[0]);
368 close(sock->fd[1]);
369 sock->fd[0] = sock->fd[1] = -1;
f2561fda
MM
370 }
371 return n;
372}
373
9f1ad541 374static int socket_write(struct imap_socket *sock, const char *buf, int len)
f2561fda 375{
684ec6c6
RS
376 int n;
377#ifndef NO_OPENSSL
378 if (sock->ssl)
379 n = SSL_write(sock->ssl, buf, len);
380 else
381#endif
7a7796e9 382 n = write_in_full(sock->fd[1], buf, len);
f2561fda 383 if (n != len) {
95c53908 384 socket_perror("write", sock, n);
7a7796e9
EFL
385 close(sock->fd[0]);
386 close(sock->fd[1]);
387 sock->fd[0] = sock->fd[1] = -1;
f2561fda
MM
388 }
389 return n;
390}
391
9f1ad541 392static void socket_shutdown(struct imap_socket *sock)
684ec6c6
RS
393{
394#ifndef NO_OPENSSL
395 if (sock->ssl) {
396 SSL_shutdown(sock->ssl);
397 SSL_free(sock->ssl);
398 }
399#endif
7a7796e9
EFL
400 close(sock->fd[0]);
401 close(sock->fd[1]);
684ec6c6
RS
402}
403
f2561fda 404/* simple line buffering */
9f1ad541 405static int buffer_gets(struct imap_buffer *b, char **s)
f2561fda
MM
406{
407 int n;
408 int start = b->offset;
409
410 *s = b->buf + start;
411
412 for (;;) {
413 /* make sure we have enough data to read the \r\n sequence */
414 if (b->offset + 1 >= b->bytes) {
415 if (start) {
416 /* shift down used bytes */
417 *s = b->buf;
418
95c53908 419 assert(start <= b->bytes);
f2561fda
MM
420 n = b->bytes - start;
421
422 if (n)
173a9cbe 423 memmove(b->buf, b->buf + start, n);
f2561fda
MM
424 b->offset -= start;
425 b->bytes = n;
426 start = 0;
427 }
428
95c53908
RS
429 n = socket_read(&b->sock, b->buf + b->bytes,
430 sizeof(b->buf) - b->bytes);
f2561fda
MM
431
432 if (n <= 0)
433 return -1;
434
435 b->bytes += n;
436 }
437
438 if (b->buf[b->offset] == '\r') {
95c53908 439 assert(b->offset + 1 < b->bytes);
f2561fda
MM
440 if (b->buf[b->offset + 1] == '\n') {
441 b->buf[b->offset] = 0; /* terminate the string */
442 b->offset += 2; /* next line */
f1a35295 443 if (0 < verbosity)
95c53908 444 puts(*s);
f2561fda
MM
445 return 0;
446 }
447 }
448
449 b->offset++;
450 }
451 /* not reached */
452}
453
95c53908 454static void imap_info(const char *msg, ...)
f2561fda
MM
455{
456 va_list va;
457
f1a35295 458 if (0 <= verbosity) {
95c53908
RS
459 va_start(va, msg);
460 vprintf(msg, va);
461 va_end(va);
462 fflush(stdout);
f2561fda
MM
463 }
464}
465
95c53908 466static void imap_warn(const char *msg, ...)
f2561fda
MM
467{
468 va_list va;
469
f1a35295 470 if (-2 < verbosity) {
95c53908
RS
471 va_start(va, msg);
472 vfprintf(stderr, msg, va);
473 va_end(va);
f2561fda
MM
474 }
475}
476
95c53908 477static char *next_arg(char **s)
f2561fda
MM
478{
479 char *ret;
480
481 if (!s || !*s)
5142db69 482 return NULL;
95c53908 483 while (isspace((unsigned char) **s))
f2561fda
MM
484 (*s)++;
485 if (!**s) {
5142db69
RS
486 *s = NULL;
487 return NULL;
f2561fda
MM
488 }
489 if (**s == '"') {
490 ++*s;
491 ret = *s;
95c53908 492 *s = strchr(*s, '"');
f2561fda
MM
493 } else {
494 ret = *s;
95c53908 495 while (**s && !isspace((unsigned char) **s))
f2561fda
MM
496 (*s)++;
497 }
498 if (*s) {
499 if (**s)
500 *(*s)++ = 0;
501 if (!**s)
5142db69 502 *s = NULL;
f2561fda
MM
503 }
504 return ret;
505}
506
95c53908 507static int nfsnprintf(char *buf, int blen, const char *fmt, ...)
f2561fda
MM
508{
509 int ret;
510 va_list va;
511
95c53908
RS
512 va_start(va, fmt);
513 if (blen <= 0 || (unsigned)(ret = vsnprintf(buf, blen, fmt, va)) >= (unsigned)blen)
033abf97 514 BUG("buffer too small. Please report a bug.");
95c53908 515 va_end(va);
f2561fda
MM
516 return ret;
517}
518
e0d8e308
TF
519static struct imap_cmd *issue_imap_cmd(struct imap_store *ctx,
520 struct imap_cmd_cb *cb,
521 const char *fmt, va_list ap)
f2561fda 522{
9f1ad541 523 struct imap *imap = ctx->imap;
f2561fda
MM
524 struct imap_cmd *cmd;
525 int n, bufl;
526 char buf[1024];
527
95c53908
RS
528 cmd = xmalloc(sizeof(struct imap_cmd));
529 nfvasprintf(&cmd->cmd, fmt, ap);
f2561fda
MM
530 cmd->tag = ++imap->nexttag;
531
532 if (cb)
533 cmd->cb = *cb;
534 else
95c53908 535 memset(&cmd->cb, 0, sizeof(cmd->cb));
f2561fda
MM
536
537 while (imap->literal_pending)
95c53908 538 get_cmd_result(ctx, NULL);
f2561fda 539
1702b138
ÆAB
540 if (!cmd->cb.data)
541 bufl = nfsnprintf(buf, sizeof(buf), "%d %s\r\n", cmd->tag, cmd->cmd);
542 else
543 bufl = nfsnprintf(buf, sizeof(buf), "%d %s{%d%s}\r\n",
544 cmd->tag, cmd->cmd, cmd->cb.dlen,
545 CAP(LITERALPLUS) ? "+" : "");
f2561fda 546
f1a35295 547 if (0 < verbosity) {
f2561fda 548 if (imap->num_in_progress)
95c53908 549 printf("(%d in progress) ", imap->num_in_progress);
ba9b9e12 550 if (!starts_with(cmd->cmd, "LOGIN"))
95c53908 551 printf(">>> %s", buf);
f2561fda 552 else
95c53908 553 printf(">>> %d LOGIN <user> <pass>\n", cmd->tag);
f2561fda 554 }
95c53908
RS
555 if (socket_write(&imap->buf.sock, buf, bufl) != bufl) {
556 free(cmd->cmd);
557 free(cmd);
8e0f7003 558 if (cb)
95c53908 559 free(cb->data);
f2561fda
MM
560 return NULL;
561 }
562 if (cmd->cb.data) {
563 if (CAP(LITERALPLUS)) {
95c53908
RS
564 n = socket_write(&imap->buf.sock, cmd->cb.data, cmd->cb.dlen);
565 free(cmd->cb.data);
f2561fda 566 if (n != cmd->cb.dlen ||
8e76bf3f 567 socket_write(&imap->buf.sock, "\r\n", 2) != 2) {
95c53908
RS
568 free(cmd->cmd);
569 free(cmd);
f2561fda
MM
570 return NULL;
571 }
5142db69 572 cmd->cb.data = NULL;
f2561fda
MM
573 } else
574 imap->literal_pending = 1;
575 } else if (cmd->cb.cont)
576 imap->literal_pending = 1;
5142db69 577 cmd->next = NULL;
f2561fda
MM
578 *imap->in_progress_append = cmd;
579 imap->in_progress_append = &cmd->next;
580 imap->num_in_progress++;
581 return cmd;
582}
583
28bea9e5 584__attribute__((format (printf, 3, 4)))
9f1ad541 585static int imap_exec(struct imap_store *ctx, struct imap_cmd_cb *cb,
95c53908 586 const char *fmt, ...)
f2561fda
MM
587{
588 va_list ap;
589 struct imap_cmd *cmdp;
590
95c53908 591 va_start(ap, fmt);
e0d8e308 592 cmdp = issue_imap_cmd(ctx, cb, fmt, ap);
95c53908 593 va_end(ap);
f2561fda
MM
594 if (!cmdp)
595 return RESP_BAD;
596
95c53908 597 return get_cmd_result(ctx, cmdp);
f2561fda
MM
598}
599
28bea9e5 600__attribute__((format (printf, 3, 4)))
9f1ad541 601static int imap_exec_m(struct imap_store *ctx, struct imap_cmd_cb *cb,
95c53908 602 const char *fmt, ...)
f2561fda
MM
603{
604 va_list ap;
605 struct imap_cmd *cmdp;
606
95c53908 607 va_start(ap, fmt);
e0d8e308 608 cmdp = issue_imap_cmd(ctx, cb, fmt, ap);
95c53908 609 va_end(ap);
f2561fda
MM
610 if (!cmdp)
611 return DRV_STORE_BAD;
612
95c53908 613 switch (get_cmd_result(ctx, cmdp)) {
f2561fda
MM
614 case RESP_BAD: return DRV_STORE_BAD;
615 case RESP_NO: return DRV_MSG_BAD;
616 default: return DRV_OK;
617 }
618}
619
3648b4d9 620static int skip_imap_list_l(char **sp, int level)
f2561fda 621{
3648b4d9 622 char *s = *sp;
f2561fda
MM
623
624 for (;;) {
95c53908 625 while (isspace((unsigned char)*s))
f2561fda
MM
626 s++;
627 if (level && *s == ')') {
628 s++;
629 break;
630 }
f2561fda
MM
631 if (*s == '(') {
632 /* sublist */
633 s++;
3648b4d9 634 if (skip_imap_list_l(&s, level + 1))
f2561fda
MM
635 goto bail;
636 } else if (*s == '"') {
637 /* quoted string */
638 s++;
f2561fda
MM
639 for (; *s != '"'; s++)
640 if (!*s)
641 goto bail;
f2561fda 642 s++;
f2561fda
MM
643 } else {
644 /* atom */
95c53908 645 for (; *s && !isspace((unsigned char)*s); s++)
f2561fda
MM
646 if (level && *s == ')')
647 break;
f2561fda
MM
648 }
649
650 if (!level)
651 break;
652 if (!*s)
653 goto bail;
654 }
655 *sp = s;
f2561fda
MM
656 return 0;
657
9f1ad541 658bail:
f2561fda
MM
659 return -1;
660}
661
3648b4d9 662static void skip_list(char **sp)
f2561fda 663{
3648b4d9 664 skip_imap_list_l(sp, 0);
f2561fda
MM
665}
666
9f1ad541 667static void parse_capability(struct imap *imap, char *cmd)
f2561fda
MM
668{
669 char *arg;
670 unsigned i;
671
672 imap->caps = 0x80000000;
95c53908 673 while ((arg = next_arg(&cmd)))
f2561fda 674 for (i = 0; i < ARRAY_SIZE(cap_list); i++)
95c53908 675 if (!strcmp(cap_list[i], arg))
f2561fda
MM
676 imap->caps |= 1 << i;
677 imap->rcaps = imap->caps;
678}
679
9f1ad541 680static int parse_response_code(struct imap_store *ctx, struct imap_cmd_cb *cb,
95c53908 681 char *s)
f2561fda 682{
9f1ad541 683 struct imap *imap = ctx->imap;
f2561fda
MM
684 char *arg, *p;
685
618ec81a 686 if (!s || *s != '[')
f2561fda
MM
687 return RESP_OK; /* no response code */
688 s++;
95c53908
RS
689 if (!(p = strchr(s, ']'))) {
690 fprintf(stderr, "IMAP error: malformed response code\n");
f2561fda
MM
691 return RESP_BAD;
692 }
693 *p++ = 0;
95c53908 694 arg = next_arg(&s);
f54c5bd4
RS
695 if (!arg) {
696 fprintf(stderr, "IMAP error: empty response code\n");
697 return RESP_BAD;
698 }
95c53908 699 if (!strcmp("UIDVALIDITY", arg)) {
636fd66b 700 if (!(arg = next_arg(&s)) || !(ctx->uidvalidity = atoi(arg))) {
95c53908 701 fprintf(stderr, "IMAP error: malformed UIDVALIDITY status\n");
f2561fda
MM
702 return RESP_BAD;
703 }
95c53908
RS
704 } else if (!strcmp("UIDNEXT", arg)) {
705 if (!(arg = next_arg(&s)) || !(imap->uidnext = atoi(arg))) {
706 fprintf(stderr, "IMAP error: malformed NEXTUID status\n");
f2561fda
MM
707 return RESP_BAD;
708 }
95c53908
RS
709 } else if (!strcmp("CAPABILITY", arg)) {
710 parse_capability(imap, s);
711 } else if (!strcmp("ALERT", arg)) {
f2561fda
MM
712 /* RFC2060 says that these messages MUST be displayed
713 * to the user
714 */
95c53908
RS
715 for (; isspace((unsigned char)*p); p++);
716 fprintf(stderr, "*** IMAP ALERT *** %s\n", p);
717 } else if (cb && cb->ctx && !strcmp("APPENDUID", arg)) {
636fd66b 718 if (!(arg = next_arg(&s)) || !(ctx->uidvalidity = atoi(arg)) ||
9f1ad541 719 !(arg = next_arg(&s)) || !(*(int *)cb->ctx = atoi(arg))) {
95c53908 720 fprintf(stderr, "IMAP error: malformed APPENDUID status\n");
f2561fda
MM
721 return RESP_BAD;
722 }
723 }
724 return RESP_OK;
725}
726
9f1ad541 727static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd)
f2561fda 728{
9f1ad541 729 struct imap *imap = ctx->imap;
e0d8e308 730 struct imap_cmd *cmdp, **pcmdp;
f54c5bd4
RS
731 char *cmd;
732 const char *arg, *arg1;
f2561fda
MM
733 int n, resp, resp2, tag;
734
735 for (;;) {
95c53908 736 if (buffer_gets(&imap->buf, &cmd))
f2561fda
MM
737 return RESP_BAD;
738
95c53908 739 arg = next_arg(&cmd);
f54c5bd4
RS
740 if (!arg) {
741 fprintf(stderr, "IMAP error: empty response\n");
742 return RESP_BAD;
743 }
f2561fda 744 if (*arg == '*') {
95c53908 745 arg = next_arg(&cmd);
f2561fda 746 if (!arg) {
95c53908 747 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
f2561fda
MM
748 return RESP_BAD;
749 }
750
95c53908 751 if (!strcmp("NAMESPACE", arg)) {
3648b4d9
MH
752 /* rfc2342 NAMESPACE response. */
753 skip_list(&cmd); /* Personal mailboxes */
754 skip_list(&cmd); /* Others' mailboxes */
755 skip_list(&cmd); /* Shared mailboxes */
95c53908
RS
756 } else if (!strcmp("OK", arg) || !strcmp("BAD", arg) ||
757 !strcmp("NO", arg) || !strcmp("BYE", arg)) {
758 if ((resp = parse_response_code(ctx, NULL, cmd)) != RESP_OK)
f2561fda 759 return resp;
1efee7ff 760 } else if (!strcmp("CAPABILITY", arg)) {
95c53908 761 parse_capability(imap, cmd);
1efee7ff
MH
762 } else if ((arg1 = next_arg(&cmd))) {
763 ; /*
764 * Unhandled response-data with at least two words.
765 * Ignore it.
766 *
767 * NEEDSWORK: Previously this case handled '<num> EXISTS'
768 * and '<num> RECENT' but as a probably-unintended side
769 * effect it ignores other unrecognized two-word
770 * responses. imap-send doesn't ever try to read
771 * messages or mailboxes these days, so consider
772 * eliminating this case.
773 */
f2561fda 774 } else {
95c53908 775 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
f2561fda
MM
776 return RESP_BAD;
777 }
778 } else if (!imap->in_progress) {
95c53908 779 fprintf(stderr, "IMAP error: unexpected reply: %s %s\n", arg, cmd ? cmd : "");
f2561fda
MM
780 return RESP_BAD;
781 } else if (*arg == '+') {
782 /* This can happen only with the last command underway, as
783 it enforces a round-trip. */
784 cmdp = (struct imap_cmd *)((char *)imap->in_progress_append -
785 offsetof(struct imap_cmd, next));
786 if (cmdp->cb.data) {
95c53908 787 n = socket_write(&imap->buf.sock, cmdp->cb.data, cmdp->cb.dlen);
6a83d902 788 FREE_AND_NULL(cmdp->cb.data);
f2561fda
MM
789 if (n != (int)cmdp->cb.dlen)
790 return RESP_BAD;
791 } else if (cmdp->cb.cont) {
95c53908 792 if (cmdp->cb.cont(ctx, cmdp, cmd))
f2561fda
MM
793 return RESP_BAD;
794 } else {
95c53908 795 fprintf(stderr, "IMAP error: unexpected command continuation request\n");
f2561fda
MM
796 return RESP_BAD;
797 }
95c53908 798 if (socket_write(&imap->buf.sock, "\r\n", 2) != 2)
f2561fda
MM
799 return RESP_BAD;
800 if (!cmdp->cb.cont)
801 imap->literal_pending = 0;
802 if (!tcmd)
803 return DRV_OK;
804 } else {
95c53908 805 tag = atoi(arg);
f2561fda
MM
806 for (pcmdp = &imap->in_progress; (cmdp = *pcmdp); pcmdp = &cmdp->next)
807 if (cmdp->tag == tag)
808 goto gottag;
95c53908 809 fprintf(stderr, "IMAP error: unexpected tag %s\n", arg);
f2561fda 810 return RESP_BAD;
9f1ad541 811 gottag:
f2561fda
MM
812 if (!(*pcmdp = cmdp->next))
813 imap->in_progress_append = pcmdp;
814 imap->num_in_progress--;
815 if (cmdp->cb.cont || cmdp->cb.data)
816 imap->literal_pending = 0;
95c53908 817 arg = next_arg(&cmd);
f54c5bd4
RS
818 if (!arg)
819 arg = "";
95c53908 820 if (!strcmp("OK", arg))
f2561fda
MM
821 resp = DRV_OK;
822 else {
e0d8e308 823 if (!strcmp("NO", arg))
f2561fda 824 resp = RESP_NO;
e0d8e308 825 else /*if (!strcmp("BAD", arg))*/
f2561fda 826 resp = RESP_BAD;
95c53908 827 fprintf(stderr, "IMAP command '%s' returned response (%s) - %s\n",
ba9b9e12 828 !starts_with(cmdp->cmd, "LOGIN") ?
f2561fda
MM
829 cmdp->cmd : "LOGIN <user> <pass>",
830 arg, cmd ? cmd : "");
831 }
95c53908 832 if ((resp2 = parse_response_code(ctx, &cmdp->cb, cmd)) > resp)
f2561fda 833 resp = resp2;
f2561fda 834 if (cmdp->cb.done)
95c53908
RS
835 cmdp->cb.done(ctx, cmdp, resp);
836 free(cmdp->cb.data);
837 free(cmdp->cmd);
838 free(cmdp);
f2561fda
MM
839 if (!tcmd || tcmd == cmdp)
840 return resp;
841 }
842 }
843 /* not reached */
844}
845
9f1ad541 846static void imap_close_server(struct imap_store *ictx)
f2561fda 847{
9f1ad541 848 struct imap *imap = ictx->imap;
f2561fda 849
7a7796e9 850 if (imap->buf.sock.fd[0] != -1) {
95c53908
RS
851 imap_exec(ictx, NULL, "LOGOUT");
852 socket_shutdown(&imap->buf.sock);
f2561fda 853 }
95c53908 854 free(imap);
f2561fda
MM
855}
856
fe47e1df 857static void imap_close_store(struct imap_store *ctx)
f2561fda 858{
fe47e1df 859 imap_close_server(ctx);
95c53908 860 free(ctx);
f2561fda
MM
861}
862
ae9c606e
HM
863#ifndef NO_OPENSSL
864
865/*
866 * hexchar() and cram() functions are based on the code from the isync
867 * project (http://isync.sf.net/).
868 */
869static char hexchar(unsigned int b)
f2561fda 870{
ae9c606e 871 return b < 10 ? '0' + b : 'a' + (b - 10);
f2561fda
MM
872}
873
42c78a21 874#define ENCODED_SIZE(n) (4 * DIV_ROUND_UP((n), 3))
ae9c606e 875static char *cram(const char *challenge_64, const char *user, const char *pass)
f2561fda 876{
ae9c606e 877 int i, resp_len, encoded_len, decoded_len;
ae9c606e
HM
878 unsigned char hash[16];
879 char hex[33];
880 char *response, *response_64, *challenge;
881
882 /*
883 * length of challenge_64 (i.e. base-64 encoded string) is a good
884 * enough upper bound for challenge (decoded result).
885 */
886 encoded_len = strlen(challenge_64);
887 challenge = xmalloc(encoded_len);
888 decoded_len = EVP_DecodeBlock((unsigned char *)challenge,
889 (unsigned char *)challenge_64, encoded_len);
890 if (decoded_len < 0)
891 die("invalid challenge %s", challenge_64);
1ed2c7b1
KY
892 if (!HMAC(EVP_md5(), pass, strlen(pass), (unsigned char *)challenge, decoded_len, hash, NULL))
893 die("HMAC error");
ae9c606e
HM
894
895 hex[32] = 0;
896 for (i = 0; i < 16; i++) {
897 hex[2 * i] = hexchar((hash[i] >> 4) & 0xf);
898 hex[2 * i + 1] = hexchar(hash[i] & 0xf);
899 }
900
901 /* response: "<user> <digest in hex>" */
75faa45a 902 response = xstrfmt("%s %s", user, hex);
eb94ee7f 903 resp_len = strlen(response);
ae9c606e 904
3733e694 905 response_64 = xmallocz(ENCODED_SIZE(resp_len));
ae9c606e
HM
906 encoded_len = EVP_EncodeBlock((unsigned char *)response_64,
907 (unsigned char *)response, resp_len);
908 if (encoded_len < 0)
909 die("EVP_EncodeBlock error");
ae9c606e
HM
910 return (char *)response_64;
911}
912
913#else
914
915static char *cram(const char *challenge_64, const char *user, const char *pass)
916{
917 die("If you want to use CRAM-MD5 authenticate method, "
918 "you have to build git-imap-send with OpenSSL library.");
919}
920
921#endif
922
923static int auth_cram_md5(struct imap_store *ctx, struct imap_cmd *cmd, const char *prompt)
924{
925 int ret;
926 char *response;
927
928 response = cram(prompt, server.user, server.pass);
929
930 ret = socket_write(&ctx->imap->buf.sock, response, strlen(response));
931 if (ret != strlen(response))
82247e9b 932 return error("IMAP error: sending response failed");
ae9c606e
HM
933
934 free(response);
935
936 return 0;
937}
938
690307f3
NMC
939static void server_fill_credential(struct imap_server_conf *srvc, struct credential *cred)
940{
941 if (srvc->user && srvc->pass)
942 return;
943
944 cred->protocol = xstrdup(srvc->use_ssl ? "imaps" : "imap");
945 cred->host = xstrdup(srvc->host);
946
947 cred->username = xstrdup_or_null(srvc->user);
948 cred->password = xstrdup_or_null(srvc->pass);
949
950 credential_fill(cred);
951
952 if (!srvc->user)
953 srvc->user = xstrdup(cred->username);
954 if (!srvc->pass)
955 srvc->pass = xstrdup(cred->password);
956}
957
e0d8e308 958static struct imap_store *imap_open_store(struct imap_server_conf *srvc, char *folder)
f2561fda 959{
791643a8 960 struct credential cred = CREDENTIAL_INIT;
9f1ad541
JH
961 struct imap_store *ctx;
962 struct imap *imap;
f2561fda 963 char *arg, *rsp;
c94d2dd0 964 int s = -1, preauth;
f2561fda 965
3345c0f5 966 ctx = xcalloc(1, sizeof(*ctx));
f2561fda 967
693eb02a 968 ctx->imap = imap = xcalloc(1, sizeof(*imap));
7a7796e9 969 imap->buf.sock.fd[0] = imap->buf.sock.fd[1] = -1;
f2561fda
MM
970 imap->in_progress_append = &imap->in_progress;
971
972 /* open connection to IMAP server */
973
974 if (srvc->tunnel) {
d3180279 975 struct child_process tunnel = CHILD_PROCESS_INIT;
f2561fda 976
c94d2dd0 977 imap_info("Starting tunnel '%s'... ", srvc->tunnel);
f2561fda 978
f9dc5d65 979 argv_array_push(&tunnel.args, srvc->tunnel);
ac0ba18d 980 tunnel.use_shell = 1;
c94d2dd0
EFL
981 tunnel.in = -1;
982 tunnel.out = -1;
983 if (start_command(&tunnel))
f9dc5d65 984 die("cannot start proxy %s", srvc->tunnel);
f2561fda 985
c94d2dd0
EFL
986 imap->buf.sock.fd[0] = tunnel.out;
987 imap->buf.sock.fd[1] = tunnel.in;
f2561fda 988
95c53908 989 imap_info("ok\n");
f2561fda 990 } else {
94ad2437
BK
991#ifndef NO_IPV6
992 struct addrinfo hints, *ai0, *ai;
993 int gai;
994 char portstr[6];
995
1a168e5c 996 xsnprintf(portstr, sizeof(portstr), "%d", srvc->port);
94ad2437
BK
997
998 memset(&hints, 0, sizeof(hints));
999 hints.ai_socktype = SOCK_STREAM;
1000 hints.ai_protocol = IPPROTO_TCP;
f2561fda 1001
94ad2437
BK
1002 imap_info("Resolving %s... ", srvc->host);
1003 gai = getaddrinfo(srvc->host, portstr, &hints, &ai);
1004 if (gai) {
1005 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai));
1006 goto bail;
f2561fda 1007 }
94ad2437 1008 imap_info("ok\n");
f2561fda 1009
94ad2437
BK
1010 for (ai0 = ai; ai; ai = ai->ai_next) {
1011 char addr[NI_MAXHOST];
f2561fda 1012
94ad2437
BK
1013 s = socket(ai->ai_family, ai->ai_socktype,
1014 ai->ai_protocol);
1015 if (s < 0)
1016 continue;
f2561fda 1017
94ad2437
BK
1018 getnameinfo(ai->ai_addr, ai->ai_addrlen, addr,
1019 sizeof(addr), NULL, 0, NI_NUMERICHOST);
1020 imap_info("Connecting to [%s]:%s... ", addr, portstr);
1021
1022 if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0) {
1023 close(s);
1024 s = -1;
1025 perror("connect");
1026 continue;
1027 }
1028
1029 break;
1030 }
1031 freeaddrinfo(ai0);
1032#else /* NO_IPV6 */
1033 struct hostent *he;
1034 struct sockaddr_in addr;
1035
95c53908
RS
1036 memset(&addr, 0, sizeof(addr));
1037 addr.sin_port = htons(srvc->port);
f2561fda
MM
1038 addr.sin_family = AF_INET;
1039
95c53908
RS
1040 imap_info("Resolving %s... ", srvc->host);
1041 he = gethostbyname(srvc->host);
f2561fda 1042 if (!he) {
95c53908 1043 perror("gethostbyname");
f2561fda
MM
1044 goto bail;
1045 }
95c53908 1046 imap_info("ok\n");
f2561fda
MM
1047
1048 addr.sin_addr.s_addr = *((int *) he->h_addr_list[0]);
1049
95c53908 1050 s = socket(PF_INET, SOCK_STREAM, 0);
f2561fda 1051
95c53908
RS
1052 imap_info("Connecting to %s:%hu... ", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
1053 if (connect(s, (struct sockaddr *)&addr, sizeof(addr))) {
1054 close(s);
94ad2437 1055 s = -1;
95c53908 1056 perror("connect");
94ad2437
BK
1057 }
1058#endif
1059 if (s < 0) {
1060 fputs("Error: unable to connect to server.\n", stderr);
f2561fda
MM
1061 goto bail;
1062 }
f2561fda 1063
7a7796e9
EFL
1064 imap->buf.sock.fd[0] = s;
1065 imap->buf.sock.fd[1] = dup(s);
f2561fda 1066
684ec6c6
RS
1067 if (srvc->use_ssl &&
1068 ssl_socket_connect(&imap->buf.sock, 0, srvc->ssl_verify)) {
1069 close(s);
1070 goto bail;
1071 }
95c53908 1072 imap_info("ok\n");
f2561fda
MM
1073 }
1074
1075 /* read the greeting string */
95c53908
RS
1076 if (buffer_gets(&imap->buf, &rsp)) {
1077 fprintf(stderr, "IMAP error: no greeting response\n");
f2561fda
MM
1078 goto bail;
1079 }
95c53908
RS
1080 arg = next_arg(&rsp);
1081 if (!arg || *arg != '*' || (arg = next_arg(&rsp)) == NULL) {
1082 fprintf(stderr, "IMAP error: invalid greeting response\n");
f2561fda
MM
1083 goto bail;
1084 }
1085 preauth = 0;
95c53908 1086 if (!strcmp("PREAUTH", arg))
f2561fda 1087 preauth = 1;
95c53908
RS
1088 else if (strcmp("OK", arg) != 0) {
1089 fprintf(stderr, "IMAP error: unknown greeting response\n");
f2561fda
MM
1090 goto bail;
1091 }
95c53908
RS
1092 parse_response_code(ctx, NULL, rsp);
1093 if (!imap->caps && imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
f2561fda
MM
1094 goto bail;
1095
1096 if (!preauth) {
684ec6c6
RS
1097#ifndef NO_OPENSSL
1098 if (!srvc->use_ssl && CAP(STARTTLS)) {
d27da38a 1099 if (imap_exec(ctx, NULL, "STARTTLS") != RESP_OK)
684ec6c6
RS
1100 goto bail;
1101 if (ssl_socket_connect(&imap->buf.sock, 1,
1102 srvc->ssl_verify))
1103 goto bail;
1104 /* capabilities may have changed, so get the new capabilities */
d27da38a 1105 if (imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
684ec6c6
RS
1106 goto bail;
1107 }
1108#endif
95c53908 1109 imap_info("Logging in...\n");
690307f3 1110 server_fill_credential(srvc, &cred);
791643a8 1111
ae9c606e
HM
1112 if (srvc->auth_method) {
1113 struct imap_cmd_cb cb;
1114
1115 if (!strcmp(srvc->auth_method, "CRAM-MD5")) {
1116 if (!CAP(AUTH_CRAM_MD5)) {
6d1fbf88 1117 fprintf(stderr, "You specified "
ae9c606e
HM
1118 "CRAM-MD5 as authentication method, "
1119 "but %s doesn't support it.\n", srvc->host);
1120 goto bail;
1121 }
1122 /* CRAM-MD5 */
1123
1124 memset(&cb, 0, sizeof(cb));
1125 cb.cont = auth_cram_md5;
1126 if (imap_exec(ctx, &cb, "AUTHENTICATE CRAM-MD5") != RESP_OK) {
1127 fprintf(stderr, "IMAP error: AUTHENTICATE CRAM-MD5 failed\n");
1128 goto bail;
1129 }
1130 } else {
1131 fprintf(stderr, "Unknown authentication method:%s\n", srvc->host);
1132 goto bail;
1133 }
1134 } else {
6c50a575
KY
1135 if (CAP(NOLOGIN)) {
1136 fprintf(stderr, "Skipping account %s@%s, server forbids LOGIN\n",
1137 srvc->user, srvc->host);
1138 goto bail;
1139 }
10439d89
CW
1140 if (!imap->buf.sock.ssl)
1141 imap_warn("*** IMAP Warning *** Password is being "
1142 "sent in the clear\n");
ae9c606e
HM
1143 if (imap_exec(ctx, NULL, "LOGIN \"%s\" \"%s\"", srvc->user, srvc->pass) != RESP_OK) {
1144 fprintf(stderr, "IMAP error: LOGIN failed\n");
1145 goto bail;
1146 }
f2561fda
MM
1147 }
1148 } /* !preauth */
1149
791643a8
DA
1150 if (cred.username)
1151 credential_approve(&cred);
1152 credential_clear(&cred);
1153
e0d8e308
TF
1154 /* check the target mailbox exists */
1155 ctx->name = folder;
1156 switch (imap_exec(ctx, NULL, "EXAMINE \"%s\"", ctx->name)) {
1157 case RESP_OK:
1158 /* ok */
1159 break;
1160 case RESP_BAD:
1161 fprintf(stderr, "IMAP error: could not check mailbox\n");
1162 goto out;
1163 case RESP_NO:
1164 if (imap_exec(ctx, NULL, "CREATE \"%s\"", ctx->name) == RESP_OK) {
1165 imap_info("Created missing mailbox\n");
1166 } else {
1167 fprintf(stderr, "IMAP error: could not create missing mailbox\n");
1168 goto out;
1169 }
1170 break;
1171 }
1172
f2561fda 1173 ctx->prefix = "";
fe47e1df 1174 return ctx;
f2561fda 1175
9f1ad541 1176bail:
791643a8
DA
1177 if (cred.username)
1178 credential_reject(&cred);
1179 credential_clear(&cred);
1180
e0d8e308 1181 out:
fe47e1df 1182 imap_close_store(ctx);
5142db69 1183 return NULL;
f2561fda
MM
1184}
1185
3691031c
MH
1186/*
1187 * Insert CR characters as necessary in *msg to ensure that every LF
1188 * character in *msg is preceded by a CR.
1189 */
f035ab62 1190static void lf_to_crlf(struct strbuf *msg)
f2561fda 1191{
59256315 1192 char *new_msg;
3691031c
MH
1193 size_t i, j;
1194 char lastc;
1195
59256315 1196 /* First pass: tally, in j, the size of the new_msg string: */
3691031c
MH
1197 for (i = j = 0, lastc = '\0'; i < msg->len; i++) {
1198 if (msg->buf[i] == '\n' && lastc != '\r')
1199 j++; /* a CR will need to be added here */
1200 lastc = msg->buf[i];
1201 j++;
f2561fda 1202 }
67d17630 1203
59256315 1204 new_msg = xmallocz(j);
3691031c
MH
1205
1206 /*
59256315 1207 * Second pass: write the new_msg string. Note that this loop is
3691031c
MH
1208 * otherwise identical to the first pass.
1209 */
1210 for (i = j = 0, lastc = '\0'; i < msg->len; i++) {
1211 if (msg->buf[i] == '\n' && lastc != '\r')
59256315
BW
1212 new_msg[j++] = '\r';
1213 lastc = new_msg[j++] = msg->buf[i];
f2561fda 1214 }
59256315 1215 strbuf_attach(msg, new_msg, j, j + 1);
67d17630 1216}
f2561fda 1217
f035ab62
MH
1218/*
1219 * Store msg to IMAP. Also detach and free the data from msg->data,
1220 * leaving msg->data empty.
1221 */
fe47e1df 1222static int imap_store_msg(struct imap_store *ctx, struct strbuf *msg)
f2561fda 1223{
9f1ad541 1224 struct imap *imap = ctx->imap;
f2561fda 1225 struct imap_cmd_cb cb;
f2561fda 1226 const char *prefix, *box;
719125c5 1227 int ret;
f2561fda 1228
cbc60761 1229 lf_to_crlf(msg);
95c53908 1230 memset(&cb, 0, sizeof(cb));
f2561fda 1231
cbc60761
MH
1232 cb.dlen = msg->len;
1233 cb.data = strbuf_detach(msg, NULL);
f2561fda 1234
636fd66b 1235 box = ctx->name;
3a7cba95 1236 prefix = !strcmp(box, "INBOX") ? "" : ctx->prefix;
719125c5 1237 ret = imap_exec_m(ctx, &cb, "APPEND \"%s%s\" ", prefix, box);
f2561fda
MM
1238 imap->caps = imap->rcaps;
1239 if (ret != DRV_OK)
1240 return ret;
f2561fda
MM
1241
1242 return DRV_OK;
1243}
1244
f035ab62 1245static void wrap_in_html(struct strbuf *msg)
c64d84f1
JW
1246{
1247 struct strbuf buf = STRBUF_INIT;
c64d84f1
JW
1248 static char *content_type = "Content-Type: text/html;\n";
1249 static char *pre_open = "<pre>\n";
1250 static char *pre_close = "</pre>\n";
118a68f9
MH
1251 const char *body = strstr(msg->buf, "\n\n");
1252
1253 if (!body)
1254 return; /* Headers but no body; no wrapping needed */
1255
1256 body += 2;
1257
1258 strbuf_add(&buf, msg->buf, body - msg->buf - 1);
1259 strbuf_addstr(&buf, content_type);
1260 strbuf_addch(&buf, '\n');
1261 strbuf_addstr(&buf, pre_open);
1262 strbuf_addstr_xml_quoted(&buf, body);
c64d84f1 1263 strbuf_addstr(&buf, pre_close);
118a68f9 1264
f035ab62
MH
1265 strbuf_release(msg);
1266 *msg = buf;
c64d84f1
JW
1267}
1268
f2561fda
MM
1269#define CHUNKSIZE 0x1000
1270
3a34e626 1271static int read_message(FILE *f, struct strbuf *all_msgs)
f2561fda 1272{
635d043f 1273 do {
3a34e626 1274 if (strbuf_fread(all_msgs, CHUNKSIZE, f) <= 0)
f2561fda 1275 break;
635d043f
PH
1276 } while (!feof(f));
1277
6360bee4 1278 return ferror(f) ? -1 : 0;
f2561fda
MM
1279}
1280
3a34e626 1281static int count_messages(struct strbuf *all_msgs)
f2561fda
MM
1282{
1283 int count = 0;
3a34e626 1284 char *p = all_msgs->buf;
f2561fda
MM
1285
1286 while (1) {
59556548 1287 if (starts_with(p, "From ")) {
4916c8f9
RR
1288 p = strstr(p+5, "\nFrom: ");
1289 if (!p) break;
1290 p = strstr(p+7, "\nDate: ");
1291 if (!p) break;
1292 p = strstr(p+7, "\nSubject: ");
1293 if (!p) break;
1294 p += 10;
f2561fda 1295 count++;
f2561fda 1296 }
95c53908 1297 p = strstr(p+5, "\nFrom ");
f2561fda
MM
1298 if (!p)
1299 break;
1300 p++;
1301 }
1302 return count;
1303}
1304
f035ab62
MH
1305/*
1306 * Copy the next message from all_msgs, starting at offset *ofs, to
1307 * msg. Update *ofs to the start of the following message. Return
1308 * true iff a message was successfully copied.
1309 */
1310static int split_msg(struct strbuf *all_msgs, struct strbuf *msg, int *ofs)
f2561fda
MM
1311{
1312 char *p, *data;
f035ab62 1313 size_t len;
f2561fda 1314
f2561fda
MM
1315 if (*ofs >= all_msgs->len)
1316 return 0;
1317
3a34e626 1318 data = &all_msgs->buf[*ofs];
f035ab62 1319 len = all_msgs->len - *ofs;
f2561fda 1320
59556548 1321 if (len < 5 || !starts_with(data, "From "))
f2561fda
MM
1322 return 0;
1323
95c53908 1324 p = strchr(data, '\n');
e0b08307 1325 if (p) {
f035ab62
MH
1326 p++;
1327 len -= p - data;
1328 *ofs += p - data;
e0b08307
MA
1329 data = p;
1330 }
1331
95c53908 1332 p = strstr(data, "\nFrom ");
f2561fda 1333 if (p)
f035ab62 1334 len = &p[1] - data;
f2561fda 1335
f035ab62
MH
1336 strbuf_add(msg, data, len);
1337 *ofs += len;
a6080a0a 1338 return 1;
f2561fda
MM
1339}
1340
ef7e1d0c 1341static void git_imap_config(void)
f2561fda 1342{
ef7e1d0c
TA
1343 const char *val = NULL;
1344
1345 git_config_get_bool("imap.sslverify", &server.ssl_verify);
1346 git_config_get_bool("imap.preformattedhtml", &server.use_html);
5dcdc780 1347 git_config_get_string("imap.folder", &server.folder);
3c17c34a 1348
ef7e1d0c
TA
1349 if (!git_config_get_value("imap.host", &val)) {
1350 if (!val) {
1351 git_die_config("imap.host", "Missing value for 'imap.host'");
1352 } else {
1353 if (starts_with(val, "imap:"))
1354 val += 5;
1355 else if (starts_with(val, "imaps:")) {
1356 val += 6;
1357 server.use_ssl = 1;
1358 }
1359 if (starts_with(val, "//"))
1360 val += 2;
1361 server.host = xstrdup(val);
f2561fda 1362 }
ef7e1d0c 1363 }
ae9c606e 1364
ef7e1d0c
TA
1365 git_config_get_string("imap.user", &server.user);
1366 git_config_get_string("imap.pass", &server.pass);
1367 git_config_get_int("imap.port", &server.port);
1368 git_config_get_string("imap.tunnel", &server.tunnel);
1369 git_config_get_string("imap.authmethod", &server.auth_method);
f2561fda
MM
1370}
1371
1e16b255
BR
1372static int append_msgs_to_imap(struct imap_server_conf *server,
1373 struct strbuf* all_msgs, int total)
f2561fda 1374{
cbc60761 1375 struct strbuf msg = STRBUF_INIT;
fe47e1df 1376 struct imap_store *ctx = NULL;
f2561fda
MM
1377 int ofs = 0;
1378 int r;
1e16b255
BR
1379 int n = 0;
1380
1381 ctx = imap_open_store(server, server->folder);
1382 if (!ctx) {
1383 fprintf(stderr, "failed to open store\n");
1384 return 1;
1385 }
1386 ctx->name = server->folder;
1387
1388 fprintf(stderr, "sending %d message%s\n", total, (total != 1) ? "s" : "");
1389 while (1) {
1390 unsigned percent = n * 100 / total;
1391
1392 fprintf(stderr, "%4u%% (%d/%d) done\r", percent, n, total);
1393
1394 if (!split_msg(all_msgs, &msg, &ofs))
1395 break;
1396 if (server->use_html)
1397 wrap_in_html(&msg);
1398 r = imap_store_msg(ctx, &msg);
1399 if (r != DRV_OK)
1400 break;
1401 n++;
1402 }
1403 fprintf(stderr, "\n");
1404
1405 imap_close_store(ctx);
1406
1407 return 0;
1408}
1409
1410#ifdef USE_CURL_FOR_IMAP_SEND
19079b3e 1411static CURL *setup_curl(struct imap_server_conf *srvc, struct credential *cred)
1e16b255
BR
1412{
1413 CURL *curl;
1414 struct strbuf path = STRBUF_INIT;
77eac3f8 1415 char *uri_encoded_folder;
1e16b255
BR
1416
1417 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
1418 die("curl_global_init failed");
1419
1420 curl = curl_easy_init();
1421
1422 if (!curl)
1423 die("curl_easy_init failed");
1424
19079b3e 1425 server_fill_credential(&server, cred);
1e16b255
BR
1426 curl_easy_setopt(curl, CURLOPT_USERNAME, server.user);
1427 curl_easy_setopt(curl, CURLOPT_PASSWORD, server.pass);
1428
d2d07ab8 1429 strbuf_addstr(&path, server.use_ssl ? "imaps://" : "imap://");
1e16b255
BR
1430 strbuf_addstr(&path, server.host);
1431 if (!path.len || path.buf[path.len - 1] != '/')
1432 strbuf_addch(&path, '/');
77eac3f8
NMC
1433
1434 uri_encoded_folder = curl_easy_escape(curl, server.folder, 0);
1435 if (!uri_encoded_folder)
1436 die("failed to encode server folder");
1437 strbuf_addstr(&path, uri_encoded_folder);
1438 curl_free(uri_encoded_folder);
1e16b255
BR
1439
1440 curl_easy_setopt(curl, CURLOPT_URL, path.buf);
1441 strbuf_release(&path);
1442 curl_easy_setopt(curl, CURLOPT_PORT, server.port);
1443
1444 if (server.auth_method) {
71d92575
JS
1445#if LIBCURL_VERSION_NUM < 0x072200
1446 warning("No LOGIN_OPTIONS support in this cURL version");
1447#else
1e16b255
BR
1448 struct strbuf auth = STRBUF_INIT;
1449 strbuf_addstr(&auth, "AUTH=");
1450 strbuf_addstr(&auth, server.auth_method);
1451 curl_easy_setopt(curl, CURLOPT_LOGIN_OPTIONS, auth.buf);
1452 strbuf_release(&auth);
71d92575 1453#endif
1e16b255
BR
1454 }
1455
230c09c0
KM
1456 if (!server.use_ssl)
1457 curl_easy_setopt(curl, CURLOPT_USE_SSL, (long)CURLUSESSL_TRY);
1e16b255
BR
1458
1459 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, server.ssl_verify);
1460 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, server.ssl_verify);
1461
1462 curl_easy_setopt(curl, CURLOPT_READFUNCTION, fread_buffer);
1463
1464 curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
1465
d47e55da 1466 if (0 < verbosity || getenv("GIT_CURL_VERBOSE"))
1e16b255 1467 curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
73e57aaf 1468 setup_curl_trace(curl);
1e16b255
BR
1469
1470 return curl;
1471}
1472
1473static int curl_append_msgs_to_imap(struct imap_server_conf *server,
3b335762
NTND
1474 struct strbuf* all_msgs, int total)
1475{
1e16b255
BR
1476 int ofs = 0;
1477 int n = 0;
1478 struct buffer msgbuf = { STRBUF_INIT, 0 };
1479 CURL *curl;
1480 CURLcode res = CURLE_OK;
19079b3e 1481 struct credential cred = CREDENTIAL_INIT;
1e16b255 1482
19079b3e 1483 curl = setup_curl(server, &cred);
1e16b255
BR
1484 curl_easy_setopt(curl, CURLOPT_READDATA, &msgbuf);
1485
1486 fprintf(stderr, "sending %d message%s\n", total, (total != 1) ? "s" : "");
1487 while (1) {
1488 unsigned percent = n * 100 / total;
1489 int prev_len;
1490
1491 fprintf(stderr, "%4u%% (%d/%d) done\r", percent, n, total);
1492
1493 prev_len = msgbuf.buf.len;
1494 if (!split_msg(all_msgs, &msgbuf.buf, &ofs))
1495 break;
1496 if (server->use_html)
1497 wrap_in_html(&msgbuf.buf);
1498 lf_to_crlf(&msgbuf.buf);
1499
1500 curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE,
1501 (curl_off_t)(msgbuf.buf.len-prev_len));
1502
1503 res = curl_easy_perform(curl);
1504
1505 if(res != CURLE_OK) {
1506 fprintf(stderr, "curl_easy_perform() failed: %s\n",
1507 curl_easy_strerror(res));
1508 break;
1509 }
1510
1511 n++;
1512 }
1513 fprintf(stderr, "\n");
1514
1515 curl_easy_cleanup(curl);
1516 curl_global_cleanup();
1517
19079b3e
NMC
1518 if (cred.username) {
1519 if (res == CURLE_OK)
1520 credential_approve(&cred);
1521#if LIBCURL_VERSION_NUM >= 0x070d01
1522 else if (res == CURLE_LOGIN_DENIED)
1523#else
1524 else
1525#endif
1526 credential_reject(&cred);
1527 }
1528
1529 credential_clear(&cred);
1530
200bc38b 1531 return res != CURLE_OK;
1e16b255
BR
1532}
1533#endif
1534
3f2e2297 1535int cmd_main(int argc, const char **argv)
1e16b255
BR
1536{
1537 struct strbuf all_msgs = STRBUF_INIT;
1538 int total;
a0406b94 1539 int nongit_ok;
f2561fda 1540
a0406b94 1541 setup_git_directory_gently(&nongit_ok);
ef7e1d0c 1542 git_imap_config();
f2561fda 1543
f1a35295
BR
1544 argc = parse_options(argc, (const char **)argv, "", imap_send_options, imap_send_usage, 0);
1545
1546 if (argc)
1547 usage_with_options(imap_send_usage, imap_send_options);
1548
1e16b255
BR
1549#ifndef USE_CURL_FOR_IMAP_SEND
1550 if (use_curl) {
dcd01ea1 1551 warning("--curl not supported in this build");
1e16b255
BR
1552 use_curl = 0;
1553 }
dcd01ea1
KM
1554#elif defined(NO_OPENSSL)
1555 if (!use_curl) {
1556 warning("--no-curl not supported in this build");
1557 use_curl = 1;
1558 }
1e16b255
BR
1559#endif
1560
684ec6c6
RS
1561 if (!server.port)
1562 server.port = server.use_ssl ? 993 : 143;
f2561fda 1563
39180571 1564 if (!server.folder) {
95c53908 1565 fprintf(stderr, "no imap store specified\n");
f2561fda
MM
1566 return 1;
1567 }
5b67b8e2 1568 if (!server.host) {
34b5cd1f 1569 if (!server.tunnel) {
95c53908 1570 fprintf(stderr, "no imap host specified\n");
34b5cd1f
JK
1571 return 1;
1572 }
1573 server.host = "tunnel";
5b67b8e2 1574 }
f2561fda
MM
1575
1576 /* read the messages */
6360bee4
MH
1577 if (read_message(stdin, &all_msgs)) {
1578 fprintf(stderr, "error reading input\n");
1579 return 1;
1580 }
1581
1582 if (all_msgs.len == 0) {
9f1ad541 1583 fprintf(stderr, "nothing to send\n");
f2561fda
MM
1584 return 1;
1585 }
1586
95c53908 1587 total = count_messages(&all_msgs);
1cd88cc9 1588 if (!total) {
9f1ad541 1589 fprintf(stderr, "no messages to send\n");
f2561fda
MM
1590 return 1;
1591 }
1592
1593 /* write it to the imap server */
f035ab62 1594
1e16b255
BR
1595 if (server.tunnel)
1596 return append_msgs_to_imap(&server, &all_msgs, total);
f2561fda 1597
1e16b255
BR
1598#ifdef USE_CURL_FOR_IMAP_SEND
1599 if (use_curl)
1600 return curl_append_msgs_to_imap(&server, &all_msgs, total);
1601#endif
f2561fda 1602
1e16b255 1603 return append_msgs_to_imap(&server, &all_msgs, total);
f2561fda 1604}