imap-send: use separate read and write fds
[git/dscho.git] / imap-send.c
blob7216453ceb428ecffa90118c7335a061e92fc524
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 #ifdef NO_OPENSSL
28 typedef void *SSL;
29 #endif
31 struct store_conf {
32 char *name;
33 const char *path; /* should this be here? its interpretation is driver-specific */
34 char *map_inbox;
35 char *trash;
36 unsigned max_size; /* off_t is overkill */
37 unsigned trash_remote_new:1, trash_only_new:1;
40 struct string_list {
41 struct string_list *next;
42 char string[1];
45 struct channel_conf {
46 struct channel_conf *next;
47 char *name;
48 struct store_conf *master, *slave;
49 char *master_name, *slave_name;
50 char *sync_state;
51 struct string_list *patterns;
52 int mops, sops;
53 unsigned max_messages; /* for slave only */
56 struct group_conf {
57 struct group_conf *next;
58 char *name;
59 struct string_list *channels;
62 /* For message->status */
63 #define M_RECENT (1<<0) /* unsyncable flag; maildir_* depend on this being 1<<0 */
64 #define M_DEAD (1<<1) /* expunged */
65 #define M_FLAGS (1<<2) /* flags fetched */
67 struct message {
68 struct message *next;
69 /* struct string_list *keywords; */
70 size_t size; /* zero implies "not fetched" */
71 int uid;
72 unsigned char flags, status;
75 struct store {
76 struct store_conf *conf; /* foreign */
78 /* currently open mailbox */
79 const char *name; /* foreign! maybe preset? */
80 char *path; /* own */
81 struct message *msgs; /* own */
82 int uidvalidity;
83 unsigned char opts; /* maybe preset? */
84 /* note that the following do _not_ reflect stats from msgs, but mailbox totals */
85 int count; /* # of messages */
86 int recent; /* # of recent messages - don't trust this beyond the initial read */
89 struct msg_data {
90 char *data;
91 int len;
92 unsigned char flags;
93 unsigned int crlf:1;
96 #define DRV_OK 0
97 #define DRV_MSG_BAD -1
98 #define DRV_BOX_BAD -2
99 #define DRV_STORE_BAD -3
101 static int Verbose, Quiet;
103 static void imap_info(const char *, ...);
104 static void imap_warn(const char *, ...);
106 static char *next_arg(char **);
108 static void free_generic_messages(struct message *);
110 static int nfsnprintf(char *buf, int blen, const char *fmt, ...);
112 static int nfvasprintf(char **strp, const char *fmt, va_list ap)
114 int len;
115 char tmp[8192];
117 len = vsnprintf(tmp, sizeof(tmp), fmt, ap);
118 if (len < 0)
119 die("Fatal: Out of memory");
120 if (len >= sizeof(tmp))
121 die("imap command overflow!");
122 *strp = xmemdupz(tmp, len);
123 return len;
126 struct imap_server_conf {
127 char *name;
128 char *tunnel;
129 char *host;
130 int port;
131 char *user;
132 char *pass;
133 int use_ssl;
134 int ssl_verify;
135 int use_html;
138 struct imap_store_conf {
139 struct store_conf gen;
140 struct imap_server_conf *server;
141 unsigned use_namespace:1;
144 #define NIL (void *)0x1
145 #define LIST (void *)0x2
147 struct imap_list {
148 struct imap_list *next, *child;
149 char *val;
150 int len;
153 struct imap_socket {
154 int fd[2];
155 SSL *ssl;
158 struct imap_buffer {
159 struct imap_socket sock;
160 int bytes;
161 int offset;
162 char buf[1024];
165 struct imap_cmd;
167 struct imap {
168 int uidnext; /* from SELECT responses */
169 struct imap_list *ns_personal, *ns_other, *ns_shared; /* NAMESPACE info */
170 unsigned caps, rcaps; /* CAPABILITY results */
171 /* command queue */
172 int nexttag, num_in_progress, literal_pending;
173 struct imap_cmd *in_progress, **in_progress_append;
174 struct imap_buffer buf; /* this is BIG, so put it last */
177 struct imap_store {
178 struct store gen;
179 int uidvalidity;
180 struct imap *imap;
181 const char *prefix;
182 unsigned /*currentnc:1,*/ trashnc:1;
185 struct imap_cmd_cb {
186 int (*cont)(struct imap_store *ctx, struct imap_cmd *cmd, const char *prompt);
187 void (*done)(struct imap_store *ctx, struct imap_cmd *cmd, int response);
188 void *ctx;
189 char *data;
190 int dlen;
191 int uid;
192 unsigned create:1, trycreate:1;
195 struct imap_cmd {
196 struct imap_cmd *next;
197 struct imap_cmd_cb cb;
198 char *cmd;
199 int tag;
202 #define CAP(cap) (imap->caps & (1 << (cap)))
204 enum CAPABILITY {
205 NOLOGIN = 0,
206 UIDPLUS,
207 LITERALPLUS,
208 NAMESPACE,
209 STARTTLS,
212 static const char *cap_list[] = {
213 "LOGINDISABLED",
214 "UIDPLUS",
215 "LITERAL+",
216 "NAMESPACE",
217 "STARTTLS",
220 #define RESP_OK 0
221 #define RESP_NO 1
222 #define RESP_BAD 2
224 static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd);
227 static const char *Flags[] = {
228 "Draft",
229 "Flagged",
230 "Answered",
231 "Seen",
232 "Deleted",
235 #ifndef NO_OPENSSL
236 static void ssl_socket_perror(const char *func)
238 fprintf(stderr, "%s: %s\n", func, ERR_error_string(ERR_get_error(), NULL));
240 #endif
242 static void socket_perror(const char *func, struct imap_socket *sock, int ret)
244 #ifndef NO_OPENSSL
245 if (sock->ssl) {
246 int sslerr = SSL_get_error(sock->ssl, ret);
247 switch (sslerr) {
248 case SSL_ERROR_NONE:
249 break;
250 case SSL_ERROR_SYSCALL:
251 perror("SSL_connect");
252 break;
253 default:
254 ssl_socket_perror("SSL_connect");
255 break;
257 } else
258 #endif
260 if (ret < 0)
261 perror(func);
262 else
263 fprintf(stderr, "%s: unexpected EOF\n", func);
267 static int ssl_socket_connect(struct imap_socket *sock, int use_tls_only, int verify)
269 #ifdef NO_OPENSSL
270 fprintf(stderr, "SSL requested but SSL support not compiled in\n");
271 return -1;
272 #else
273 SSL_METHOD *meth;
274 SSL_CTX *ctx;
275 int ret;
277 SSL_library_init();
278 SSL_load_error_strings();
280 if (use_tls_only)
281 meth = TLSv1_method();
282 else
283 meth = SSLv23_method();
285 if (!meth) {
286 ssl_socket_perror("SSLv23_method");
287 return -1;
290 ctx = SSL_CTX_new(meth);
292 if (verify)
293 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
295 if (!SSL_CTX_set_default_verify_paths(ctx)) {
296 ssl_socket_perror("SSL_CTX_set_default_verify_paths");
297 return -1;
299 sock->ssl = SSL_new(ctx);
300 if (!sock->ssl) {
301 ssl_socket_perror("SSL_new");
302 return -1;
304 if (!SSL_set_rfd(sock->ssl, sock->fd[0])) {
305 ssl_socket_perror("SSL_set_rfd");
306 return -1;
308 if (!SSL_set_wfd(sock->ssl, sock->fd[1])) {
309 ssl_socket_perror("SSL_set_wfd");
310 return -1;
313 ret = SSL_connect(sock->ssl);
314 if (ret <= 0) {
315 socket_perror("SSL_connect", sock, ret);
316 return -1;
319 return 0;
320 #endif
323 static int socket_read(struct imap_socket *sock, char *buf, int len)
325 ssize_t n;
326 #ifndef NO_OPENSSL
327 if (sock->ssl)
328 n = SSL_read(sock->ssl, buf, len);
329 else
330 #endif
331 n = xread(sock->fd[0], buf, len);
332 if (n <= 0) {
333 socket_perror("read", sock, n);
334 close(sock->fd[0]);
335 close(sock->fd[1]);
336 sock->fd[0] = sock->fd[1] = -1;
338 return n;
341 static int socket_write(struct imap_socket *sock, const char *buf, int len)
343 int n;
344 #ifndef NO_OPENSSL
345 if (sock->ssl)
346 n = SSL_write(sock->ssl, buf, len);
347 else
348 #endif
349 n = write_in_full(sock->fd[1], buf, len);
350 if (n != len) {
351 socket_perror("write", sock, n);
352 close(sock->fd[0]);
353 close(sock->fd[1]);
354 sock->fd[0] = sock->fd[1] = -1;
356 return n;
359 static void socket_shutdown(struct imap_socket *sock)
361 #ifndef NO_OPENSSL
362 if (sock->ssl) {
363 SSL_shutdown(sock->ssl);
364 SSL_free(sock->ssl);
366 #endif
367 close(sock->fd[0]);
368 close(sock->fd[1]);
371 /* simple line buffering */
372 static int buffer_gets(struct imap_buffer *b, char **s)
374 int n;
375 int start = b->offset;
377 *s = b->buf + start;
379 for (;;) {
380 /* make sure we have enough data to read the \r\n sequence */
381 if (b->offset + 1 >= b->bytes) {
382 if (start) {
383 /* shift down used bytes */
384 *s = b->buf;
386 assert(start <= b->bytes);
387 n = b->bytes - start;
389 if (n)
390 memmove(b->buf, b->buf + start, n);
391 b->offset -= start;
392 b->bytes = n;
393 start = 0;
396 n = socket_read(&b->sock, b->buf + b->bytes,
397 sizeof(b->buf) - b->bytes);
399 if (n <= 0)
400 return -1;
402 b->bytes += n;
405 if (b->buf[b->offset] == '\r') {
406 assert(b->offset + 1 < b->bytes);
407 if (b->buf[b->offset + 1] == '\n') {
408 b->buf[b->offset] = 0; /* terminate the string */
409 b->offset += 2; /* next line */
410 if (Verbose)
411 puts(*s);
412 return 0;
416 b->offset++;
418 /* not reached */
421 static void imap_info(const char *msg, ...)
423 va_list va;
425 if (!Quiet) {
426 va_start(va, msg);
427 vprintf(msg, va);
428 va_end(va);
429 fflush(stdout);
433 static void imap_warn(const char *msg, ...)
435 va_list va;
437 if (Quiet < 2) {
438 va_start(va, msg);
439 vfprintf(stderr, msg, va);
440 va_end(va);
444 static char *next_arg(char **s)
446 char *ret;
448 if (!s || !*s)
449 return NULL;
450 while (isspace((unsigned char) **s))
451 (*s)++;
452 if (!**s) {
453 *s = NULL;
454 return NULL;
456 if (**s == '"') {
457 ++*s;
458 ret = *s;
459 *s = strchr(*s, '"');
460 } else {
461 ret = *s;
462 while (**s && !isspace((unsigned char) **s))
463 (*s)++;
465 if (*s) {
466 if (**s)
467 *(*s)++ = 0;
468 if (!**s)
469 *s = NULL;
471 return ret;
474 static void free_generic_messages(struct message *msgs)
476 struct message *tmsg;
478 for (; msgs; msgs = tmsg) {
479 tmsg = msgs->next;
480 free(msgs);
484 static int nfsnprintf(char *buf, int blen, const char *fmt, ...)
486 int ret;
487 va_list va;
489 va_start(va, fmt);
490 if (blen <= 0 || (unsigned)(ret = vsnprintf(buf, blen, fmt, va)) >= (unsigned)blen)
491 die("Fatal: buffer too small. Please report a bug.");
492 va_end(va);
493 return ret;
496 static struct imap_cmd *v_issue_imap_cmd(struct imap_store *ctx,
497 struct imap_cmd_cb *cb,
498 const char *fmt, va_list ap)
500 struct imap *imap = ctx->imap;
501 struct imap_cmd *cmd;
502 int n, bufl;
503 char buf[1024];
505 cmd = xmalloc(sizeof(struct imap_cmd));
506 nfvasprintf(&cmd->cmd, fmt, ap);
507 cmd->tag = ++imap->nexttag;
509 if (cb)
510 cmd->cb = *cb;
511 else
512 memset(&cmd->cb, 0, sizeof(cmd->cb));
514 while (imap->literal_pending)
515 get_cmd_result(ctx, NULL);
517 bufl = nfsnprintf(buf, sizeof(buf), cmd->cb.data ? CAP(LITERALPLUS) ?
518 "%d %s{%d+}\r\n" : "%d %s{%d}\r\n" : "%d %s\r\n",
519 cmd->tag, cmd->cmd, cmd->cb.dlen);
520 if (Verbose) {
521 if (imap->num_in_progress)
522 printf("(%d in progress) ", imap->num_in_progress);
523 if (memcmp(cmd->cmd, "LOGIN", 5))
524 printf(">>> %s", buf);
525 else
526 printf(">>> %d LOGIN <user> <pass>\n", cmd->tag);
528 if (socket_write(&imap->buf.sock, buf, bufl) != bufl) {
529 free(cmd->cmd);
530 free(cmd);
531 if (cb)
532 free(cb->data);
533 return NULL;
535 if (cmd->cb.data) {
536 if (CAP(LITERALPLUS)) {
537 n = socket_write(&imap->buf.sock, cmd->cb.data, cmd->cb.dlen);
538 free(cmd->cb.data);
539 if (n != cmd->cb.dlen ||
540 socket_write(&imap->buf.sock, "\r\n", 2) != 2) {
541 free(cmd->cmd);
542 free(cmd);
543 return NULL;
545 cmd->cb.data = NULL;
546 } else
547 imap->literal_pending = 1;
548 } else if (cmd->cb.cont)
549 imap->literal_pending = 1;
550 cmd->next = NULL;
551 *imap->in_progress_append = cmd;
552 imap->in_progress_append = &cmd->next;
553 imap->num_in_progress++;
554 return cmd;
557 static struct imap_cmd *issue_imap_cmd(struct imap_store *ctx,
558 struct imap_cmd_cb *cb,
559 const char *fmt, ...)
561 struct imap_cmd *ret;
562 va_list ap;
564 va_start(ap, fmt);
565 ret = v_issue_imap_cmd(ctx, cb, fmt, ap);
566 va_end(ap);
567 return ret;
570 static int imap_exec(struct imap_store *ctx, struct imap_cmd_cb *cb,
571 const char *fmt, ...)
573 va_list ap;
574 struct imap_cmd *cmdp;
576 va_start(ap, fmt);
577 cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
578 va_end(ap);
579 if (!cmdp)
580 return RESP_BAD;
582 return get_cmd_result(ctx, cmdp);
585 static int imap_exec_m(struct imap_store *ctx, struct imap_cmd_cb *cb,
586 const char *fmt, ...)
588 va_list ap;
589 struct imap_cmd *cmdp;
591 va_start(ap, fmt);
592 cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
593 va_end(ap);
594 if (!cmdp)
595 return DRV_STORE_BAD;
597 switch (get_cmd_result(ctx, cmdp)) {
598 case RESP_BAD: return DRV_STORE_BAD;
599 case RESP_NO: return DRV_MSG_BAD;
600 default: return DRV_OK;
604 static int is_atom(struct imap_list *list)
606 return list && list->val && list->val != NIL && list->val != LIST;
609 static int is_list(struct imap_list *list)
611 return list && list->val == LIST;
614 static void free_list(struct imap_list *list)
616 struct imap_list *tmp;
618 for (; list; list = tmp) {
619 tmp = list->next;
620 if (is_list(list))
621 free_list(list->child);
622 else if (is_atom(list))
623 free(list->val);
624 free(list);
628 static int parse_imap_list_l(struct imap *imap, char **sp, struct imap_list **curp, int level)
630 struct imap_list *cur;
631 char *s = *sp, *p;
632 int n, bytes;
634 for (;;) {
635 while (isspace((unsigned char)*s))
636 s++;
637 if (level && *s == ')') {
638 s++;
639 break;
641 *curp = cur = xmalloc(sizeof(*cur));
642 curp = &cur->next;
643 cur->val = NULL; /* for clean bail */
644 if (*s == '(') {
645 /* sublist */
646 s++;
647 cur->val = LIST;
648 if (parse_imap_list_l(imap, &s, &cur->child, level + 1))
649 goto bail;
650 } else if (imap && *s == '{') {
651 /* literal */
652 bytes = cur->len = strtol(s + 1, &s, 10);
653 if (*s != '}')
654 goto bail;
656 s = cur->val = xmalloc(cur->len);
658 /* dump whats left over in the input buffer */
659 n = imap->buf.bytes - imap->buf.offset;
661 if (n > bytes)
662 /* the entire message fit in the buffer */
663 n = bytes;
665 memcpy(s, imap->buf.buf + imap->buf.offset, n);
666 s += n;
667 bytes -= n;
669 /* mark that we used part of the buffer */
670 imap->buf.offset += n;
672 /* now read the rest of the message */
673 while (bytes > 0) {
674 if ((n = socket_read(&imap->buf.sock, s, bytes)) <= 0)
675 goto bail;
676 s += n;
677 bytes -= n;
680 if (buffer_gets(&imap->buf, &s))
681 goto bail;
682 } else if (*s == '"') {
683 /* quoted string */
684 s++;
685 p = s;
686 for (; *s != '"'; s++)
687 if (!*s)
688 goto bail;
689 cur->len = s - p;
690 s++;
691 cur->val = xmemdupz(p, cur->len);
692 } else {
693 /* atom */
694 p = s;
695 for (; *s && !isspace((unsigned char)*s); s++)
696 if (level && *s == ')')
697 break;
698 cur->len = s - p;
699 if (cur->len == 3 && !memcmp("NIL", p, 3))
700 cur->val = NIL;
701 else
702 cur->val = xmemdupz(p, cur->len);
705 if (!level)
706 break;
707 if (!*s)
708 goto bail;
710 *sp = s;
711 *curp = NULL;
712 return 0;
714 bail:
715 *curp = NULL;
716 return -1;
719 static struct imap_list *parse_imap_list(struct imap *imap, char **sp)
721 struct imap_list *head;
723 if (!parse_imap_list_l(imap, sp, &head, 0))
724 return head;
725 free_list(head);
726 return NULL;
729 static struct imap_list *parse_list(char **sp)
731 return parse_imap_list(NULL, sp);
734 static void parse_capability(struct imap *imap, char *cmd)
736 char *arg;
737 unsigned i;
739 imap->caps = 0x80000000;
740 while ((arg = next_arg(&cmd)))
741 for (i = 0; i < ARRAY_SIZE(cap_list); i++)
742 if (!strcmp(cap_list[i], arg))
743 imap->caps |= 1 << i;
744 imap->rcaps = imap->caps;
747 static int parse_response_code(struct imap_store *ctx, struct imap_cmd_cb *cb,
748 char *s)
750 struct imap *imap = ctx->imap;
751 char *arg, *p;
753 if (*s != '[')
754 return RESP_OK; /* no response code */
755 s++;
756 if (!(p = strchr(s, ']'))) {
757 fprintf(stderr, "IMAP error: malformed response code\n");
758 return RESP_BAD;
760 *p++ = 0;
761 arg = next_arg(&s);
762 if (!strcmp("UIDVALIDITY", arg)) {
763 if (!(arg = next_arg(&s)) || !(ctx->gen.uidvalidity = atoi(arg))) {
764 fprintf(stderr, "IMAP error: malformed UIDVALIDITY status\n");
765 return RESP_BAD;
767 } else if (!strcmp("UIDNEXT", arg)) {
768 if (!(arg = next_arg(&s)) || !(imap->uidnext = atoi(arg))) {
769 fprintf(stderr, "IMAP error: malformed NEXTUID status\n");
770 return RESP_BAD;
772 } else if (!strcmp("CAPABILITY", arg)) {
773 parse_capability(imap, s);
774 } else if (!strcmp("ALERT", arg)) {
775 /* RFC2060 says that these messages MUST be displayed
776 * to the user
778 for (; isspace((unsigned char)*p); p++);
779 fprintf(stderr, "*** IMAP ALERT *** %s\n", p);
780 } else if (cb && cb->ctx && !strcmp("APPENDUID", arg)) {
781 if (!(arg = next_arg(&s)) || !(ctx->gen.uidvalidity = atoi(arg)) ||
782 !(arg = next_arg(&s)) || !(*(int *)cb->ctx = atoi(arg))) {
783 fprintf(stderr, "IMAP error: malformed APPENDUID status\n");
784 return RESP_BAD;
787 return RESP_OK;
790 static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd)
792 struct imap *imap = ctx->imap;
793 struct imap_cmd *cmdp, **pcmdp, *ncmdp;
794 char *cmd, *arg, *arg1, *p;
795 int n, resp, resp2, tag;
797 for (;;) {
798 if (buffer_gets(&imap->buf, &cmd))
799 return RESP_BAD;
801 arg = next_arg(&cmd);
802 if (*arg == '*') {
803 arg = next_arg(&cmd);
804 if (!arg) {
805 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
806 return RESP_BAD;
809 if (!strcmp("NAMESPACE", arg)) {
810 imap->ns_personal = parse_list(&cmd);
811 imap->ns_other = parse_list(&cmd);
812 imap->ns_shared = parse_list(&cmd);
813 } else if (!strcmp("OK", arg) || !strcmp("BAD", arg) ||
814 !strcmp("NO", arg) || !strcmp("BYE", arg)) {
815 if ((resp = parse_response_code(ctx, NULL, cmd)) != RESP_OK)
816 return resp;
817 } else if (!strcmp("CAPABILITY", arg))
818 parse_capability(imap, cmd);
819 else if ((arg1 = next_arg(&cmd))) {
820 if (!strcmp("EXISTS", arg1))
821 ctx->gen.count = atoi(arg);
822 else if (!strcmp("RECENT", arg1))
823 ctx->gen.recent = atoi(arg);
824 } else {
825 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
826 return RESP_BAD;
828 } else if (!imap->in_progress) {
829 fprintf(stderr, "IMAP error: unexpected reply: %s %s\n", arg, cmd ? cmd : "");
830 return RESP_BAD;
831 } else if (*arg == '+') {
832 /* This can happen only with the last command underway, as
833 it enforces a round-trip. */
834 cmdp = (struct imap_cmd *)((char *)imap->in_progress_append -
835 offsetof(struct imap_cmd, next));
836 if (cmdp->cb.data) {
837 n = socket_write(&imap->buf.sock, cmdp->cb.data, cmdp->cb.dlen);
838 free(cmdp->cb.data);
839 cmdp->cb.data = NULL;
840 if (n != (int)cmdp->cb.dlen)
841 return RESP_BAD;
842 } else if (cmdp->cb.cont) {
843 if (cmdp->cb.cont(ctx, cmdp, cmd))
844 return RESP_BAD;
845 } else {
846 fprintf(stderr, "IMAP error: unexpected command continuation request\n");
847 return RESP_BAD;
849 if (socket_write(&imap->buf.sock, "\r\n", 2) != 2)
850 return RESP_BAD;
851 if (!cmdp->cb.cont)
852 imap->literal_pending = 0;
853 if (!tcmd)
854 return DRV_OK;
855 } else {
856 tag = atoi(arg);
857 for (pcmdp = &imap->in_progress; (cmdp = *pcmdp); pcmdp = &cmdp->next)
858 if (cmdp->tag == tag)
859 goto gottag;
860 fprintf(stderr, "IMAP error: unexpected tag %s\n", arg);
861 return RESP_BAD;
862 gottag:
863 if (!(*pcmdp = cmdp->next))
864 imap->in_progress_append = pcmdp;
865 imap->num_in_progress--;
866 if (cmdp->cb.cont || cmdp->cb.data)
867 imap->literal_pending = 0;
868 arg = next_arg(&cmd);
869 if (!strcmp("OK", arg))
870 resp = DRV_OK;
871 else {
872 if (!strcmp("NO", arg)) {
873 if (cmdp->cb.create && cmd && (cmdp->cb.trycreate || !memcmp(cmd, "[TRYCREATE]", 11))) { /* SELECT, APPEND or UID COPY */
874 p = strchr(cmdp->cmd, '"');
875 if (!issue_imap_cmd(ctx, NULL, "CREATE \"%.*s\"", strchr(p + 1, '"') - p + 1, p)) {
876 resp = RESP_BAD;
877 goto normal;
879 /* not waiting here violates the spec, but a server that does not
880 grok this nonetheless violates it too. */
881 cmdp->cb.create = 0;
882 if (!(ncmdp = issue_imap_cmd(ctx, &cmdp->cb, "%s", cmdp->cmd))) {
883 resp = RESP_BAD;
884 goto normal;
886 free(cmdp->cmd);
887 free(cmdp);
888 if (!tcmd)
889 return 0; /* ignored */
890 if (cmdp == tcmd)
891 tcmd = ncmdp;
892 continue;
894 resp = RESP_NO;
895 } else /*if (!strcmp("BAD", arg))*/
896 resp = RESP_BAD;
897 fprintf(stderr, "IMAP command '%s' returned response (%s) - %s\n",
898 memcmp(cmdp->cmd, "LOGIN", 5) ?
899 cmdp->cmd : "LOGIN <user> <pass>",
900 arg, cmd ? cmd : "");
902 if ((resp2 = parse_response_code(ctx, &cmdp->cb, cmd)) > resp)
903 resp = resp2;
904 normal:
905 if (cmdp->cb.done)
906 cmdp->cb.done(ctx, cmdp, resp);
907 free(cmdp->cb.data);
908 free(cmdp->cmd);
909 free(cmdp);
910 if (!tcmd || tcmd == cmdp)
911 return resp;
914 /* not reached */
917 static void imap_close_server(struct imap_store *ictx)
919 struct imap *imap = ictx->imap;
921 if (imap->buf.sock.fd[0] != -1) {
922 imap_exec(ictx, NULL, "LOGOUT");
923 socket_shutdown(&imap->buf.sock);
925 free_list(imap->ns_personal);
926 free_list(imap->ns_other);
927 free_list(imap->ns_shared);
928 free(imap);
931 static void imap_close_store(struct store *ctx)
933 imap_close_server((struct imap_store *)ctx);
934 free_generic_messages(ctx->msgs);
935 free(ctx);
938 static struct store *imap_open_store(struct imap_server_conf *srvc)
940 struct imap_store *ctx;
941 struct imap *imap;
942 char *arg, *rsp;
943 int s = -1, a[2], preauth;
944 pid_t pid;
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 imap_info("Starting tunnel '%s'... ", srvc->tunnel);
957 if (socketpair(PF_UNIX, SOCK_STREAM, 0, a)) {
958 perror("socketpair");
959 exit(1);
962 pid = fork();
963 if (pid < 0)
964 _exit(127);
965 if (!pid) {
966 if (dup2(a[0], 0) == -1 || dup2(a[0], 1) == -1)
967 _exit(127);
968 close(a[0]);
969 close(a[1]);
970 execl("/bin/sh", "sh", "-c", srvc->tunnel, NULL);
971 _exit(127);
974 close(a[0]);
976 imap->buf.sock.fd[0] = a[1];
977 imap->buf.sock.fd[1] = dup(a[1]);
979 imap_info("ok\n");
980 } else {
981 #ifndef NO_IPV6
982 struct addrinfo hints, *ai0, *ai;
983 int gai;
984 char portstr[6];
986 snprintf(portstr, sizeof(portstr), "%hu", srvc->port);
988 memset(&hints, 0, sizeof(hints));
989 hints.ai_socktype = SOCK_STREAM;
990 hints.ai_protocol = IPPROTO_TCP;
992 imap_info("Resolving %s... ", srvc->host);
993 gai = getaddrinfo(srvc->host, portstr, &hints, &ai);
994 if (gai) {
995 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai));
996 goto bail;
998 imap_info("ok\n");
1000 for (ai0 = ai; ai; ai = ai->ai_next) {
1001 char addr[NI_MAXHOST];
1003 s = socket(ai->ai_family, ai->ai_socktype,
1004 ai->ai_protocol);
1005 if (s < 0)
1006 continue;
1008 getnameinfo(ai->ai_addr, ai->ai_addrlen, addr,
1009 sizeof(addr), NULL, 0, NI_NUMERICHOST);
1010 imap_info("Connecting to [%s]:%s... ", addr, portstr);
1012 if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0) {
1013 close(s);
1014 s = -1;
1015 perror("connect");
1016 continue;
1019 break;
1021 freeaddrinfo(ai0);
1022 #else /* NO_IPV6 */
1023 struct hostent *he;
1024 struct sockaddr_in addr;
1026 memset(&addr, 0, sizeof(addr));
1027 addr.sin_port = htons(srvc->port);
1028 addr.sin_family = AF_INET;
1030 imap_info("Resolving %s... ", srvc->host);
1031 he = gethostbyname(srvc->host);
1032 if (!he) {
1033 perror("gethostbyname");
1034 goto bail;
1036 imap_info("ok\n");
1038 addr.sin_addr.s_addr = *((int *) he->h_addr_list[0]);
1040 s = socket(PF_INET, SOCK_STREAM, 0);
1042 imap_info("Connecting to %s:%hu... ", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
1043 if (connect(s, (struct sockaddr *)&addr, sizeof(addr))) {
1044 close(s);
1045 s = -1;
1046 perror("connect");
1048 #endif
1049 if (s < 0) {
1050 fputs("Error: unable to connect to server.\n", stderr);
1051 goto bail;
1054 imap->buf.sock.fd[0] = s;
1055 imap->buf.sock.fd[1] = dup(s);
1057 if (srvc->use_ssl &&
1058 ssl_socket_connect(&imap->buf.sock, 0, srvc->ssl_verify)) {
1059 close(s);
1060 goto bail;
1062 imap_info("ok\n");
1065 /* read the greeting string */
1066 if (buffer_gets(&imap->buf, &rsp)) {
1067 fprintf(stderr, "IMAP error: no greeting response\n");
1068 goto bail;
1070 arg = next_arg(&rsp);
1071 if (!arg || *arg != '*' || (arg = next_arg(&rsp)) == NULL) {
1072 fprintf(stderr, "IMAP error: invalid greeting response\n");
1073 goto bail;
1075 preauth = 0;
1076 if (!strcmp("PREAUTH", arg))
1077 preauth = 1;
1078 else if (strcmp("OK", arg) != 0) {
1079 fprintf(stderr, "IMAP error: unknown greeting response\n");
1080 goto bail;
1082 parse_response_code(ctx, NULL, rsp);
1083 if (!imap->caps && imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1084 goto bail;
1086 if (!preauth) {
1087 #ifndef NO_OPENSSL
1088 if (!srvc->use_ssl && CAP(STARTTLS)) {
1089 if (imap_exec(ctx, 0, "STARTTLS") != RESP_OK)
1090 goto bail;
1091 if (ssl_socket_connect(&imap->buf.sock, 1,
1092 srvc->ssl_verify))
1093 goto bail;
1094 /* capabilities may have changed, so get the new capabilities */
1095 if (imap_exec(ctx, 0, "CAPABILITY") != RESP_OK)
1096 goto bail;
1098 #endif
1099 imap_info("Logging in...\n");
1100 if (!srvc->user) {
1101 fprintf(stderr, "Skipping server %s, no user\n", srvc->host);
1102 goto bail;
1104 if (!srvc->pass) {
1105 char prompt[80];
1106 sprintf(prompt, "Password (%s@%s): ", srvc->user, srvc->host);
1107 arg = getpass(prompt);
1108 if (!arg) {
1109 perror("getpass");
1110 exit(1);
1112 if (!*arg) {
1113 fprintf(stderr, "Skipping account %s@%s, no password\n", srvc->user, srvc->host);
1114 goto bail;
1117 * getpass() returns a pointer to a static buffer. make a copy
1118 * for long term storage.
1120 srvc->pass = xstrdup(arg);
1122 if (CAP(NOLOGIN)) {
1123 fprintf(stderr, "Skipping account %s@%s, server forbids LOGIN\n", srvc->user, srvc->host);
1124 goto bail;
1126 if (!imap->buf.sock.ssl)
1127 imap_warn("*** IMAP Warning *** Password is being "
1128 "sent in the clear\n");
1129 if (imap_exec(ctx, NULL, "LOGIN \"%s\" \"%s\"", srvc->user, srvc->pass) != RESP_OK) {
1130 fprintf(stderr, "IMAP error: LOGIN failed\n");
1131 goto bail;
1133 } /* !preauth */
1135 ctx->prefix = "";
1136 ctx->trashnc = 1;
1137 return (struct store *)ctx;
1139 bail:
1140 imap_close_store(&ctx->gen);
1141 return NULL;
1144 static int imap_make_flags(int flags, char *buf)
1146 const char *s;
1147 unsigned i, d;
1149 for (i = d = 0; i < ARRAY_SIZE(Flags); i++)
1150 if (flags & (1 << i)) {
1151 buf[d++] = ' ';
1152 buf[d++] = '\\';
1153 for (s = Flags[i]; *s; s++)
1154 buf[d++] = *s;
1156 buf[0] = '(';
1157 buf[d++] = ')';
1158 return d;
1161 static int imap_store_msg(struct store *gctx, struct msg_data *data)
1163 struct imap_store *ctx = (struct imap_store *)gctx;
1164 struct imap *imap = ctx->imap;
1165 struct imap_cmd_cb cb;
1166 const char *prefix, *box;
1167 int ret, d;
1168 char flagstr[128];
1170 memset(&cb, 0, sizeof(cb));
1172 cb.dlen = data->len;
1173 cb.data = xmalloc(cb.dlen);
1174 memcpy(cb.data, data->data, data->len);
1176 d = 0;
1177 if (data->flags) {
1178 d = imap_make_flags(data->flags, flagstr);
1179 flagstr[d++] = ' ';
1181 flagstr[d] = 0;
1183 box = gctx->name;
1184 prefix = !strcmp(box, "INBOX") ? "" : ctx->prefix;
1185 cb.create = 0;
1186 ret = imap_exec_m(ctx, &cb, "APPEND \"%s%s\" %s", prefix, box, flagstr);
1187 imap->caps = imap->rcaps;
1188 if (ret != DRV_OK)
1189 return ret;
1190 gctx->count++;
1192 return DRV_OK;
1195 static void encode_html_chars(struct strbuf *p)
1197 int i;
1198 for (i = 0; i < p->len; i++) {
1199 if (p->buf[i] == '&')
1200 strbuf_splice(p, i, 1, "&amp;", 5);
1201 if (p->buf[i] == '<')
1202 strbuf_splice(p, i, 1, "&lt;", 4);
1203 if (p->buf[i] == '>')
1204 strbuf_splice(p, i, 1, "&gt;", 4);
1205 if (p->buf[i] == '"')
1206 strbuf_splice(p, i, 1, "&quot;", 6);
1209 static void wrap_in_html(struct msg_data *msg)
1211 struct strbuf buf = STRBUF_INIT;
1212 struct strbuf **lines;
1213 struct strbuf **p;
1214 static char *content_type = "Content-Type: text/html;\n";
1215 static char *pre_open = "<pre>\n";
1216 static char *pre_close = "</pre>\n";
1217 int added_header = 0;
1219 strbuf_attach(&buf, msg->data, msg->len, msg->len);
1220 lines = strbuf_split(&buf, '\n');
1221 strbuf_release(&buf);
1222 for (p = lines; *p; p++) {
1223 if (! added_header) {
1224 if ((*p)->len == 1 && *((*p)->buf) == '\n') {
1225 strbuf_addstr(&buf, content_type);
1226 strbuf_addbuf(&buf, *p);
1227 strbuf_addstr(&buf, pre_open);
1228 added_header = 1;
1229 continue;
1232 else
1233 encode_html_chars(*p);
1234 strbuf_addbuf(&buf, *p);
1236 strbuf_addstr(&buf, pre_close);
1237 strbuf_list_free(lines);
1238 msg->len = buf.len;
1239 msg->data = strbuf_detach(&buf, NULL);
1242 #define CHUNKSIZE 0x1000
1244 static int read_message(FILE *f, struct msg_data *msg)
1246 struct strbuf buf = STRBUF_INIT;
1248 memset(msg, 0, sizeof(*msg));
1250 do {
1251 if (strbuf_fread(&buf, CHUNKSIZE, f) <= 0)
1252 break;
1253 } while (!feof(f));
1255 msg->len = buf.len;
1256 msg->data = strbuf_detach(&buf, NULL);
1257 return msg->len;
1260 static int count_messages(struct msg_data *msg)
1262 int count = 0;
1263 char *p = msg->data;
1265 while (1) {
1266 if (!prefixcmp(p, "From ")) {
1267 count++;
1268 p += 5;
1270 p = strstr(p+5, "\nFrom ");
1271 if (!p)
1272 break;
1273 p++;
1275 return count;
1278 static int split_msg(struct msg_data *all_msgs, struct msg_data *msg, int *ofs)
1280 char *p, *data;
1282 memset(msg, 0, sizeof *msg);
1283 if (*ofs >= all_msgs->len)
1284 return 0;
1286 data = &all_msgs->data[*ofs];
1287 msg->len = all_msgs->len - *ofs;
1289 if (msg->len < 5 || prefixcmp(data, "From "))
1290 return 0;
1292 p = strchr(data, '\n');
1293 if (p) {
1294 p = &p[1];
1295 msg->len -= p-data;
1296 *ofs += p-data;
1297 data = p;
1300 p = strstr(data, "\nFrom ");
1301 if (p)
1302 msg->len = &p[1] - data;
1304 msg->data = xmemdupz(data, msg->len);
1305 *ofs += msg->len;
1306 return 1;
1309 static struct imap_server_conf server = {
1310 NULL, /* name */
1311 NULL, /* tunnel */
1312 NULL, /* host */
1313 0, /* port */
1314 NULL, /* user */
1315 NULL, /* pass */
1316 0, /* use_ssl */
1317 1, /* ssl_verify */
1318 0, /* use_html */
1321 static char *imap_folder;
1323 static int git_imap_config(const char *key, const char *val, void *cb)
1325 char imap_key[] = "imap.";
1327 if (strncmp(key, imap_key, sizeof imap_key - 1))
1328 return 0;
1330 if (!val)
1331 return config_error_nonbool(key);
1333 key += sizeof imap_key - 1;
1335 if (!strcmp("folder", key)) {
1336 imap_folder = xstrdup(val);
1337 } else if (!strcmp("host", key)) {
1338 if (!prefixcmp(val, "imap:"))
1339 val += 5;
1340 else if (!prefixcmp(val, "imaps:")) {
1341 val += 6;
1342 server.use_ssl = 1;
1344 if (!prefixcmp(val, "//"))
1345 val += 2;
1346 server.host = xstrdup(val);
1347 } else if (!strcmp("user", key))
1348 server.user = xstrdup(val);
1349 else if (!strcmp("pass", key))
1350 server.pass = xstrdup(val);
1351 else if (!strcmp("port", key))
1352 server.port = git_config_int(key, val);
1353 else if (!strcmp("tunnel", key))
1354 server.tunnel = xstrdup(val);
1355 else if (!strcmp("sslverify", key))
1356 server.ssl_verify = git_config_bool(key, val);
1357 else if (!strcmp("preformattedHTML", key))
1358 server.use_html = git_config_bool(key, val);
1359 return 0;
1362 int main(int argc, char **argv)
1364 struct msg_data all_msgs, msg;
1365 struct store *ctx = NULL;
1366 int ofs = 0;
1367 int r;
1368 int total, n = 0;
1369 int nongit_ok;
1371 git_extract_argv0_path(argv[0]);
1373 setup_git_directory_gently(&nongit_ok);
1374 git_config(git_imap_config, NULL);
1376 if (!server.port)
1377 server.port = server.use_ssl ? 993 : 143;
1379 if (!imap_folder) {
1380 fprintf(stderr, "no imap store specified\n");
1381 return 1;
1383 if (!server.host) {
1384 if (!server.tunnel) {
1385 fprintf(stderr, "no imap host specified\n");
1386 return 1;
1388 server.host = "tunnel";
1391 /* read the messages */
1392 if (!read_message(stdin, &all_msgs)) {
1393 fprintf(stderr, "nothing to send\n");
1394 return 1;
1397 total = count_messages(&all_msgs);
1398 if (!total) {
1399 fprintf(stderr, "no messages to send\n");
1400 return 1;
1403 /* write it to the imap server */
1404 ctx = imap_open_store(&server);
1405 if (!ctx) {
1406 fprintf(stderr, "failed to open store\n");
1407 return 1;
1410 fprintf(stderr, "sending %d message%s\n", total, (total != 1) ? "s" : "");
1411 ctx->name = imap_folder;
1412 while (1) {
1413 unsigned percent = n * 100 / total;
1414 fprintf(stderr, "%4u%% (%d/%d) done\r", percent, n, total);
1415 if (!split_msg(&all_msgs, &msg, &ofs))
1416 break;
1417 if (server.use_html)
1418 wrap_in_html(&msg);
1419 r = imap_store_msg(ctx, &msg);
1420 if (r != DRV_OK)
1421 break;
1422 n++;
1424 fprintf(stderr, "\n");
1426 imap_close_store(ctx);
1428 return 0;