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