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