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