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