imap-send: use run-command API for tunneling
[git/dscho.git] / imap-send.c
blob72ed640125ec1c1305c4e714ff9dfd96f2c34435
1 /*
2 * git-imap-send - drops patches into an imap Drafts folder
3 * derived from isync/mbsync - mailbox synchronizer
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
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.
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.
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
25 #include "cache.h"
26 #include "exec_cmd.h"
27 #include "run-command.h"
28 #ifdef NO_OPENSSL
29 typedef void *SSL;
30 #endif
32 struct store_conf {
33 char *name;
34 const char *path; /* should this be here? its interpretation is driver-specific */
35 char *map_inbox;
36 char *trash;
37 unsigned max_size; /* off_t is overkill */
38 unsigned trash_remote_new:1, trash_only_new:1;
41 struct string_list {
42 struct string_list *next;
43 char string[1];
46 struct channel_conf {
47 struct channel_conf *next;
48 char *name;
49 struct store_conf *master, *slave;
50 char *master_name, *slave_name;
51 char *sync_state;
52 struct string_list *patterns;
53 int mops, sops;
54 unsigned max_messages; /* for slave only */
57 struct group_conf {
58 struct group_conf *next;
59 char *name;
60 struct string_list *channels;
63 /* For message->status */
64 #define M_RECENT (1<<0) /* unsyncable flag; maildir_* depend on this being 1<<0 */
65 #define M_DEAD (1<<1) /* expunged */
66 #define M_FLAGS (1<<2) /* flags fetched */
68 struct message {
69 struct message *next;
70 /* struct string_list *keywords; */
71 size_t size; /* zero implies "not fetched" */
72 int uid;
73 unsigned char flags, status;
76 struct store {
77 struct store_conf *conf; /* foreign */
79 /* currently open mailbox */
80 const char *name; /* foreign! maybe preset? */
81 char *path; /* own */
82 struct message *msgs; /* own */
83 int uidvalidity;
84 unsigned char opts; /* maybe preset? */
85 /* note that the following do _not_ reflect stats from msgs, but mailbox totals */
86 int count; /* # of messages */
87 int recent; /* # of recent messages - don't trust this beyond the initial read */
90 struct msg_data {
91 char *data;
92 int len;
93 unsigned char flags;
94 unsigned int crlf:1;
97 #define DRV_OK 0
98 #define DRV_MSG_BAD -1
99 #define DRV_BOX_BAD -2
100 #define DRV_STORE_BAD -3
102 static int Verbose, Quiet;
104 static void imap_info(const char *, ...);
105 static void imap_warn(const char *, ...);
107 static char *next_arg(char **);
109 static void free_generic_messages(struct message *);
111 static int nfsnprintf(char *buf, int blen, const char *fmt, ...);
113 static int nfvasprintf(char **strp, const char *fmt, va_list ap)
115 int len;
116 char tmp[8192];
118 len = vsnprintf(tmp, sizeof(tmp), fmt, ap);
119 if (len < 0)
120 die("Fatal: Out of memory");
121 if (len >= sizeof(tmp))
122 die("imap command overflow!");
123 *strp = xmemdupz(tmp, len);
124 return len;
127 struct imap_server_conf {
128 char *name;
129 char *tunnel;
130 char *host;
131 int port;
132 char *user;
133 char *pass;
134 int use_ssl;
135 int ssl_verify;
136 int use_html;
139 struct imap_store_conf {
140 struct store_conf gen;
141 struct imap_server_conf *server;
142 unsigned use_namespace:1;
145 #define NIL (void *)0x1
146 #define LIST (void *)0x2
148 struct imap_list {
149 struct imap_list *next, *child;
150 char *val;
151 int len;
154 struct imap_socket {
155 int fd[2];
156 SSL *ssl;
159 struct imap_buffer {
160 struct imap_socket sock;
161 int bytes;
162 int offset;
163 char buf[1024];
166 struct imap_cmd;
168 struct imap {
169 int uidnext; /* from SELECT responses */
170 struct imap_list *ns_personal, *ns_other, *ns_shared; /* NAMESPACE info */
171 unsigned caps, rcaps; /* CAPABILITY results */
172 /* command queue */
173 int nexttag, num_in_progress, literal_pending;
174 struct imap_cmd *in_progress, **in_progress_append;
175 struct imap_buffer buf; /* this is BIG, so put it last */
178 struct imap_store {
179 struct store gen;
180 int uidvalidity;
181 struct imap *imap;
182 const char *prefix;
183 unsigned /*currentnc:1,*/ trashnc:1;
186 struct imap_cmd_cb {
187 int (*cont)(struct imap_store *ctx, struct imap_cmd *cmd, const char *prompt);
188 void (*done)(struct imap_store *ctx, struct imap_cmd *cmd, int response);
189 void *ctx;
190 char *data;
191 int dlen;
192 int uid;
193 unsigned create:1, trycreate:1;
196 struct imap_cmd {
197 struct imap_cmd *next;
198 struct imap_cmd_cb cb;
199 char *cmd;
200 int tag;
203 #define CAP(cap) (imap->caps & (1 << (cap)))
205 enum CAPABILITY {
206 NOLOGIN = 0,
207 UIDPLUS,
208 LITERALPLUS,
209 NAMESPACE,
210 STARTTLS,
213 static const char *cap_list[] = {
214 "LOGINDISABLED",
215 "UIDPLUS",
216 "LITERAL+",
217 "NAMESPACE",
218 "STARTTLS",
221 #define RESP_OK 0
222 #define RESP_NO 1
223 #define RESP_BAD 2
225 static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd);
228 static const char *Flags[] = {
229 "Draft",
230 "Flagged",
231 "Answered",
232 "Seen",
233 "Deleted",
236 #ifndef NO_OPENSSL
237 static void ssl_socket_perror(const char *func)
239 fprintf(stderr, "%s: %s\n", func, ERR_error_string(ERR_get_error(), NULL));
241 #endif
243 static void socket_perror(const char *func, struct imap_socket *sock, int ret)
245 #ifndef NO_OPENSSL
246 if (sock->ssl) {
247 int sslerr = SSL_get_error(sock->ssl, ret);
248 switch (sslerr) {
249 case SSL_ERROR_NONE:
250 break;
251 case SSL_ERROR_SYSCALL:
252 perror("SSL_connect");
253 break;
254 default:
255 ssl_socket_perror("SSL_connect");
256 break;
258 } else
259 #endif
261 if (ret < 0)
262 perror(func);
263 else
264 fprintf(stderr, "%s: unexpected EOF\n", func);
268 static int ssl_socket_connect(struct imap_socket *sock, int use_tls_only, int verify)
270 #ifdef NO_OPENSSL
271 fprintf(stderr, "SSL requested but SSL support not compiled in\n");
272 return -1;
273 #else
274 SSL_METHOD *meth;
275 SSL_CTX *ctx;
276 int ret;
278 SSL_library_init();
279 SSL_load_error_strings();
281 if (use_tls_only)
282 meth = TLSv1_method();
283 else
284 meth = SSLv23_method();
286 if (!meth) {
287 ssl_socket_perror("SSLv23_method");
288 return -1;
291 ctx = SSL_CTX_new(meth);
293 if (verify)
294 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
296 if (!SSL_CTX_set_default_verify_paths(ctx)) {
297 ssl_socket_perror("SSL_CTX_set_default_verify_paths");
298 return -1;
300 sock->ssl = SSL_new(ctx);
301 if (!sock->ssl) {
302 ssl_socket_perror("SSL_new");
303 return -1;
305 if (!SSL_set_rfd(sock->ssl, sock->fd[0])) {
306 ssl_socket_perror("SSL_set_rfd");
307 return -1;
309 if (!SSL_set_wfd(sock->ssl, sock->fd[1])) {
310 ssl_socket_perror("SSL_set_wfd");
311 return -1;
314 ret = SSL_connect(sock->ssl);
315 if (ret <= 0) {
316 socket_perror("SSL_connect", sock, ret);
317 return -1;
320 return 0;
321 #endif
324 static int socket_read(struct imap_socket *sock, char *buf, int len)
326 ssize_t n;
327 #ifndef NO_OPENSSL
328 if (sock->ssl)
329 n = SSL_read(sock->ssl, buf, len);
330 else
331 #endif
332 n = xread(sock->fd[0], buf, len);
333 if (n <= 0) {
334 socket_perror("read", sock, n);
335 close(sock->fd[0]);
336 close(sock->fd[1]);
337 sock->fd[0] = sock->fd[1] = -1;
339 return n;
342 static int socket_write(struct imap_socket *sock, const char *buf, int len)
344 int n;
345 #ifndef NO_OPENSSL
346 if (sock->ssl)
347 n = SSL_write(sock->ssl, buf, len);
348 else
349 #endif
350 n = write_in_full(sock->fd[1], buf, len);
351 if (n != len) {
352 socket_perror("write", sock, n);
353 close(sock->fd[0]);
354 close(sock->fd[1]);
355 sock->fd[0] = sock->fd[1] = -1;
357 return n;
360 static void socket_shutdown(struct imap_socket *sock)
362 #ifndef NO_OPENSSL
363 if (sock->ssl) {
364 SSL_shutdown(sock->ssl);
365 SSL_free(sock->ssl);
367 #endif
368 close(sock->fd[0]);
369 close(sock->fd[1]);
372 /* simple line buffering */
373 static int buffer_gets(struct imap_buffer *b, char **s)
375 int n;
376 int start = b->offset;
378 *s = b->buf + start;
380 for (;;) {
381 /* make sure we have enough data to read the \r\n sequence */
382 if (b->offset + 1 >= b->bytes) {
383 if (start) {
384 /* shift down used bytes */
385 *s = b->buf;
387 assert(start <= b->bytes);
388 n = b->bytes - start;
390 if (n)
391 memmove(b->buf, b->buf + start, n);
392 b->offset -= start;
393 b->bytes = n;
394 start = 0;
397 n = socket_read(&b->sock, b->buf + b->bytes,
398 sizeof(b->buf) - b->bytes);
400 if (n <= 0)
401 return -1;
403 b->bytes += n;
406 if (b->buf[b->offset] == '\r') {
407 assert(b->offset + 1 < b->bytes);
408 if (b->buf[b->offset + 1] == '\n') {
409 b->buf[b->offset] = 0; /* terminate the string */
410 b->offset += 2; /* next line */
411 if (Verbose)
412 puts(*s);
413 return 0;
417 b->offset++;
419 /* not reached */
422 static void imap_info(const char *msg, ...)
424 va_list va;
426 if (!Quiet) {
427 va_start(va, msg);
428 vprintf(msg, va);
429 va_end(va);
430 fflush(stdout);
434 static void imap_warn(const char *msg, ...)
436 va_list va;
438 if (Quiet < 2) {
439 va_start(va, msg);
440 vfprintf(stderr, msg, va);
441 va_end(va);
445 static char *next_arg(char **s)
447 char *ret;
449 if (!s || !*s)
450 return NULL;
451 while (isspace((unsigned char) **s))
452 (*s)++;
453 if (!**s) {
454 *s = NULL;
455 return NULL;
457 if (**s == '"') {
458 ++*s;
459 ret = *s;
460 *s = strchr(*s, '"');
461 } else {
462 ret = *s;
463 while (**s && !isspace((unsigned char) **s))
464 (*s)++;
466 if (*s) {
467 if (**s)
468 *(*s)++ = 0;
469 if (!**s)
470 *s = NULL;
472 return ret;
475 static void free_generic_messages(struct message *msgs)
477 struct message *tmsg;
479 for (; msgs; msgs = tmsg) {
480 tmsg = msgs->next;
481 free(msgs);
485 static int nfsnprintf(char *buf, int blen, const char *fmt, ...)
487 int ret;
488 va_list va;
490 va_start(va, fmt);
491 if (blen <= 0 || (unsigned)(ret = vsnprintf(buf, blen, fmt, va)) >= (unsigned)blen)
492 die("Fatal: buffer too small. Please report a bug.");
493 va_end(va);
494 return ret;
497 static struct imap_cmd *v_issue_imap_cmd(struct imap_store *ctx,
498 struct imap_cmd_cb *cb,
499 const char *fmt, va_list ap)
501 struct imap *imap = ctx->imap;
502 struct imap_cmd *cmd;
503 int n, bufl;
504 char buf[1024];
506 cmd = xmalloc(sizeof(struct imap_cmd));
507 nfvasprintf(&cmd->cmd, fmt, ap);
508 cmd->tag = ++imap->nexttag;
510 if (cb)
511 cmd->cb = *cb;
512 else
513 memset(&cmd->cb, 0, sizeof(cmd->cb));
515 while (imap->literal_pending)
516 get_cmd_result(ctx, NULL);
518 bufl = nfsnprintf(buf, sizeof(buf), cmd->cb.data ? CAP(LITERALPLUS) ?
519 "%d %s{%d+}\r\n" : "%d %s{%d}\r\n" : "%d %s\r\n",
520 cmd->tag, cmd->cmd, cmd->cb.dlen);
521 if (Verbose) {
522 if (imap->num_in_progress)
523 printf("(%d in progress) ", imap->num_in_progress);
524 if (memcmp(cmd->cmd, "LOGIN", 5))
525 printf(">>> %s", buf);
526 else
527 printf(">>> %d LOGIN <user> <pass>\n", cmd->tag);
529 if (socket_write(&imap->buf.sock, buf, bufl) != bufl) {
530 free(cmd->cmd);
531 free(cmd);
532 if (cb)
533 free(cb->data);
534 return NULL;
536 if (cmd->cb.data) {
537 if (CAP(LITERALPLUS)) {
538 n = socket_write(&imap->buf.sock, cmd->cb.data, cmd->cb.dlen);
539 free(cmd->cb.data);
540 if (n != cmd->cb.dlen ||
541 socket_write(&imap->buf.sock, "\r\n", 2) != 2) {
542 free(cmd->cmd);
543 free(cmd);
544 return NULL;
546 cmd->cb.data = NULL;
547 } else
548 imap->literal_pending = 1;
549 } else if (cmd->cb.cont)
550 imap->literal_pending = 1;
551 cmd->next = NULL;
552 *imap->in_progress_append = cmd;
553 imap->in_progress_append = &cmd->next;
554 imap->num_in_progress++;
555 return cmd;
558 static struct imap_cmd *issue_imap_cmd(struct imap_store *ctx,
559 struct imap_cmd_cb *cb,
560 const char *fmt, ...)
562 struct imap_cmd *ret;
563 va_list ap;
565 va_start(ap, fmt);
566 ret = v_issue_imap_cmd(ctx, cb, fmt, ap);
567 va_end(ap);
568 return ret;
571 static int imap_exec(struct imap_store *ctx, struct imap_cmd_cb *cb,
572 const char *fmt, ...)
574 va_list ap;
575 struct imap_cmd *cmdp;
577 va_start(ap, fmt);
578 cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
579 va_end(ap);
580 if (!cmdp)
581 return RESP_BAD;
583 return get_cmd_result(ctx, cmdp);
586 static int imap_exec_m(struct imap_store *ctx, struct imap_cmd_cb *cb,
587 const char *fmt, ...)
589 va_list ap;
590 struct imap_cmd *cmdp;
592 va_start(ap, fmt);
593 cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
594 va_end(ap);
595 if (!cmdp)
596 return DRV_STORE_BAD;
598 switch (get_cmd_result(ctx, cmdp)) {
599 case RESP_BAD: return DRV_STORE_BAD;
600 case RESP_NO: return DRV_MSG_BAD;
601 default: return DRV_OK;
605 static int is_atom(struct imap_list *list)
607 return list && list->val && list->val != NIL && list->val != LIST;
610 static int is_list(struct imap_list *list)
612 return list && list->val == LIST;
615 static void free_list(struct imap_list *list)
617 struct imap_list *tmp;
619 for (; list; list = tmp) {
620 tmp = list->next;
621 if (is_list(list))
622 free_list(list->child);
623 else if (is_atom(list))
624 free(list->val);
625 free(list);
629 static int parse_imap_list_l(struct imap *imap, char **sp, struct imap_list **curp, int level)
631 struct imap_list *cur;
632 char *s = *sp, *p;
633 int n, bytes;
635 for (;;) {
636 while (isspace((unsigned char)*s))
637 s++;
638 if (level && *s == ')') {
639 s++;
640 break;
642 *curp = cur = xmalloc(sizeof(*cur));
643 curp = &cur->next;
644 cur->val = NULL; /* for clean bail */
645 if (*s == '(') {
646 /* sublist */
647 s++;
648 cur->val = LIST;
649 if (parse_imap_list_l(imap, &s, &cur->child, level + 1))
650 goto bail;
651 } else if (imap && *s == '{') {
652 /* literal */
653 bytes = cur->len = strtol(s + 1, &s, 10);
654 if (*s != '}')
655 goto bail;
657 s = cur->val = xmalloc(cur->len);
659 /* dump whats left over in the input buffer */
660 n = imap->buf.bytes - imap->buf.offset;
662 if (n > bytes)
663 /* the entire message fit in the buffer */
664 n = bytes;
666 memcpy(s, imap->buf.buf + imap->buf.offset, n);
667 s += n;
668 bytes -= n;
670 /* mark that we used part of the buffer */
671 imap->buf.offset += n;
673 /* now read the rest of the message */
674 while (bytes > 0) {
675 if ((n = socket_read(&imap->buf.sock, s, bytes)) <= 0)
676 goto bail;
677 s += n;
678 bytes -= n;
681 if (buffer_gets(&imap->buf, &s))
682 goto bail;
683 } else if (*s == '"') {
684 /* quoted string */
685 s++;
686 p = s;
687 for (; *s != '"'; s++)
688 if (!*s)
689 goto bail;
690 cur->len = s - p;
691 s++;
692 cur->val = xmemdupz(p, cur->len);
693 } else {
694 /* atom */
695 p = s;
696 for (; *s && !isspace((unsigned char)*s); s++)
697 if (level && *s == ')')
698 break;
699 cur->len = s - p;
700 if (cur->len == 3 && !memcmp("NIL", p, 3))
701 cur->val = NIL;
702 else
703 cur->val = xmemdupz(p, cur->len);
706 if (!level)
707 break;
708 if (!*s)
709 goto bail;
711 *sp = s;
712 *curp = NULL;
713 return 0;
715 bail:
716 *curp = NULL;
717 return -1;
720 static struct imap_list *parse_imap_list(struct imap *imap, char **sp)
722 struct imap_list *head;
724 if (!parse_imap_list_l(imap, sp, &head, 0))
725 return head;
726 free_list(head);
727 return NULL;
730 static struct imap_list *parse_list(char **sp)
732 return parse_imap_list(NULL, sp);
735 static void parse_capability(struct imap *imap, char *cmd)
737 char *arg;
738 unsigned i;
740 imap->caps = 0x80000000;
741 while ((arg = next_arg(&cmd)))
742 for (i = 0; i < ARRAY_SIZE(cap_list); i++)
743 if (!strcmp(cap_list[i], arg))
744 imap->caps |= 1 << i;
745 imap->rcaps = imap->caps;
748 static int parse_response_code(struct imap_store *ctx, struct imap_cmd_cb *cb,
749 char *s)
751 struct imap *imap = ctx->imap;
752 char *arg, *p;
754 if (*s != '[')
755 return RESP_OK; /* no response code */
756 s++;
757 if (!(p = strchr(s, ']'))) {
758 fprintf(stderr, "IMAP error: malformed response code\n");
759 return RESP_BAD;
761 *p++ = 0;
762 arg = next_arg(&s);
763 if (!strcmp("UIDVALIDITY", arg)) {
764 if (!(arg = next_arg(&s)) || !(ctx->gen.uidvalidity = atoi(arg))) {
765 fprintf(stderr, "IMAP error: malformed UIDVALIDITY status\n");
766 return RESP_BAD;
768 } else if (!strcmp("UIDNEXT", arg)) {
769 if (!(arg = next_arg(&s)) || !(imap->uidnext = atoi(arg))) {
770 fprintf(stderr, "IMAP error: malformed NEXTUID status\n");
771 return RESP_BAD;
773 } else if (!strcmp("CAPABILITY", arg)) {
774 parse_capability(imap, s);
775 } else if (!strcmp("ALERT", arg)) {
776 /* RFC2060 says that these messages MUST be displayed
777 * to the user
779 for (; isspace((unsigned char)*p); p++);
780 fprintf(stderr, "*** IMAP ALERT *** %s\n", p);
781 } else if (cb && cb->ctx && !strcmp("APPENDUID", arg)) {
782 if (!(arg = next_arg(&s)) || !(ctx->gen.uidvalidity = atoi(arg)) ||
783 !(arg = next_arg(&s)) || !(*(int *)cb->ctx = atoi(arg))) {
784 fprintf(stderr, "IMAP error: malformed APPENDUID status\n");
785 return RESP_BAD;
788 return RESP_OK;
791 static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd)
793 struct imap *imap = ctx->imap;
794 struct imap_cmd *cmdp, **pcmdp, *ncmdp;
795 char *cmd, *arg, *arg1, *p;
796 int n, resp, resp2, tag;
798 for (;;) {
799 if (buffer_gets(&imap->buf, &cmd))
800 return RESP_BAD;
802 arg = next_arg(&cmd);
803 if (*arg == '*') {
804 arg = next_arg(&cmd);
805 if (!arg) {
806 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
807 return RESP_BAD;
810 if (!strcmp("NAMESPACE", arg)) {
811 imap->ns_personal = parse_list(&cmd);
812 imap->ns_other = parse_list(&cmd);
813 imap->ns_shared = parse_list(&cmd);
814 } else if (!strcmp("OK", arg) || !strcmp("BAD", arg) ||
815 !strcmp("NO", arg) || !strcmp("BYE", arg)) {
816 if ((resp = parse_response_code(ctx, NULL, cmd)) != RESP_OK)
817 return resp;
818 } else if (!strcmp("CAPABILITY", arg))
819 parse_capability(imap, cmd);
820 else if ((arg1 = next_arg(&cmd))) {
821 if (!strcmp("EXISTS", arg1))
822 ctx->gen.count = atoi(arg);
823 else if (!strcmp("RECENT", arg1))
824 ctx->gen.recent = atoi(arg);
825 } else {
826 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
827 return RESP_BAD;
829 } else if (!imap->in_progress) {
830 fprintf(stderr, "IMAP error: unexpected reply: %s %s\n", arg, cmd ? cmd : "");
831 return RESP_BAD;
832 } else if (*arg == '+') {
833 /* This can happen only with the last command underway, as
834 it enforces a round-trip. */
835 cmdp = (struct imap_cmd *)((char *)imap->in_progress_append -
836 offsetof(struct imap_cmd, next));
837 if (cmdp->cb.data) {
838 n = socket_write(&imap->buf.sock, cmdp->cb.data, cmdp->cb.dlen);
839 free(cmdp->cb.data);
840 cmdp->cb.data = NULL;
841 if (n != (int)cmdp->cb.dlen)
842 return RESP_BAD;
843 } else if (cmdp->cb.cont) {
844 if (cmdp->cb.cont(ctx, cmdp, cmd))
845 return RESP_BAD;
846 } else {
847 fprintf(stderr, "IMAP error: unexpected command continuation request\n");
848 return RESP_BAD;
850 if (socket_write(&imap->buf.sock, "\r\n", 2) != 2)
851 return RESP_BAD;
852 if (!cmdp->cb.cont)
853 imap->literal_pending = 0;
854 if (!tcmd)
855 return DRV_OK;
856 } else {
857 tag = atoi(arg);
858 for (pcmdp = &imap->in_progress; (cmdp = *pcmdp); pcmdp = &cmdp->next)
859 if (cmdp->tag == tag)
860 goto gottag;
861 fprintf(stderr, "IMAP error: unexpected tag %s\n", arg);
862 return RESP_BAD;
863 gottag:
864 if (!(*pcmdp = cmdp->next))
865 imap->in_progress_append = pcmdp;
866 imap->num_in_progress--;
867 if (cmdp->cb.cont || cmdp->cb.data)
868 imap->literal_pending = 0;
869 arg = next_arg(&cmd);
870 if (!strcmp("OK", arg))
871 resp = DRV_OK;
872 else {
873 if (!strcmp("NO", arg)) {
874 if (cmdp->cb.create && cmd && (cmdp->cb.trycreate || !memcmp(cmd, "[TRYCREATE]", 11))) { /* SELECT, APPEND or UID COPY */
875 p = strchr(cmdp->cmd, '"');
876 if (!issue_imap_cmd(ctx, NULL, "CREATE \"%.*s\"", strchr(p + 1, '"') - p + 1, p)) {
877 resp = RESP_BAD;
878 goto normal;
880 /* not waiting here violates the spec, but a server that does not
881 grok this nonetheless violates it too. */
882 cmdp->cb.create = 0;
883 if (!(ncmdp = issue_imap_cmd(ctx, &cmdp->cb, "%s", cmdp->cmd))) {
884 resp = RESP_BAD;
885 goto normal;
887 free(cmdp->cmd);
888 free(cmdp);
889 if (!tcmd)
890 return 0; /* ignored */
891 if (cmdp == tcmd)
892 tcmd = ncmdp;
893 continue;
895 resp = RESP_NO;
896 } else /*if (!strcmp("BAD", arg))*/
897 resp = RESP_BAD;
898 fprintf(stderr, "IMAP command '%s' returned response (%s) - %s\n",
899 memcmp(cmdp->cmd, "LOGIN", 5) ?
900 cmdp->cmd : "LOGIN <user> <pass>",
901 arg, cmd ? cmd : "");
903 if ((resp2 = parse_response_code(ctx, &cmdp->cb, cmd)) > resp)
904 resp = resp2;
905 normal:
906 if (cmdp->cb.done)
907 cmdp->cb.done(ctx, cmdp, resp);
908 free(cmdp->cb.data);
909 free(cmdp->cmd);
910 free(cmdp);
911 if (!tcmd || tcmd == cmdp)
912 return resp;
915 /* not reached */
918 static void imap_close_server(struct imap_store *ictx)
920 struct imap *imap = ictx->imap;
922 if (imap->buf.sock.fd[0] != -1) {
923 imap_exec(ictx, NULL, "LOGOUT");
924 socket_shutdown(&imap->buf.sock);
926 free_list(imap->ns_personal);
927 free_list(imap->ns_other);
928 free_list(imap->ns_shared);
929 free(imap);
932 static void imap_close_store(struct store *ctx)
934 imap_close_server((struct imap_store *)ctx);
935 free_generic_messages(ctx->msgs);
936 free(ctx);
939 static struct store *imap_open_store(struct imap_server_conf *srvc)
941 struct imap_store *ctx;
942 struct imap *imap;
943 char *arg, *rsp;
944 int s = -1, preauth;
946 ctx = xcalloc(sizeof(*ctx), 1);
948 ctx->imap = imap = xcalloc(sizeof(*imap), 1);
949 imap->buf.sock.fd[0] = imap->buf.sock.fd[1] = -1;
950 imap->in_progress_append = &imap->in_progress;
952 /* open connection to IMAP server */
954 if (srvc->tunnel) {
955 const char *argv[4];
956 struct child_process tunnel = {0};
958 imap_info("Starting tunnel '%s'... ", srvc->tunnel);
960 argv[0] = "sh";
961 argv[1] = "-c";
962 argv[2] = srvc->tunnel;
963 argv[3] = NULL;
965 tunnel.argv = argv;
966 tunnel.in = -1;
967 tunnel.out = -1;
968 if (start_command(&tunnel))
969 die("cannot start proxy %s", argv[0]);
971 imap->buf.sock.fd[0] = tunnel.out;
972 imap->buf.sock.fd[1] = tunnel.in;
974 imap_info("ok\n");
975 } else {
976 #ifndef NO_IPV6
977 struct addrinfo hints, *ai0, *ai;
978 int gai;
979 char portstr[6];
981 snprintf(portstr, sizeof(portstr), "%hu", srvc->port);
983 memset(&hints, 0, sizeof(hints));
984 hints.ai_socktype = SOCK_STREAM;
985 hints.ai_protocol = IPPROTO_TCP;
987 imap_info("Resolving %s... ", srvc->host);
988 gai = getaddrinfo(srvc->host, portstr, &hints, &ai);
989 if (gai) {
990 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai));
991 goto bail;
993 imap_info("ok\n");
995 for (ai0 = ai; ai; ai = ai->ai_next) {
996 char addr[NI_MAXHOST];
998 s = socket(ai->ai_family, ai->ai_socktype,
999 ai->ai_protocol);
1000 if (s < 0)
1001 continue;
1003 getnameinfo(ai->ai_addr, ai->ai_addrlen, addr,
1004 sizeof(addr), NULL, 0, NI_NUMERICHOST);
1005 imap_info("Connecting to [%s]:%s... ", addr, portstr);
1007 if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0) {
1008 close(s);
1009 s = -1;
1010 perror("connect");
1011 continue;
1014 break;
1016 freeaddrinfo(ai0);
1017 #else /* NO_IPV6 */
1018 struct hostent *he;
1019 struct sockaddr_in addr;
1021 memset(&addr, 0, sizeof(addr));
1022 addr.sin_port = htons(srvc->port);
1023 addr.sin_family = AF_INET;
1025 imap_info("Resolving %s... ", srvc->host);
1026 he = gethostbyname(srvc->host);
1027 if (!he) {
1028 perror("gethostbyname");
1029 goto bail;
1031 imap_info("ok\n");
1033 addr.sin_addr.s_addr = *((int *) he->h_addr_list[0]);
1035 s = socket(PF_INET, SOCK_STREAM, 0);
1037 imap_info("Connecting to %s:%hu... ", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
1038 if (connect(s, (struct sockaddr *)&addr, sizeof(addr))) {
1039 close(s);
1040 s = -1;
1041 perror("connect");
1043 #endif
1044 if (s < 0) {
1045 fputs("Error: unable to connect to server.\n", stderr);
1046 goto bail;
1049 imap->buf.sock.fd[0] = s;
1050 imap->buf.sock.fd[1] = dup(s);
1052 if (srvc->use_ssl &&
1053 ssl_socket_connect(&imap->buf.sock, 0, srvc->ssl_verify)) {
1054 close(s);
1055 goto bail;
1057 imap_info("ok\n");
1060 /* read the greeting string */
1061 if (buffer_gets(&imap->buf, &rsp)) {
1062 fprintf(stderr, "IMAP error: no greeting response\n");
1063 goto bail;
1065 arg = next_arg(&rsp);
1066 if (!arg || *arg != '*' || (arg = next_arg(&rsp)) == NULL) {
1067 fprintf(stderr, "IMAP error: invalid greeting response\n");
1068 goto bail;
1070 preauth = 0;
1071 if (!strcmp("PREAUTH", arg))
1072 preauth = 1;
1073 else if (strcmp("OK", arg) != 0) {
1074 fprintf(stderr, "IMAP error: unknown greeting response\n");
1075 goto bail;
1077 parse_response_code(ctx, NULL, rsp);
1078 if (!imap->caps && imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1079 goto bail;
1081 if (!preauth) {
1082 #ifndef NO_OPENSSL
1083 if (!srvc->use_ssl && CAP(STARTTLS)) {
1084 if (imap_exec(ctx, 0, "STARTTLS") != RESP_OK)
1085 goto bail;
1086 if (ssl_socket_connect(&imap->buf.sock, 1,
1087 srvc->ssl_verify))
1088 goto bail;
1089 /* capabilities may have changed, so get the new capabilities */
1090 if (imap_exec(ctx, 0, "CAPABILITY") != RESP_OK)
1091 goto bail;
1093 #endif
1094 imap_info("Logging in...\n");
1095 if (!srvc->user) {
1096 fprintf(stderr, "Skipping server %s, no user\n", srvc->host);
1097 goto bail;
1099 if (!srvc->pass) {
1100 char prompt[80];
1101 sprintf(prompt, "Password (%s@%s): ", srvc->user, srvc->host);
1102 arg = getpass(prompt);
1103 if (!arg) {
1104 perror("getpass");
1105 exit(1);
1107 if (!*arg) {
1108 fprintf(stderr, "Skipping account %s@%s, no password\n", srvc->user, srvc->host);
1109 goto bail;
1112 * getpass() returns a pointer to a static buffer. make a copy
1113 * for long term storage.
1115 srvc->pass = xstrdup(arg);
1117 if (CAP(NOLOGIN)) {
1118 fprintf(stderr, "Skipping account %s@%s, server forbids LOGIN\n", srvc->user, srvc->host);
1119 goto bail;
1121 if (!imap->buf.sock.ssl)
1122 imap_warn("*** IMAP Warning *** Password is being "
1123 "sent in the clear\n");
1124 if (imap_exec(ctx, NULL, "LOGIN \"%s\" \"%s\"", srvc->user, srvc->pass) != RESP_OK) {
1125 fprintf(stderr, "IMAP error: LOGIN failed\n");
1126 goto bail;
1128 } /* !preauth */
1130 ctx->prefix = "";
1131 ctx->trashnc = 1;
1132 return (struct store *)ctx;
1134 bail:
1135 imap_close_store(&ctx->gen);
1136 return NULL;
1139 static int imap_make_flags(int flags, char *buf)
1141 const char *s;
1142 unsigned i, d;
1144 for (i = d = 0; i < ARRAY_SIZE(Flags); i++)
1145 if (flags & (1 << i)) {
1146 buf[d++] = ' ';
1147 buf[d++] = '\\';
1148 for (s = Flags[i]; *s; s++)
1149 buf[d++] = *s;
1151 buf[0] = '(';
1152 buf[d++] = ')';
1153 return d;
1156 static int imap_store_msg(struct store *gctx, struct msg_data *data)
1158 struct imap_store *ctx = (struct imap_store *)gctx;
1159 struct imap *imap = ctx->imap;
1160 struct imap_cmd_cb cb;
1161 const char *prefix, *box;
1162 int ret, d;
1163 char flagstr[128];
1165 memset(&cb, 0, sizeof(cb));
1167 cb.dlen = data->len;
1168 cb.data = xmalloc(cb.dlen);
1169 memcpy(cb.data, data->data, data->len);
1171 d = 0;
1172 if (data->flags) {
1173 d = imap_make_flags(data->flags, flagstr);
1174 flagstr[d++] = ' ';
1176 flagstr[d] = 0;
1178 box = gctx->name;
1179 prefix = !strcmp(box, "INBOX") ? "" : ctx->prefix;
1180 cb.create = 0;
1181 ret = imap_exec_m(ctx, &cb, "APPEND \"%s%s\" %s", prefix, box, flagstr);
1182 imap->caps = imap->rcaps;
1183 if (ret != DRV_OK)
1184 return ret;
1185 gctx->count++;
1187 return DRV_OK;
1190 static void encode_html_chars(struct strbuf *p)
1192 int i;
1193 for (i = 0; i < p->len; i++) {
1194 if (p->buf[i] == '&')
1195 strbuf_splice(p, i, 1, "&amp;", 5);
1196 if (p->buf[i] == '<')
1197 strbuf_splice(p, i, 1, "&lt;", 4);
1198 if (p->buf[i] == '>')
1199 strbuf_splice(p, i, 1, "&gt;", 4);
1200 if (p->buf[i] == '"')
1201 strbuf_splice(p, i, 1, "&quot;", 6);
1204 static void wrap_in_html(struct msg_data *msg)
1206 struct strbuf buf = STRBUF_INIT;
1207 struct strbuf **lines;
1208 struct strbuf **p;
1209 static char *content_type = "Content-Type: text/html;\n";
1210 static char *pre_open = "<pre>\n";
1211 static char *pre_close = "</pre>\n";
1212 int added_header = 0;
1214 strbuf_attach(&buf, msg->data, msg->len, msg->len);
1215 lines = strbuf_split(&buf, '\n');
1216 strbuf_release(&buf);
1217 for (p = lines; *p; p++) {
1218 if (! added_header) {
1219 if ((*p)->len == 1 && *((*p)->buf) == '\n') {
1220 strbuf_addstr(&buf, content_type);
1221 strbuf_addbuf(&buf, *p);
1222 strbuf_addstr(&buf, pre_open);
1223 added_header = 1;
1224 continue;
1227 else
1228 encode_html_chars(*p);
1229 strbuf_addbuf(&buf, *p);
1231 strbuf_addstr(&buf, pre_close);
1232 strbuf_list_free(lines);
1233 msg->len = buf.len;
1234 msg->data = strbuf_detach(&buf, NULL);
1237 #define CHUNKSIZE 0x1000
1239 static int read_message(FILE *f, struct msg_data *msg)
1241 struct strbuf buf = STRBUF_INIT;
1243 memset(msg, 0, sizeof(*msg));
1245 do {
1246 if (strbuf_fread(&buf, CHUNKSIZE, f) <= 0)
1247 break;
1248 } while (!feof(f));
1250 msg->len = buf.len;
1251 msg->data = strbuf_detach(&buf, NULL);
1252 return msg->len;
1255 static int count_messages(struct msg_data *msg)
1257 int count = 0;
1258 char *p = msg->data;
1260 while (1) {
1261 if (!prefixcmp(p, "From ")) {
1262 count++;
1263 p += 5;
1265 p = strstr(p+5, "\nFrom ");
1266 if (!p)
1267 break;
1268 p++;
1270 return count;
1273 static int split_msg(struct msg_data *all_msgs, struct msg_data *msg, int *ofs)
1275 char *p, *data;
1277 memset(msg, 0, sizeof *msg);
1278 if (*ofs >= all_msgs->len)
1279 return 0;
1281 data = &all_msgs->data[*ofs];
1282 msg->len = all_msgs->len - *ofs;
1284 if (msg->len < 5 || prefixcmp(data, "From "))
1285 return 0;
1287 p = strchr(data, '\n');
1288 if (p) {
1289 p = &p[1];
1290 msg->len -= p-data;
1291 *ofs += p-data;
1292 data = p;
1295 p = strstr(data, "\nFrom ");
1296 if (p)
1297 msg->len = &p[1] - data;
1299 msg->data = xmemdupz(data, msg->len);
1300 *ofs += msg->len;
1301 return 1;
1304 static struct imap_server_conf server = {
1305 NULL, /* name */
1306 NULL, /* tunnel */
1307 NULL, /* host */
1308 0, /* port */
1309 NULL, /* user */
1310 NULL, /* pass */
1311 0, /* use_ssl */
1312 1, /* ssl_verify */
1313 0, /* use_html */
1316 static char *imap_folder;
1318 static int git_imap_config(const char *key, const char *val, void *cb)
1320 char imap_key[] = "imap.";
1322 if (strncmp(key, imap_key, sizeof imap_key - 1))
1323 return 0;
1325 if (!val)
1326 return config_error_nonbool(key);
1328 key += sizeof imap_key - 1;
1330 if (!strcmp("folder", key)) {
1331 imap_folder = xstrdup(val);
1332 } else if (!strcmp("host", key)) {
1333 if (!prefixcmp(val, "imap:"))
1334 val += 5;
1335 else if (!prefixcmp(val, "imaps:")) {
1336 val += 6;
1337 server.use_ssl = 1;
1339 if (!prefixcmp(val, "//"))
1340 val += 2;
1341 server.host = xstrdup(val);
1342 } else if (!strcmp("user", key))
1343 server.user = xstrdup(val);
1344 else if (!strcmp("pass", key))
1345 server.pass = xstrdup(val);
1346 else if (!strcmp("port", key))
1347 server.port = git_config_int(key, val);
1348 else if (!strcmp("tunnel", key))
1349 server.tunnel = xstrdup(val);
1350 else if (!strcmp("sslverify", key))
1351 server.ssl_verify = git_config_bool(key, val);
1352 else if (!strcmp("preformattedHTML", key))
1353 server.use_html = git_config_bool(key, val);
1354 return 0;
1357 int main(int argc, char **argv)
1359 struct msg_data all_msgs, msg;
1360 struct store *ctx = NULL;
1361 int ofs = 0;
1362 int r;
1363 int total, n = 0;
1364 int nongit_ok;
1366 git_extract_argv0_path(argv[0]);
1368 setup_git_directory_gently(&nongit_ok);
1369 git_config(git_imap_config, NULL);
1371 if (!server.port)
1372 server.port = server.use_ssl ? 993 : 143;
1374 if (!imap_folder) {
1375 fprintf(stderr, "no imap store specified\n");
1376 return 1;
1378 if (!server.host) {
1379 if (!server.tunnel) {
1380 fprintf(stderr, "no imap host specified\n");
1381 return 1;
1383 server.host = "tunnel";
1386 /* read the messages */
1387 if (!read_message(stdin, &all_msgs)) {
1388 fprintf(stderr, "nothing to send\n");
1389 return 1;
1392 total = count_messages(&all_msgs);
1393 if (!total) {
1394 fprintf(stderr, "no messages to send\n");
1395 return 1;
1398 /* write it to the imap server */
1399 ctx = imap_open_store(&server);
1400 if (!ctx) {
1401 fprintf(stderr, "failed to open store\n");
1402 return 1;
1405 fprintf(stderr, "sending %d message%s\n", total, (total != 1) ? "s" : "");
1406 ctx->name = imap_folder;
1407 while (1) {
1408 unsigned percent = n * 100 / total;
1409 fprintf(stderr, "%4u%% (%d/%d) done\r", percent, n, total);
1410 if (!split_msg(&all_msgs, &msg, &ofs))
1411 break;
1412 if (server.use_html)
1413 wrap_in_html(&msg);
1414 r = imap_store_msg(ctx, &msg);
1415 if (r != DRV_OK)
1416 break;
1417 n++;
1419 fprintf(stderr, "\n");
1421 imap_close_store(ctx);
1423 return 0;