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