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