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