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