imap-send: support subjectAltName as well
[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         ret = SSL_connect(sock->ssl);
374         if (ret <= 0) {
375                 socket_perror("SSL_connect", sock, ret);
376                 return -1;
377         }
378
379         if (verify) {
380                 /* make sure the hostname matches that of the certificate */
381                 cert = SSL_get_peer_certificate(sock->ssl);
382                 if (!cert)
383                         return error("unable to get peer certificate.");
384                 if (verify_hostname(cert, server.host) < 0)
385                         return -1;
386         }
387
388         return 0;
389 }
390 #endif
391
392 static int socket_read(struct imap_socket *sock, char *buf, int len)
393 {
394         ssize_t n;
395 #ifndef NO_OPENSSL
396         if (sock->ssl)
397                 n = SSL_read(sock->ssl, buf, len);
398         else
399 #endif
400                 n = xread(sock->fd[0], buf, len);
401         if (n <= 0) {
402                 socket_perror("read", sock, n);
403                 close(sock->fd[0]);
404                 close(sock->fd[1]);
405                 sock->fd[0] = sock->fd[1] = -1;
406         }
407         return n;
408 }
409
410 static int socket_write(struct imap_socket *sock, const char *buf, int len)
411 {
412         int n;
413 #ifndef NO_OPENSSL
414         if (sock->ssl)
415                 n = SSL_write(sock->ssl, buf, len);
416         else
417 #endif
418                 n = write_in_full(sock->fd[1], buf, len);
419         if (n != len) {
420                 socket_perror("write", sock, n);
421                 close(sock->fd[0]);
422                 close(sock->fd[1]);
423                 sock->fd[0] = sock->fd[1] = -1;
424         }
425         return n;
426 }
427
428 static void socket_shutdown(struct imap_socket *sock)
429 {
430 #ifndef NO_OPENSSL
431         if (sock->ssl) {
432                 SSL_shutdown(sock->ssl);
433                 SSL_free(sock->ssl);
434         }
435 #endif
436         close(sock->fd[0]);
437         close(sock->fd[1]);
438 }
439
440 /* simple line buffering */
441 static int buffer_gets(struct imap_buffer *b, char **s)
442 {
443         int n;
444         int start = b->offset;
445
446         *s = b->buf + start;
447
448         for (;;) {
449                 /* make sure we have enough data to read the \r\n sequence */
450                 if (b->offset + 1 >= b->bytes) {
451                         if (start) {
452                                 /* shift down used bytes */
453                                 *s = b->buf;
454
455                                 assert(start <= b->bytes);
456                                 n = b->bytes - start;
457
458                                 if (n)
459                                         memmove(b->buf, b->buf + start, n);
460                                 b->offset -= start;
461                                 b->bytes = n;
462                                 start = 0;
463                         }
464
465                         n = socket_read(&b->sock, b->buf + b->bytes,
466                                          sizeof(b->buf) - b->bytes);
467
468                         if (n <= 0)
469                                 return -1;
470
471                         b->bytes += n;
472                 }
473
474                 if (b->buf[b->offset] == '\r') {
475                         assert(b->offset + 1 < b->bytes);
476                         if (b->buf[b->offset + 1] == '\n') {
477                                 b->buf[b->offset] = 0;  /* terminate the string */
478                                 b->offset += 2; /* next line */
479                                 if (Verbose)
480                                         puts(*s);
481                                 return 0;
482                         }
483                 }
484
485                 b->offset++;
486         }
487         /* not reached */
488 }
489
490 static void imap_info(const char *msg, ...)
491 {
492         va_list va;
493
494         if (!Quiet) {
495                 va_start(va, msg);
496                 vprintf(msg, va);
497                 va_end(va);
498                 fflush(stdout);
499         }
500 }
501
502 static void imap_warn(const char *msg, ...)
503 {
504         va_list va;
505
506         if (Quiet < 2) {
507                 va_start(va, msg);
508                 vfprintf(stderr, msg, va);
509                 va_end(va);
510         }
511 }
512
513 static char *next_arg(char **s)
514 {
515         char *ret;
516
517         if (!s || !*s)
518                 return NULL;
519         while (isspace((unsigned char) **s))
520                 (*s)++;
521         if (!**s) {
522                 *s = NULL;
523                 return NULL;
524         }
525         if (**s == '"') {
526                 ++*s;
527                 ret = *s;
528                 *s = strchr(*s, '"');
529         } else {
530                 ret = *s;
531                 while (**s && !isspace((unsigned char) **s))
532                         (*s)++;
533         }
534         if (*s) {
535                 if (**s)
536                         *(*s)++ = 0;
537                 if (!**s)
538                         *s = NULL;
539         }
540         return ret;
541 }
542
543 static void free_generic_messages(struct message *msgs)
544 {
545         struct message *tmsg;
546
547         for (; msgs; msgs = tmsg) {
548                 tmsg = msgs->next;
549                 free(msgs);
550         }
551 }
552
553 static int nfsnprintf(char *buf, int blen, const char *fmt, ...)
554 {
555         int ret;
556         va_list va;
557
558         va_start(va, fmt);
559         if (blen <= 0 || (unsigned)(ret = vsnprintf(buf, blen, fmt, va)) >= (unsigned)blen)
560                 die("Fatal: buffer too small. Please report a bug.");
561         va_end(va);
562         return ret;
563 }
564
565 static struct imap_cmd *v_issue_imap_cmd(struct imap_store *ctx,
566                                          struct imap_cmd_cb *cb,
567                                          const char *fmt, va_list ap)
568 {
569         struct imap *imap = ctx->imap;
570         struct imap_cmd *cmd;
571         int n, bufl;
572         char buf[1024];
573
574         cmd = xmalloc(sizeof(struct imap_cmd));
575         nfvasprintf(&cmd->cmd, fmt, ap);
576         cmd->tag = ++imap->nexttag;
577
578         if (cb)
579                 cmd->cb = *cb;
580         else
581                 memset(&cmd->cb, 0, sizeof(cmd->cb));
582
583         while (imap->literal_pending)
584                 get_cmd_result(ctx, NULL);
585
586         if (!cmd->cb.data)
587                 bufl = nfsnprintf(buf, sizeof(buf), "%d %s\r\n", cmd->tag, cmd->cmd);
588         else
589                 bufl = nfsnprintf(buf, sizeof(buf), "%d %s{%d%s}\r\n",
590                                   cmd->tag, cmd->cmd, cmd->cb.dlen,
591                                   CAP(LITERALPLUS) ? "+" : "");
592
593         if (Verbose) {
594                 if (imap->num_in_progress)
595                         printf("(%d in progress) ", imap->num_in_progress);
596                 if (memcmp(cmd->cmd, "LOGIN", 5))
597                         printf(">>> %s", buf);
598                 else
599                         printf(">>> %d LOGIN <user> <pass>\n", cmd->tag);
600         }
601         if (socket_write(&imap->buf.sock, buf, bufl) != bufl) {
602                 free(cmd->cmd);
603                 free(cmd);
604                 if (cb)
605                         free(cb->data);
606                 return NULL;
607         }
608         if (cmd->cb.data) {
609                 if (CAP(LITERALPLUS)) {
610                         n = socket_write(&imap->buf.sock, cmd->cb.data, cmd->cb.dlen);
611                         free(cmd->cb.data);
612                         if (n != cmd->cb.dlen ||
613                             socket_write(&imap->buf.sock, "\r\n", 2) != 2) {
614                                 free(cmd->cmd);
615                                 free(cmd);
616                                 return NULL;
617                         }
618                         cmd->cb.data = NULL;
619                 } else
620                         imap->literal_pending = 1;
621         } else if (cmd->cb.cont)
622                 imap->literal_pending = 1;
623         cmd->next = NULL;
624         *imap->in_progress_append = cmd;
625         imap->in_progress_append = &cmd->next;
626         imap->num_in_progress++;
627         return cmd;
628 }
629
630 __attribute__((format (printf, 3, 4)))
631 static struct imap_cmd *issue_imap_cmd(struct imap_store *ctx,
632                                        struct imap_cmd_cb *cb,
633                                        const char *fmt, ...)
634 {
635         struct imap_cmd *ret;
636         va_list ap;
637
638         va_start(ap, fmt);
639         ret = v_issue_imap_cmd(ctx, cb, fmt, ap);
640         va_end(ap);
641         return ret;
642 }
643
644 __attribute__((format (printf, 3, 4)))
645 static int imap_exec(struct imap_store *ctx, struct imap_cmd_cb *cb,
646                      const char *fmt, ...)
647 {
648         va_list ap;
649         struct imap_cmd *cmdp;
650
651         va_start(ap, fmt);
652         cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
653         va_end(ap);
654         if (!cmdp)
655                 return RESP_BAD;
656
657         return get_cmd_result(ctx, cmdp);
658 }
659
660 __attribute__((format (printf, 3, 4)))
661 static int imap_exec_m(struct imap_store *ctx, struct imap_cmd_cb *cb,
662                        const char *fmt, ...)
663 {
664         va_list ap;
665         struct imap_cmd *cmdp;
666
667         va_start(ap, fmt);
668         cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
669         va_end(ap);
670         if (!cmdp)
671                 return DRV_STORE_BAD;
672
673         switch (get_cmd_result(ctx, cmdp)) {
674         case RESP_BAD: return DRV_STORE_BAD;
675         case RESP_NO: return DRV_MSG_BAD;
676         default: return DRV_OK;
677         }
678 }
679
680 static int is_atom(struct imap_list *list)
681 {
682         return list && list->val && list->val != NIL && list->val != LIST;
683 }
684
685 static int is_list(struct imap_list *list)
686 {
687         return list && list->val == LIST;
688 }
689
690 static void free_list(struct imap_list *list)
691 {
692         struct imap_list *tmp;
693
694         for (; list; list = tmp) {
695                 tmp = list->next;
696                 if (is_list(list))
697                         free_list(list->child);
698                 else if (is_atom(list))
699                         free(list->val);
700                 free(list);
701         }
702 }
703
704 static int parse_imap_list_l(struct imap *imap, char **sp, struct imap_list **curp, int level)
705 {
706         struct imap_list *cur;
707         char *s = *sp, *p;
708         int n, bytes;
709
710         for (;;) {
711                 while (isspace((unsigned char)*s))
712                         s++;
713                 if (level && *s == ')') {
714                         s++;
715                         break;
716                 }
717                 *curp = cur = xmalloc(sizeof(*cur));
718                 curp = &cur->next;
719                 cur->val = NULL; /* for clean bail */
720                 if (*s == '(') {
721                         /* sublist */
722                         s++;
723                         cur->val = LIST;
724                         if (parse_imap_list_l(imap, &s, &cur->child, level + 1))
725                                 goto bail;
726                 } else if (imap && *s == '{') {
727                         /* literal */
728                         bytes = cur->len = strtol(s + 1, &s, 10);
729                         if (*s != '}')
730                                 goto bail;
731
732                         s = cur->val = xmalloc(cur->len);
733
734                         /* dump whats left over in the input buffer */
735                         n = imap->buf.bytes - imap->buf.offset;
736
737                         if (n > bytes)
738                                 /* the entire message fit in the buffer */
739                                 n = bytes;
740
741                         memcpy(s, imap->buf.buf + imap->buf.offset, n);
742                         s += n;
743                         bytes -= n;
744
745                         /* mark that we used part of the buffer */
746                         imap->buf.offset += n;
747
748                         /* now read the rest of the message */
749                         while (bytes > 0) {
750                                 if ((n = socket_read(&imap->buf.sock, s, bytes)) <= 0)
751                                         goto bail;
752                                 s += n;
753                                 bytes -= n;
754                         }
755
756                         if (buffer_gets(&imap->buf, &s))
757                                 goto bail;
758                 } else if (*s == '"') {
759                         /* quoted string */
760                         s++;
761                         p = s;
762                         for (; *s != '"'; s++)
763                                 if (!*s)
764                                         goto bail;
765                         cur->len = s - p;
766                         s++;
767                         cur->val = xmemdupz(p, cur->len);
768                 } else {
769                         /* atom */
770                         p = s;
771                         for (; *s && !isspace((unsigned char)*s); s++)
772                                 if (level && *s == ')')
773                                         break;
774                         cur->len = s - p;
775                         if (cur->len == 3 && !memcmp("NIL", p, 3))
776                                 cur->val = NIL;
777                         else
778                                 cur->val = xmemdupz(p, cur->len);
779                 }
780
781                 if (!level)
782                         break;
783                 if (!*s)
784                         goto bail;
785         }
786         *sp = s;
787         *curp = NULL;
788         return 0;
789
790 bail:
791         *curp = NULL;
792         return -1;
793 }
794
795 static struct imap_list *parse_imap_list(struct imap *imap, char **sp)
796 {
797         struct imap_list *head;
798
799         if (!parse_imap_list_l(imap, sp, &head, 0))
800                 return head;
801         free_list(head);
802         return NULL;
803 }
804
805 static struct imap_list *parse_list(char **sp)
806 {
807         return parse_imap_list(NULL, sp);
808 }
809
810 static void parse_capability(struct imap *imap, char *cmd)
811 {
812         char *arg;
813         unsigned i;
814
815         imap->caps = 0x80000000;
816         while ((arg = next_arg(&cmd)))
817                 for (i = 0; i < ARRAY_SIZE(cap_list); i++)
818                         if (!strcmp(cap_list[i], arg))
819                                 imap->caps |= 1 << i;
820         imap->rcaps = imap->caps;
821 }
822
823 static int parse_response_code(struct imap_store *ctx, struct imap_cmd_cb *cb,
824                                char *s)
825 {
826         struct imap *imap = ctx->imap;
827         char *arg, *p;
828
829         if (*s != '[')
830                 return RESP_OK;         /* no response code */
831         s++;
832         if (!(p = strchr(s, ']'))) {
833                 fprintf(stderr, "IMAP error: malformed response code\n");
834                 return RESP_BAD;
835         }
836         *p++ = 0;
837         arg = next_arg(&s);
838         if (!strcmp("UIDVALIDITY", arg)) {
839                 if (!(arg = next_arg(&s)) || !(ctx->gen.uidvalidity = atoi(arg))) {
840                         fprintf(stderr, "IMAP error: malformed UIDVALIDITY status\n");
841                         return RESP_BAD;
842                 }
843         } else if (!strcmp("UIDNEXT", arg)) {
844                 if (!(arg = next_arg(&s)) || !(imap->uidnext = atoi(arg))) {
845                         fprintf(stderr, "IMAP error: malformed NEXTUID status\n");
846                         return RESP_BAD;
847                 }
848         } else if (!strcmp("CAPABILITY", arg)) {
849                 parse_capability(imap, s);
850         } else if (!strcmp("ALERT", arg)) {
851                 /* RFC2060 says that these messages MUST be displayed
852                  * to the user
853                  */
854                 for (; isspace((unsigned char)*p); p++);
855                 fprintf(stderr, "*** IMAP ALERT *** %s\n", p);
856         } else if (cb && cb->ctx && !strcmp("APPENDUID", arg)) {
857                 if (!(arg = next_arg(&s)) || !(ctx->gen.uidvalidity = atoi(arg)) ||
858                     !(arg = next_arg(&s)) || !(*(int *)cb->ctx = atoi(arg))) {
859                         fprintf(stderr, "IMAP error: malformed APPENDUID status\n");
860                         return RESP_BAD;
861                 }
862         }
863         return RESP_OK;
864 }
865
866 static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd)
867 {
868         struct imap *imap = ctx->imap;
869         struct imap_cmd *cmdp, **pcmdp, *ncmdp;
870         char *cmd, *arg, *arg1, *p;
871         int n, resp, resp2, tag;
872
873         for (;;) {
874                 if (buffer_gets(&imap->buf, &cmd))
875                         return RESP_BAD;
876
877                 arg = next_arg(&cmd);
878                 if (*arg == '*') {
879                         arg = next_arg(&cmd);
880                         if (!arg) {
881                                 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
882                                 return RESP_BAD;
883                         }
884
885                         if (!strcmp("NAMESPACE", arg)) {
886                                 imap->ns_personal = parse_list(&cmd);
887                                 imap->ns_other = parse_list(&cmd);
888                                 imap->ns_shared = parse_list(&cmd);
889                         } else if (!strcmp("OK", arg) || !strcmp("BAD", arg) ||
890                                    !strcmp("NO", arg) || !strcmp("BYE", arg)) {
891                                 if ((resp = parse_response_code(ctx, NULL, cmd)) != RESP_OK)
892                                         return resp;
893                         } else if (!strcmp("CAPABILITY", arg))
894                                 parse_capability(imap, cmd);
895                         else if ((arg1 = next_arg(&cmd))) {
896                                 if (!strcmp("EXISTS", arg1))
897                                         ctx->gen.count = atoi(arg);
898                                 else if (!strcmp("RECENT", arg1))
899                                         ctx->gen.recent = atoi(arg);
900                         } else {
901                                 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
902                                 return RESP_BAD;
903                         }
904                 } else if (!imap->in_progress) {
905                         fprintf(stderr, "IMAP error: unexpected reply: %s %s\n", arg, cmd ? cmd : "");
906                         return RESP_BAD;
907                 } else if (*arg == '+') {
908                         /* This can happen only with the last command underway, as
909                            it enforces a round-trip. */
910                         cmdp = (struct imap_cmd *)((char *)imap->in_progress_append -
911                                offsetof(struct imap_cmd, next));
912                         if (cmdp->cb.data) {
913                                 n = socket_write(&imap->buf.sock, cmdp->cb.data, cmdp->cb.dlen);
914                                 free(cmdp->cb.data);
915                                 cmdp->cb.data = NULL;
916                                 if (n != (int)cmdp->cb.dlen)
917                                         return RESP_BAD;
918                         } else if (cmdp->cb.cont) {
919                                 if (cmdp->cb.cont(ctx, cmdp, cmd))
920                                         return RESP_BAD;
921                         } else {
922                                 fprintf(stderr, "IMAP error: unexpected command continuation request\n");
923                                 return RESP_BAD;
924                         }
925                         if (socket_write(&imap->buf.sock, "\r\n", 2) != 2)
926                                 return RESP_BAD;
927                         if (!cmdp->cb.cont)
928                                 imap->literal_pending = 0;
929                         if (!tcmd)
930                                 return DRV_OK;
931                 } else {
932                         tag = atoi(arg);
933                         for (pcmdp = &imap->in_progress; (cmdp = *pcmdp); pcmdp = &cmdp->next)
934                                 if (cmdp->tag == tag)
935                                         goto gottag;
936                         fprintf(stderr, "IMAP error: unexpected tag %s\n", arg);
937                         return RESP_BAD;
938                 gottag:
939                         if (!(*pcmdp = cmdp->next))
940                                 imap->in_progress_append = pcmdp;
941                         imap->num_in_progress--;
942                         if (cmdp->cb.cont || cmdp->cb.data)
943                                 imap->literal_pending = 0;
944                         arg = next_arg(&cmd);
945                         if (!strcmp("OK", arg))
946                                 resp = DRV_OK;
947                         else {
948                                 if (!strcmp("NO", arg)) {
949                                         if (cmdp->cb.create && cmd && (cmdp->cb.trycreate || !memcmp(cmd, "[TRYCREATE]", 11))) { /* SELECT, APPEND or UID COPY */
950                                                 p = strchr(cmdp->cmd, '"');
951                                                 if (!issue_imap_cmd(ctx, NULL, "CREATE \"%.*s\"", (int)(strchr(p + 1, '"') - p + 1), p)) {
952                                                         resp = RESP_BAD;
953                                                         goto normal;
954                                                 }
955                                                 /* not waiting here violates the spec, but a server that does not
956                                                    grok this nonetheless violates it too. */
957                                                 cmdp->cb.create = 0;
958                                                 if (!(ncmdp = issue_imap_cmd(ctx, &cmdp->cb, "%s", cmdp->cmd))) {
959                                                         resp = RESP_BAD;
960                                                         goto normal;
961                                                 }
962                                                 free(cmdp->cmd);
963                                                 free(cmdp);
964                                                 if (!tcmd)
965                                                         return 0;       /* ignored */
966                                                 if (cmdp == tcmd)
967                                                         tcmd = ncmdp;
968                                                 continue;
969                                         }
970                                         resp = RESP_NO;
971                                 } else /*if (!strcmp("BAD", arg))*/
972                                         resp = RESP_BAD;
973                                 fprintf(stderr, "IMAP command '%s' returned response (%s) - %s\n",
974                                          memcmp(cmdp->cmd, "LOGIN", 5) ?
975                                                         cmdp->cmd : "LOGIN <user> <pass>",
976                                                         arg, cmd ? cmd : "");
977                         }
978                         if ((resp2 = parse_response_code(ctx, &cmdp->cb, cmd)) > resp)
979                                 resp = resp2;
980                 normal:
981                         if (cmdp->cb.done)
982                                 cmdp->cb.done(ctx, cmdp, resp);
983                         free(cmdp->cb.data);
984                         free(cmdp->cmd);
985                         free(cmdp);
986                         if (!tcmd || tcmd == cmdp)
987                                 return resp;
988                 }
989         }
990         /* not reached */
991 }
992
993 static void imap_close_server(struct imap_store *ictx)
994 {
995         struct imap *imap = ictx->imap;
996
997         if (imap->buf.sock.fd[0] != -1) {
998                 imap_exec(ictx, NULL, "LOGOUT");
999                 socket_shutdown(&imap->buf.sock);
1000         }
1001         free_list(imap->ns_personal);
1002         free_list(imap->ns_other);
1003         free_list(imap->ns_shared);
1004         free(imap);
1005 }
1006
1007 static void imap_close_store(struct store *ctx)
1008 {
1009         imap_close_server((struct imap_store *)ctx);
1010         free_generic_messages(ctx->msgs);
1011         free(ctx);
1012 }
1013
1014 #ifndef NO_OPENSSL
1015
1016 /*
1017  * hexchar() and cram() functions are based on the code from the isync
1018  * project (http://isync.sf.net/).
1019  */
1020 static char hexchar(unsigned int b)
1021 {
1022         return b < 10 ? '0' + b : 'a' + (b - 10);
1023 }
1024
1025 #define ENCODED_SIZE(n) (4*((n+2)/3))
1026 static char *cram(const char *challenge_64, const char *user, const char *pass)
1027 {
1028         int i, resp_len, encoded_len, decoded_len;
1029         HMAC_CTX hmac;
1030         unsigned char hash[16];
1031         char hex[33];
1032         char *response, *response_64, *challenge;
1033
1034         /*
1035          * length of challenge_64 (i.e. base-64 encoded string) is a good
1036          * enough upper bound for challenge (decoded result).
1037          */
1038         encoded_len = strlen(challenge_64);
1039         challenge = xmalloc(encoded_len);
1040         decoded_len = EVP_DecodeBlock((unsigned char *)challenge,
1041                                       (unsigned char *)challenge_64, encoded_len);
1042         if (decoded_len < 0)
1043                 die("invalid challenge %s", challenge_64);
1044         HMAC_Init(&hmac, (unsigned char *)pass, strlen(pass), EVP_md5());
1045         HMAC_Update(&hmac, (unsigned char *)challenge, decoded_len);
1046         HMAC_Final(&hmac, hash, NULL);
1047         HMAC_CTX_cleanup(&hmac);
1048
1049         hex[32] = 0;
1050         for (i = 0; i < 16; i++) {
1051                 hex[2 * i] = hexchar((hash[i] >> 4) & 0xf);
1052                 hex[2 * i + 1] = hexchar(hash[i] & 0xf);
1053         }
1054
1055         /* response: "<user> <digest in hex>" */
1056         resp_len = strlen(user) + 1 + strlen(hex) + 1;
1057         response = xmalloc(resp_len);
1058         sprintf(response, "%s %s", user, hex);
1059
1060         response_64 = xmalloc(ENCODED_SIZE(resp_len) + 1);
1061         encoded_len = EVP_EncodeBlock((unsigned char *)response_64,
1062                                       (unsigned char *)response, resp_len);
1063         if (encoded_len < 0)
1064                 die("EVP_EncodeBlock error");
1065         response_64[encoded_len] = '\0';
1066         return (char *)response_64;
1067 }
1068
1069 #else
1070
1071 static char *cram(const char *challenge_64, const char *user, const char *pass)
1072 {
1073         die("If you want to use CRAM-MD5 authenticate method, "
1074             "you have to build git-imap-send with OpenSSL library.");
1075 }
1076
1077 #endif
1078
1079 static int auth_cram_md5(struct imap_store *ctx, struct imap_cmd *cmd, const char *prompt)
1080 {
1081         int ret;
1082         char *response;
1083
1084         response = cram(prompt, server.user, server.pass);
1085
1086         ret = socket_write(&ctx->imap->buf.sock, response, strlen(response));
1087         if (ret != strlen(response))
1088                 return error("IMAP error: sending response failed\n");
1089
1090         free(response);
1091
1092         return 0;
1093 }
1094
1095 static struct store *imap_open_store(struct imap_server_conf *srvc)
1096 {
1097         struct imap_store *ctx;
1098         struct imap *imap;
1099         char *arg, *rsp;
1100         int s = -1, preauth;
1101
1102         ctx = xcalloc(sizeof(*ctx), 1);
1103
1104         ctx->imap = imap = xcalloc(sizeof(*imap), 1);
1105         imap->buf.sock.fd[0] = imap->buf.sock.fd[1] = -1;
1106         imap->in_progress_append = &imap->in_progress;
1107
1108         /* open connection to IMAP server */
1109
1110         if (srvc->tunnel) {
1111                 const char *argv[] = { srvc->tunnel, NULL };
1112                 struct child_process tunnel = {NULL};
1113
1114                 imap_info("Starting tunnel '%s'... ", srvc->tunnel);
1115
1116                 tunnel.argv = argv;
1117                 tunnel.use_shell = 1;
1118                 tunnel.in = -1;
1119                 tunnel.out = -1;
1120                 if (start_command(&tunnel))
1121                         die("cannot start proxy %s", argv[0]);
1122
1123                 imap->buf.sock.fd[0] = tunnel.out;
1124                 imap->buf.sock.fd[1] = tunnel.in;
1125
1126                 imap_info("ok\n");
1127         } else {
1128 #ifndef NO_IPV6
1129                 struct addrinfo hints, *ai0, *ai;
1130                 int gai;
1131                 char portstr[6];
1132
1133                 snprintf(portstr, sizeof(portstr), "%d", srvc->port);
1134
1135                 memset(&hints, 0, sizeof(hints));
1136                 hints.ai_socktype = SOCK_STREAM;
1137                 hints.ai_protocol = IPPROTO_TCP;
1138
1139                 imap_info("Resolving %s... ", srvc->host);
1140                 gai = getaddrinfo(srvc->host, portstr, &hints, &ai);
1141                 if (gai) {
1142                         fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai));
1143                         goto bail;
1144                 }
1145                 imap_info("ok\n");
1146
1147                 for (ai0 = ai; ai; ai = ai->ai_next) {
1148                         char addr[NI_MAXHOST];
1149
1150                         s = socket(ai->ai_family, ai->ai_socktype,
1151                                    ai->ai_protocol);
1152                         if (s < 0)
1153                                 continue;
1154
1155                         getnameinfo(ai->ai_addr, ai->ai_addrlen, addr,
1156                                     sizeof(addr), NULL, 0, NI_NUMERICHOST);
1157                         imap_info("Connecting to [%s]:%s... ", addr, portstr);
1158
1159                         if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0) {
1160                                 close(s);
1161                                 s = -1;
1162                                 perror("connect");
1163                                 continue;
1164                         }
1165
1166                         break;
1167                 }
1168                 freeaddrinfo(ai0);
1169 #else /* NO_IPV6 */
1170                 struct hostent *he;
1171                 struct sockaddr_in addr;
1172
1173                 memset(&addr, 0, sizeof(addr));
1174                 addr.sin_port = htons(srvc->port);
1175                 addr.sin_family = AF_INET;
1176
1177                 imap_info("Resolving %s... ", srvc->host);
1178                 he = gethostbyname(srvc->host);
1179                 if (!he) {
1180                         perror("gethostbyname");
1181                         goto bail;
1182                 }
1183                 imap_info("ok\n");
1184
1185                 addr.sin_addr.s_addr = *((int *) he->h_addr_list[0]);
1186
1187                 s = socket(PF_INET, SOCK_STREAM, 0);
1188
1189                 imap_info("Connecting to %s:%hu... ", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
1190                 if (connect(s, (struct sockaddr *)&addr, sizeof(addr))) {
1191                         close(s);
1192                         s = -1;
1193                         perror("connect");
1194                 }
1195 #endif
1196                 if (s < 0) {
1197                         fputs("Error: unable to connect to server.\n", stderr);
1198                         goto bail;
1199                 }
1200
1201                 imap->buf.sock.fd[0] = s;
1202                 imap->buf.sock.fd[1] = dup(s);
1203
1204                 if (srvc->use_ssl &&
1205                     ssl_socket_connect(&imap->buf.sock, 0, srvc->ssl_verify)) {
1206                         close(s);
1207                         goto bail;
1208                 }
1209                 imap_info("ok\n");
1210         }
1211
1212         /* read the greeting string */
1213         if (buffer_gets(&imap->buf, &rsp)) {
1214                 fprintf(stderr, "IMAP error: no greeting response\n");
1215                 goto bail;
1216         }
1217         arg = next_arg(&rsp);
1218         if (!arg || *arg != '*' || (arg = next_arg(&rsp)) == NULL) {
1219                 fprintf(stderr, "IMAP error: invalid greeting response\n");
1220                 goto bail;
1221         }
1222         preauth = 0;
1223         if (!strcmp("PREAUTH", arg))
1224                 preauth = 1;
1225         else if (strcmp("OK", arg) != 0) {
1226                 fprintf(stderr, "IMAP error: unknown greeting response\n");
1227                 goto bail;
1228         }
1229         parse_response_code(ctx, NULL, rsp);
1230         if (!imap->caps && imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1231                 goto bail;
1232
1233         if (!preauth) {
1234 #ifndef NO_OPENSSL
1235                 if (!srvc->use_ssl && CAP(STARTTLS)) {
1236                         if (imap_exec(ctx, NULL, "STARTTLS") != RESP_OK)
1237                                 goto bail;
1238                         if (ssl_socket_connect(&imap->buf.sock, 1,
1239                                                srvc->ssl_verify))
1240                                 goto bail;
1241                         /* capabilities may have changed, so get the new capabilities */
1242                         if (imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1243                                 goto bail;
1244                 }
1245 #endif
1246                 imap_info("Logging in...\n");
1247                 if (!srvc->user) {
1248                         fprintf(stderr, "Skipping server %s, no user\n", srvc->host);
1249                         goto bail;
1250                 }
1251                 if (!srvc->pass) {
1252                         char prompt[80];
1253                         sprintf(prompt, "Password (%s@%s): ", srvc->user, srvc->host);
1254                         arg = git_getpass(prompt);
1255                         if (!arg) {
1256                                 perror("getpass");
1257                                 exit(1);
1258                         }
1259                         if (!*arg) {
1260                                 fprintf(stderr, "Skipping account %s@%s, no password\n", srvc->user, srvc->host);
1261                                 goto bail;
1262                         }
1263                         /*
1264                          * getpass() returns a pointer to a static buffer.  make a copy
1265                          * for long term storage.
1266                          */
1267                         srvc->pass = xstrdup(arg);
1268                 }
1269                 if (CAP(NOLOGIN)) {
1270                         fprintf(stderr, "Skipping account %s@%s, server forbids LOGIN\n", srvc->user, srvc->host);
1271                         goto bail;
1272                 }
1273
1274                 if (srvc->auth_method) {
1275                         struct imap_cmd_cb cb;
1276
1277                         if (!strcmp(srvc->auth_method, "CRAM-MD5")) {
1278                                 if (!CAP(AUTH_CRAM_MD5)) {
1279                                         fprintf(stderr, "You specified"
1280                                                 "CRAM-MD5 as authentication method, "
1281                                                 "but %s doesn't support it.\n", srvc->host);
1282                                         goto bail;
1283                                 }
1284                                 /* CRAM-MD5 */
1285
1286                                 memset(&cb, 0, sizeof(cb));
1287                                 cb.cont = auth_cram_md5;
1288                                 if (imap_exec(ctx, &cb, "AUTHENTICATE CRAM-MD5") != RESP_OK) {
1289                                         fprintf(stderr, "IMAP error: AUTHENTICATE CRAM-MD5 failed\n");
1290                                         goto bail;
1291                                 }
1292                         } else {
1293                                 fprintf(stderr, "Unknown authentication method:%s\n", srvc->host);
1294                                 goto bail;
1295                         }
1296                 } else {
1297                         if (!imap->buf.sock.ssl)
1298                                 imap_warn("*** IMAP Warning *** Password is being "
1299                                           "sent in the clear\n");
1300                         if (imap_exec(ctx, NULL, "LOGIN \"%s\" \"%s\"", srvc->user, srvc->pass) != RESP_OK) {
1301                                 fprintf(stderr, "IMAP error: LOGIN failed\n");
1302                                 goto bail;
1303                         }
1304                 }
1305         } /* !preauth */
1306
1307         ctx->prefix = "";
1308         ctx->trashnc = 1;
1309         return (struct store *)ctx;
1310
1311 bail:
1312         imap_close_store(&ctx->gen);
1313         return NULL;
1314 }
1315
1316 static int imap_make_flags(int flags, char *buf)
1317 {
1318         const char *s;
1319         unsigned i, d;
1320
1321         for (i = d = 0; i < ARRAY_SIZE(Flags); i++)
1322                 if (flags & (1 << i)) {
1323                         buf[d++] = ' ';
1324                         buf[d++] = '\\';
1325                         for (s = Flags[i]; *s; s++)
1326                                 buf[d++] = *s;
1327                 }
1328         buf[0] = '(';
1329         buf[d++] = ')';
1330         return d;
1331 }
1332
1333 static void lf_to_crlf(struct msg_data *msg)
1334 {
1335         char *new;
1336         int i, j, lfnum = 0;
1337
1338         if (msg->data[0] == '\n')
1339                 lfnum++;
1340         for (i = 1; i < msg->len; i++) {
1341                 if (msg->data[i - 1] != '\r' && msg->data[i] == '\n')
1342                         lfnum++;
1343         }
1344
1345         new = xmalloc(msg->len + lfnum);
1346         if (msg->data[0] == '\n') {
1347                 new[0] = '\r';
1348                 new[1] = '\n';
1349                 i = 1;
1350                 j = 2;
1351         } else {
1352                 new[0] = msg->data[0];
1353                 i = 1;
1354                 j = 1;
1355         }
1356         for ( ; i < msg->len; i++) {
1357                 if (msg->data[i] != '\n') {
1358                         new[j++] = msg->data[i];
1359                         continue;
1360                 }
1361                 if (msg->data[i - 1] != '\r')
1362                         new[j++] = '\r';
1363                 /* otherwise it already had CR before */
1364                 new[j++] = '\n';
1365         }
1366         msg->len += lfnum;
1367         free(msg->data);
1368         msg->data = new;
1369 }
1370
1371 static int imap_store_msg(struct store *gctx, struct msg_data *data)
1372 {
1373         struct imap_store *ctx = (struct imap_store *)gctx;
1374         struct imap *imap = ctx->imap;
1375         struct imap_cmd_cb cb;
1376         const char *prefix, *box;
1377         int ret, d;
1378         char flagstr[128];
1379
1380         lf_to_crlf(data);
1381         memset(&cb, 0, sizeof(cb));
1382
1383         cb.dlen = data->len;
1384         cb.data = xmalloc(cb.dlen);
1385         memcpy(cb.data, data->data, data->len);
1386
1387         d = 0;
1388         if (data->flags) {
1389                 d = imap_make_flags(data->flags, flagstr);
1390                 flagstr[d++] = ' ';
1391         }
1392         flagstr[d] = 0;
1393
1394         box = gctx->name;
1395         prefix = !strcmp(box, "INBOX") ? "" : ctx->prefix;
1396         cb.create = 0;
1397         ret = imap_exec_m(ctx, &cb, "APPEND \"%s%s\" %s", prefix, box, flagstr);
1398         imap->caps = imap->rcaps;
1399         if (ret != DRV_OK)
1400                 return ret;
1401         gctx->count++;
1402
1403         return DRV_OK;
1404 }
1405
1406 static void encode_html_chars(struct strbuf *p)
1407 {
1408         int i;
1409         for (i = 0; i < p->len; i++) {
1410                 if (p->buf[i] == '&')
1411                         strbuf_splice(p, i, 1, "&amp;", 5);
1412                 if (p->buf[i] == '<')
1413                         strbuf_splice(p, i, 1, "&lt;", 4);
1414                 if (p->buf[i] == '>')
1415                         strbuf_splice(p, i, 1, "&gt;", 4);
1416                 if (p->buf[i] == '"')
1417                         strbuf_splice(p, i, 1, "&quot;", 6);
1418         }
1419 }
1420 static void wrap_in_html(struct msg_data *msg)
1421 {
1422         struct strbuf buf = STRBUF_INIT;
1423         struct strbuf **lines;
1424         struct strbuf **p;
1425         static char *content_type = "Content-Type: text/html;\n";
1426         static char *pre_open = "<pre>\n";
1427         static char *pre_close = "</pre>\n";
1428         int added_header = 0;
1429
1430         strbuf_attach(&buf, msg->data, msg->len, msg->len);
1431         lines = strbuf_split(&buf, '\n');
1432         strbuf_release(&buf);
1433         for (p = lines; *p; p++) {
1434                 if (! added_header) {
1435                         if ((*p)->len == 1 && *((*p)->buf) == '\n') {
1436                                 strbuf_addstr(&buf, content_type);
1437                                 strbuf_addbuf(&buf, *p);
1438                                 strbuf_addstr(&buf, pre_open);
1439                                 added_header = 1;
1440                                 continue;
1441                         }
1442                 }
1443                 else
1444                         encode_html_chars(*p);
1445                 strbuf_addbuf(&buf, *p);
1446         }
1447         strbuf_addstr(&buf, pre_close);
1448         strbuf_list_free(lines);
1449         msg->len  = buf.len;
1450         msg->data = strbuf_detach(&buf, NULL);
1451 }
1452
1453 #define CHUNKSIZE 0x1000
1454
1455 static int read_message(FILE *f, struct msg_data *msg)
1456 {
1457         struct strbuf buf = STRBUF_INIT;
1458
1459         memset(msg, 0, sizeof(*msg));
1460
1461         do {
1462                 if (strbuf_fread(&buf, CHUNKSIZE, f) <= 0)
1463                         break;
1464         } while (!feof(f));
1465
1466         msg->len  = buf.len;
1467         msg->data = strbuf_detach(&buf, NULL);
1468         return msg->len;
1469 }
1470
1471 static int count_messages(struct msg_data *msg)
1472 {
1473         int count = 0;
1474         char *p = msg->data;
1475
1476         while (1) {
1477                 if (!prefixcmp(p, "From ")) {
1478                         p = strstr(p+5, "\nFrom: ");
1479                         if (!p) break;
1480                         p = strstr(p+7, "\nDate: ");
1481                         if (!p) break;
1482                         p = strstr(p+7, "\nSubject: ");
1483                         if (!p) break;
1484                         p += 10;
1485                         count++;
1486                 }
1487                 p = strstr(p+5, "\nFrom ");
1488                 if (!p)
1489                         break;
1490                 p++;
1491         }
1492         return count;
1493 }
1494
1495 static int split_msg(struct msg_data *all_msgs, struct msg_data *msg, int *ofs)
1496 {
1497         char *p, *data;
1498
1499         memset(msg, 0, sizeof *msg);
1500         if (*ofs >= all_msgs->len)
1501                 return 0;
1502
1503         data = &all_msgs->data[*ofs];
1504         msg->len = all_msgs->len - *ofs;
1505
1506         if (msg->len < 5 || prefixcmp(data, "From "))
1507                 return 0;
1508
1509         p = strchr(data, '\n');
1510         if (p) {
1511                 p = &p[1];
1512                 msg->len -= p-data;
1513                 *ofs += p-data;
1514                 data = p;
1515         }
1516
1517         p = strstr(data, "\nFrom ");
1518         if (p)
1519                 msg->len = &p[1] - data;
1520
1521         msg->data = xmemdupz(data, msg->len);
1522         *ofs += msg->len;
1523         return 1;
1524 }
1525
1526 static char *imap_folder;
1527
1528 static int git_imap_config(const char *key, const char *val, void *cb)
1529 {
1530         char imap_key[] = "imap.";
1531
1532         if (strncmp(key, imap_key, sizeof imap_key - 1))
1533                 return 0;
1534
1535         key += sizeof imap_key - 1;
1536
1537         /* check booleans first, and barf on others */
1538         if (!strcmp("sslverify", key))
1539                 server.ssl_verify = git_config_bool(key, val);
1540         else if (!strcmp("preformattedhtml", key))
1541                 server.use_html = git_config_bool(key, val);
1542         else if (!val)
1543                 return config_error_nonbool(key);
1544
1545         if (!strcmp("folder", key)) {
1546                 imap_folder = xstrdup(val);
1547         } else if (!strcmp("host", key)) {
1548                 if (!prefixcmp(val, "imap:"))
1549                         val += 5;
1550                 else if (!prefixcmp(val, "imaps:")) {
1551                         val += 6;
1552                         server.use_ssl = 1;
1553                 }
1554                 if (!prefixcmp(val, "//"))
1555                         val += 2;
1556                 server.host = xstrdup(val);
1557         } else if (!strcmp("user", key))
1558                 server.user = xstrdup(val);
1559         else if (!strcmp("pass", key))
1560                 server.pass = xstrdup(val);
1561         else if (!strcmp("port", key))
1562                 server.port = git_config_int(key, val);
1563         else if (!strcmp("tunnel", key))
1564                 server.tunnel = xstrdup(val);
1565         else if (!strcmp("authmethod", key))
1566                 server.auth_method = xstrdup(val);
1567
1568         return 0;
1569 }
1570
1571 int main(int argc, char **argv)
1572 {
1573         struct msg_data all_msgs, msg;
1574         struct store *ctx = NULL;
1575         int ofs = 0;
1576         int r;
1577         int total, n = 0;
1578         int nongit_ok;
1579
1580         git_extract_argv0_path(argv[0]);
1581
1582         if (argc != 1)
1583                 usage(imap_send_usage);
1584
1585         setup_git_directory_gently(&nongit_ok);
1586         git_config(git_imap_config, NULL);
1587
1588         if (!server.port)
1589                 server.port = server.use_ssl ? 993 : 143;
1590
1591         if (!imap_folder) {
1592                 fprintf(stderr, "no imap store specified\n");
1593                 return 1;
1594         }
1595         if (!server.host) {
1596                 if (!server.tunnel) {
1597                         fprintf(stderr, "no imap host specified\n");
1598                         return 1;
1599                 }
1600                 server.host = "tunnel";
1601         }
1602
1603         /* read the messages */
1604         if (!read_message(stdin, &all_msgs)) {
1605                 fprintf(stderr, "nothing to send\n");
1606                 return 1;
1607         }
1608
1609         total = count_messages(&all_msgs);
1610         if (!total) {
1611                 fprintf(stderr, "no messages to send\n");
1612                 return 1;
1613         }
1614
1615         /* write it to the imap server */
1616         ctx = imap_open_store(&server);
1617         if (!ctx) {
1618                 fprintf(stderr, "failed to open store\n");
1619                 return 1;
1620         }
1621
1622         fprintf(stderr, "sending %d message%s\n", total, (total != 1) ? "s" : "");
1623         ctx->name = imap_folder;
1624         while (1) {
1625                 unsigned percent = n * 100 / total;
1626                 fprintf(stderr, "%4u%% (%d/%d) done\r", percent, n, total);
1627                 if (!split_msg(&all_msgs, &msg, &ofs))
1628                         break;
1629                 if (server.use_html)
1630                         wrap_in_html(&msg);
1631                 r = imap_store_msg(ctx, &msg);
1632                 if (r != DRV_OK)
1633                         break;
1634                 n++;
1635         }
1636         fprintf(stderr, "\n");
1637
1638         imap_close_store(ctx);
1639
1640         return 0;
1641 }