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