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