reset: improve worktree safety valves
[git/kirr.git] / imap-send.c
blobf805c6ed813bbc6130bcd2d9f89bdb44ad9625e1
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 static void arc4_init(void);
127 static unsigned char arc4_getbyte(void);
129 struct imap_server_conf {
130 char *name;
131 char *tunnel;
132 char *host;
133 int port;
134 char *user;
135 char *pass;
136 int use_ssl;
137 int ssl_verify;
138 int use_html;
141 struct imap_store_conf {
142 struct store_conf gen;
143 struct imap_server_conf *server;
144 unsigned use_namespace:1;
147 #define NIL (void *)0x1
148 #define LIST (void *)0x2
150 struct imap_list {
151 struct imap_list *next, *child;
152 char *val;
153 int len;
156 struct imap_socket {
157 int fd;
158 SSL *ssl;
161 struct imap_buffer {
162 struct imap_socket sock;
163 int bytes;
164 int offset;
165 char buf[1024];
168 struct imap_cmd;
170 struct imap {
171 int uidnext; /* from SELECT responses */
172 struct imap_list *ns_personal, *ns_other, *ns_shared; /* NAMESPACE info */
173 unsigned caps, rcaps; /* CAPABILITY results */
174 /* command queue */
175 int nexttag, num_in_progress, literal_pending;
176 struct imap_cmd *in_progress, **in_progress_append;
177 struct imap_buffer buf; /* this is BIG, so put it last */
180 struct imap_store {
181 struct store gen;
182 int uidvalidity;
183 struct imap *imap;
184 const char *prefix;
185 unsigned /*currentnc:1,*/ trashnc:1;
188 struct imap_cmd_cb {
189 int (*cont)(struct imap_store *ctx, struct imap_cmd *cmd, const char *prompt);
190 void (*done)(struct imap_store *ctx, struct imap_cmd *cmd, int response);
191 void *ctx;
192 char *data;
193 int dlen;
194 int uid;
195 unsigned create:1, trycreate:1;
198 struct imap_cmd {
199 struct imap_cmd *next;
200 struct imap_cmd_cb cb;
201 char *cmd;
202 int tag;
205 #define CAP(cap) (imap->caps & (1 << (cap)))
207 enum CAPABILITY {
208 NOLOGIN = 0,
209 UIDPLUS,
210 LITERALPLUS,
211 NAMESPACE,
212 STARTTLS,
215 static const char *cap_list[] = {
216 "LOGINDISABLED",
217 "UIDPLUS",
218 "LITERAL+",
219 "NAMESPACE",
220 "STARTTLS",
223 #define RESP_OK 0
224 #define RESP_NO 1
225 #define RESP_BAD 2
227 static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd);
230 static const char *Flags[] = {
231 "Draft",
232 "Flagged",
233 "Answered",
234 "Seen",
235 "Deleted",
238 #ifndef NO_OPENSSL
239 static void ssl_socket_perror(const char *func)
241 fprintf(stderr, "%s: %s\n", func, ERR_error_string(ERR_get_error(), NULL));
243 #endif
245 static void socket_perror(const char *func, struct imap_socket *sock, int ret)
247 #ifndef NO_OPENSSL
248 if (sock->ssl) {
249 int sslerr = SSL_get_error(sock->ssl, ret);
250 switch (sslerr) {
251 case SSL_ERROR_NONE:
252 break;
253 case SSL_ERROR_SYSCALL:
254 perror("SSL_connect");
255 break;
256 default:
257 ssl_socket_perror("SSL_connect");
258 break;
260 } else
261 #endif
263 if (ret < 0)
264 perror(func);
265 else
266 fprintf(stderr, "%s: unexpected EOF\n", func);
270 static int ssl_socket_connect(struct imap_socket *sock, int use_tls_only, int verify)
272 #ifdef NO_OPENSSL
273 fprintf(stderr, "SSL requested but SSL support not compiled in\n");
274 return -1;
275 #else
276 #if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
277 const SSL_METHOD *meth;
278 #else
279 SSL_METHOD *meth;
280 #endif
281 SSL_CTX *ctx;
282 int ret;
284 SSL_library_init();
285 SSL_load_error_strings();
287 if (use_tls_only)
288 meth = TLSv1_method();
289 else
290 meth = SSLv23_method();
292 if (!meth) {
293 ssl_socket_perror("SSLv23_method");
294 return -1;
297 ctx = SSL_CTX_new(meth);
299 if (verify)
300 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
302 if (!SSL_CTX_set_default_verify_paths(ctx)) {
303 ssl_socket_perror("SSL_CTX_set_default_verify_paths");
304 return -1;
306 sock->ssl = SSL_new(ctx);
307 if (!sock->ssl) {
308 ssl_socket_perror("SSL_new");
309 return -1;
311 if (!SSL_set_fd(sock->ssl, sock->fd)) {
312 ssl_socket_perror("SSL_set_fd");
313 return -1;
316 ret = SSL_connect(sock->ssl);
317 if (ret <= 0) {
318 socket_perror("SSL_connect", sock, ret);
319 return -1;
322 return 0;
323 #endif
326 static int socket_read(struct imap_socket *sock, char *buf, int len)
328 ssize_t n;
329 #ifndef NO_OPENSSL
330 if (sock->ssl)
331 n = SSL_read(sock->ssl, buf, len);
332 else
333 #endif
334 n = xread(sock->fd, buf, len);
335 if (n <= 0) {
336 socket_perror("read", sock, n);
337 close(sock->fd);
338 sock->fd = -1;
340 return n;
343 static int socket_write(struct imap_socket *sock, const char *buf, int len)
345 int n;
346 #ifndef NO_OPENSSL
347 if (sock->ssl)
348 n = SSL_write(sock->ssl, buf, len);
349 else
350 #endif
351 n = write_in_full(sock->fd, buf, len);
352 if (n != len) {
353 socket_perror("write", sock, n);
354 close(sock->fd);
355 sock->fd = -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);
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 {
497 unsigned char i, j, s[256];
498 } rs;
500 static void arc4_init(void)
502 int i, fd;
503 unsigned char j, si, dat[128];
505 if ((fd = open("/dev/urandom", O_RDONLY)) < 0 && (fd = open("/dev/random", O_RDONLY)) < 0) {
506 fprintf(stderr, "Fatal: no random number source available.\n");
507 exit(3);
509 if (read_in_full(fd, dat, 128) != 128) {
510 fprintf(stderr, "Fatal: cannot read random number source.\n");
511 exit(3);
513 close(fd);
515 for (i = 0; i < 256; i++)
516 rs.s[i] = i;
517 for (i = j = 0; i < 256; i++) {
518 si = rs.s[i];
519 j += si + dat[i & 127];
520 rs.s[i] = rs.s[j];
521 rs.s[j] = si;
523 rs.i = rs.j = 0;
525 for (i = 0; i < 256; i++)
526 arc4_getbyte();
529 static unsigned char arc4_getbyte(void)
531 unsigned char si, sj;
533 rs.i++;
534 si = rs.s[rs.i];
535 rs.j += si;
536 sj = rs.s[rs.j];
537 rs.s[rs.i] = sj;
538 rs.s[rs.j] = si;
539 return rs.s[(si + sj) & 0xff];
542 static struct imap_cmd *v_issue_imap_cmd(struct imap_store *ctx,
543 struct imap_cmd_cb *cb,
544 const char *fmt, va_list ap)
546 struct imap *imap = ctx->imap;
547 struct imap_cmd *cmd;
548 int n, bufl;
549 char buf[1024];
551 cmd = xmalloc(sizeof(struct imap_cmd));
552 nfvasprintf(&cmd->cmd, fmt, ap);
553 cmd->tag = ++imap->nexttag;
555 if (cb)
556 cmd->cb = *cb;
557 else
558 memset(&cmd->cb, 0, sizeof(cmd->cb));
560 while (imap->literal_pending)
561 get_cmd_result(ctx, NULL);
563 bufl = nfsnprintf(buf, sizeof(buf), cmd->cb.data ? CAP(LITERALPLUS) ?
564 "%d %s{%d+}\r\n" : "%d %s{%d}\r\n" : "%d %s\r\n",
565 cmd->tag, cmd->cmd, cmd->cb.dlen);
566 if (Verbose) {
567 if (imap->num_in_progress)
568 printf("(%d in progress) ", imap->num_in_progress);
569 if (memcmp(cmd->cmd, "LOGIN", 5))
570 printf(">>> %s", buf);
571 else
572 printf(">>> %d LOGIN <user> <pass>\n", cmd->tag);
574 if (socket_write(&imap->buf.sock, buf, bufl) != bufl) {
575 free(cmd->cmd);
576 free(cmd);
577 if (cb)
578 free(cb->data);
579 return NULL;
581 if (cmd->cb.data) {
582 if (CAP(LITERALPLUS)) {
583 n = socket_write(&imap->buf.sock, cmd->cb.data, cmd->cb.dlen);
584 free(cmd->cb.data);
585 if (n != cmd->cb.dlen ||
586 socket_write(&imap->buf.sock, "\r\n", 2) != 2) {
587 free(cmd->cmd);
588 free(cmd);
589 return NULL;
591 cmd->cb.data = NULL;
592 } else
593 imap->literal_pending = 1;
594 } else if (cmd->cb.cont)
595 imap->literal_pending = 1;
596 cmd->next = NULL;
597 *imap->in_progress_append = cmd;
598 imap->in_progress_append = &cmd->next;
599 imap->num_in_progress++;
600 return cmd;
603 static struct imap_cmd *issue_imap_cmd(struct imap_store *ctx,
604 struct imap_cmd_cb *cb,
605 const char *fmt, ...)
607 struct imap_cmd *ret;
608 va_list ap;
610 va_start(ap, fmt);
611 ret = v_issue_imap_cmd(ctx, cb, fmt, ap);
612 va_end(ap);
613 return ret;
616 static int imap_exec(struct imap_store *ctx, struct imap_cmd_cb *cb,
617 const char *fmt, ...)
619 va_list ap;
620 struct imap_cmd *cmdp;
622 va_start(ap, fmt);
623 cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
624 va_end(ap);
625 if (!cmdp)
626 return RESP_BAD;
628 return get_cmd_result(ctx, cmdp);
631 static int imap_exec_m(struct imap_store *ctx, struct imap_cmd_cb *cb,
632 const char *fmt, ...)
634 va_list ap;
635 struct imap_cmd *cmdp;
637 va_start(ap, fmt);
638 cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
639 va_end(ap);
640 if (!cmdp)
641 return DRV_STORE_BAD;
643 switch (get_cmd_result(ctx, cmdp)) {
644 case RESP_BAD: return DRV_STORE_BAD;
645 case RESP_NO: return DRV_MSG_BAD;
646 default: return DRV_OK;
650 static int is_atom(struct imap_list *list)
652 return list && list->val && list->val != NIL && list->val != LIST;
655 static int is_list(struct imap_list *list)
657 return list && list->val == LIST;
660 static void free_list(struct imap_list *list)
662 struct imap_list *tmp;
664 for (; list; list = tmp) {
665 tmp = list->next;
666 if (is_list(list))
667 free_list(list->child);
668 else if (is_atom(list))
669 free(list->val);
670 free(list);
674 static int parse_imap_list_l(struct imap *imap, char **sp, struct imap_list **curp, int level)
676 struct imap_list *cur;
677 char *s = *sp, *p;
678 int n, bytes;
680 for (;;) {
681 while (isspace((unsigned char)*s))
682 s++;
683 if (level && *s == ')') {
684 s++;
685 break;
687 *curp = cur = xmalloc(sizeof(*cur));
688 curp = &cur->next;
689 cur->val = NULL; /* for clean bail */
690 if (*s == '(') {
691 /* sublist */
692 s++;
693 cur->val = LIST;
694 if (parse_imap_list_l(imap, &s, &cur->child, level + 1))
695 goto bail;
696 } else if (imap && *s == '{') {
697 /* literal */
698 bytes = cur->len = strtol(s + 1, &s, 10);
699 if (*s != '}')
700 goto bail;
702 s = cur->val = xmalloc(cur->len);
704 /* dump whats left over in the input buffer */
705 n = imap->buf.bytes - imap->buf.offset;
707 if (n > bytes)
708 /* the entire message fit in the buffer */
709 n = bytes;
711 memcpy(s, imap->buf.buf + imap->buf.offset, n);
712 s += n;
713 bytes -= n;
715 /* mark that we used part of the buffer */
716 imap->buf.offset += n;
718 /* now read the rest of the message */
719 while (bytes > 0) {
720 if ((n = socket_read(&imap->buf.sock, s, bytes)) <= 0)
721 goto bail;
722 s += n;
723 bytes -= n;
726 if (buffer_gets(&imap->buf, &s))
727 goto bail;
728 } else if (*s == '"') {
729 /* quoted string */
730 s++;
731 p = s;
732 for (; *s != '"'; s++)
733 if (!*s)
734 goto bail;
735 cur->len = s - p;
736 s++;
737 cur->val = xmemdupz(p, cur->len);
738 } else {
739 /* atom */
740 p = s;
741 for (; *s && !isspace((unsigned char)*s); s++)
742 if (level && *s == ')')
743 break;
744 cur->len = s - p;
745 if (cur->len == 3 && !memcmp("NIL", p, 3))
746 cur->val = NIL;
747 else
748 cur->val = xmemdupz(p, cur->len);
751 if (!level)
752 break;
753 if (!*s)
754 goto bail;
756 *sp = s;
757 *curp = NULL;
758 return 0;
760 bail:
761 *curp = NULL;
762 return -1;
765 static struct imap_list *parse_imap_list(struct imap *imap, char **sp)
767 struct imap_list *head;
769 if (!parse_imap_list_l(imap, sp, &head, 0))
770 return head;
771 free_list(head);
772 return NULL;
775 static struct imap_list *parse_list(char **sp)
777 return parse_imap_list(NULL, sp);
780 static void parse_capability(struct imap *imap, char *cmd)
782 char *arg;
783 unsigned i;
785 imap->caps = 0x80000000;
786 while ((arg = next_arg(&cmd)))
787 for (i = 0; i < ARRAY_SIZE(cap_list); i++)
788 if (!strcmp(cap_list[i], arg))
789 imap->caps |= 1 << i;
790 imap->rcaps = imap->caps;
793 static int parse_response_code(struct imap_store *ctx, struct imap_cmd_cb *cb,
794 char *s)
796 struct imap *imap = ctx->imap;
797 char *arg, *p;
799 if (*s != '[')
800 return RESP_OK; /* no response code */
801 s++;
802 if (!(p = strchr(s, ']'))) {
803 fprintf(stderr, "IMAP error: malformed response code\n");
804 return RESP_BAD;
806 *p++ = 0;
807 arg = next_arg(&s);
808 if (!strcmp("UIDVALIDITY", arg)) {
809 if (!(arg = next_arg(&s)) || !(ctx->gen.uidvalidity = atoi(arg))) {
810 fprintf(stderr, "IMAP error: malformed UIDVALIDITY status\n");
811 return RESP_BAD;
813 } else if (!strcmp("UIDNEXT", arg)) {
814 if (!(arg = next_arg(&s)) || !(imap->uidnext = atoi(arg))) {
815 fprintf(stderr, "IMAP error: malformed NEXTUID status\n");
816 return RESP_BAD;
818 } else if (!strcmp("CAPABILITY", arg)) {
819 parse_capability(imap, s);
820 } else if (!strcmp("ALERT", arg)) {
821 /* RFC2060 says that these messages MUST be displayed
822 * to the user
824 for (; isspace((unsigned char)*p); p++);
825 fprintf(stderr, "*** IMAP ALERT *** %s\n", p);
826 } else if (cb && cb->ctx && !strcmp("APPENDUID", arg)) {
827 if (!(arg = next_arg(&s)) || !(ctx->gen.uidvalidity = atoi(arg)) ||
828 !(arg = next_arg(&s)) || !(*(int *)cb->ctx = atoi(arg))) {
829 fprintf(stderr, "IMAP error: malformed APPENDUID status\n");
830 return RESP_BAD;
833 return RESP_OK;
836 static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd)
838 struct imap *imap = ctx->imap;
839 struct imap_cmd *cmdp, **pcmdp, *ncmdp;
840 char *cmd, *arg, *arg1, *p;
841 int n, resp, resp2, tag;
843 for (;;) {
844 if (buffer_gets(&imap->buf, &cmd))
845 return RESP_BAD;
847 arg = next_arg(&cmd);
848 if (*arg == '*') {
849 arg = next_arg(&cmd);
850 if (!arg) {
851 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
852 return RESP_BAD;
855 if (!strcmp("NAMESPACE", arg)) {
856 imap->ns_personal = parse_list(&cmd);
857 imap->ns_other = parse_list(&cmd);
858 imap->ns_shared = parse_list(&cmd);
859 } else if (!strcmp("OK", arg) || !strcmp("BAD", arg) ||
860 !strcmp("NO", arg) || !strcmp("BYE", arg)) {
861 if ((resp = parse_response_code(ctx, NULL, cmd)) != RESP_OK)
862 return resp;
863 } else if (!strcmp("CAPABILITY", arg))
864 parse_capability(imap, cmd);
865 else if ((arg1 = next_arg(&cmd))) {
866 if (!strcmp("EXISTS", arg1))
867 ctx->gen.count = atoi(arg);
868 else if (!strcmp("RECENT", arg1))
869 ctx->gen.recent = atoi(arg);
870 } else {
871 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
872 return RESP_BAD;
874 } else if (!imap->in_progress) {
875 fprintf(stderr, "IMAP error: unexpected reply: %s %s\n", arg, cmd ? cmd : "");
876 return RESP_BAD;
877 } else if (*arg == '+') {
878 /* This can happen only with the last command underway, as
879 it enforces a round-trip. */
880 cmdp = (struct imap_cmd *)((char *)imap->in_progress_append -
881 offsetof(struct imap_cmd, next));
882 if (cmdp->cb.data) {
883 n = socket_write(&imap->buf.sock, cmdp->cb.data, cmdp->cb.dlen);
884 free(cmdp->cb.data);
885 cmdp->cb.data = NULL;
886 if (n != (int)cmdp->cb.dlen)
887 return RESP_BAD;
888 } else if (cmdp->cb.cont) {
889 if (cmdp->cb.cont(ctx, cmdp, cmd))
890 return RESP_BAD;
891 } else {
892 fprintf(stderr, "IMAP error: unexpected command continuation request\n");
893 return RESP_BAD;
895 if (socket_write(&imap->buf.sock, "\r\n", 2) != 2)
896 return RESP_BAD;
897 if (!cmdp->cb.cont)
898 imap->literal_pending = 0;
899 if (!tcmd)
900 return DRV_OK;
901 } else {
902 tag = atoi(arg);
903 for (pcmdp = &imap->in_progress; (cmdp = *pcmdp); pcmdp = &cmdp->next)
904 if (cmdp->tag == tag)
905 goto gottag;
906 fprintf(stderr, "IMAP error: unexpected tag %s\n", arg);
907 return RESP_BAD;
908 gottag:
909 if (!(*pcmdp = cmdp->next))
910 imap->in_progress_append = pcmdp;
911 imap->num_in_progress--;
912 if (cmdp->cb.cont || cmdp->cb.data)
913 imap->literal_pending = 0;
914 arg = next_arg(&cmd);
915 if (!strcmp("OK", arg))
916 resp = DRV_OK;
917 else {
918 if (!strcmp("NO", arg)) {
919 if (cmdp->cb.create && cmd && (cmdp->cb.trycreate || !memcmp(cmd, "[TRYCREATE]", 11))) { /* SELECT, APPEND or UID COPY */
920 p = strchr(cmdp->cmd, '"');
921 if (!issue_imap_cmd(ctx, NULL, "CREATE \"%.*s\"", strchr(p + 1, '"') - p + 1, p)) {
922 resp = RESP_BAD;
923 goto normal;
925 /* not waiting here violates the spec, but a server that does not
926 grok this nonetheless violates it too. */
927 cmdp->cb.create = 0;
928 if (!(ncmdp = issue_imap_cmd(ctx, &cmdp->cb, "%s", cmdp->cmd))) {
929 resp = RESP_BAD;
930 goto normal;
932 free(cmdp->cmd);
933 free(cmdp);
934 if (!tcmd)
935 return 0; /* ignored */
936 if (cmdp == tcmd)
937 tcmd = ncmdp;
938 continue;
940 resp = RESP_NO;
941 } else /*if (!strcmp("BAD", arg))*/
942 resp = RESP_BAD;
943 fprintf(stderr, "IMAP command '%s' returned response (%s) - %s\n",
944 memcmp(cmdp->cmd, "LOGIN", 5) ?
945 cmdp->cmd : "LOGIN <user> <pass>",
946 arg, cmd ? cmd : "");
948 if ((resp2 = parse_response_code(ctx, &cmdp->cb, cmd)) > resp)
949 resp = resp2;
950 normal:
951 if (cmdp->cb.done)
952 cmdp->cb.done(ctx, cmdp, resp);
953 free(cmdp->cb.data);
954 free(cmdp->cmd);
955 free(cmdp);
956 if (!tcmd || tcmd == cmdp)
957 return resp;
960 /* not reached */
963 static void imap_close_server(struct imap_store *ictx)
965 struct imap *imap = ictx->imap;
967 if (imap->buf.sock.fd != -1) {
968 imap_exec(ictx, NULL, "LOGOUT");
969 socket_shutdown(&imap->buf.sock);
971 free_list(imap->ns_personal);
972 free_list(imap->ns_other);
973 free_list(imap->ns_shared);
974 free(imap);
977 static void imap_close_store(struct store *ctx)
979 imap_close_server((struct imap_store *)ctx);
980 free_generic_messages(ctx->msgs);
981 free(ctx);
984 static struct store *imap_open_store(struct imap_server_conf *srvc)
986 struct imap_store *ctx;
987 struct imap *imap;
988 char *arg, *rsp;
989 int s = -1, a[2], preauth;
990 pid_t pid;
992 ctx = xcalloc(sizeof(*ctx), 1);
994 ctx->imap = imap = xcalloc(sizeof(*imap), 1);
995 imap->buf.sock.fd = -1;
996 imap->in_progress_append = &imap->in_progress;
998 /* open connection to IMAP server */
1000 if (srvc->tunnel) {
1001 imap_info("Starting tunnel '%s'... ", srvc->tunnel);
1003 if (socketpair(PF_UNIX, SOCK_STREAM, 0, a)) {
1004 perror("socketpair");
1005 exit(1);
1008 pid = fork();
1009 if (pid < 0)
1010 _exit(127);
1011 if (!pid) {
1012 if (dup2(a[0], 0) == -1 || dup2(a[0], 1) == -1)
1013 _exit(127);
1014 close(a[0]);
1015 close(a[1]);
1016 execl("/bin/sh", "sh", "-c", srvc->tunnel, NULL);
1017 _exit(127);
1020 close(a[0]);
1022 imap->buf.sock.fd = a[1];
1024 imap_info("ok\n");
1025 } else {
1026 #ifndef NO_IPV6
1027 struct addrinfo hints, *ai0, *ai;
1028 int gai;
1029 char portstr[6];
1031 snprintf(portstr, sizeof(portstr), "%hu", srvc->port);
1033 memset(&hints, 0, sizeof(hints));
1034 hints.ai_socktype = SOCK_STREAM;
1035 hints.ai_protocol = IPPROTO_TCP;
1037 imap_info("Resolving %s... ", srvc->host);
1038 gai = getaddrinfo(srvc->host, portstr, &hints, &ai);
1039 if (gai) {
1040 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai));
1041 goto bail;
1043 imap_info("ok\n");
1045 for (ai0 = ai; ai; ai = ai->ai_next) {
1046 char addr[NI_MAXHOST];
1048 s = socket(ai->ai_family, ai->ai_socktype,
1049 ai->ai_protocol);
1050 if (s < 0)
1051 continue;
1053 getnameinfo(ai->ai_addr, ai->ai_addrlen, addr,
1054 sizeof(addr), NULL, 0, NI_NUMERICHOST);
1055 imap_info("Connecting to [%s]:%s... ", addr, portstr);
1057 if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0) {
1058 close(s);
1059 s = -1;
1060 perror("connect");
1061 continue;
1064 break;
1066 freeaddrinfo(ai0);
1067 #else /* NO_IPV6 */
1068 struct hostent *he;
1069 struct sockaddr_in addr;
1071 memset(&addr, 0, sizeof(addr));
1072 addr.sin_port = htons(srvc->port);
1073 addr.sin_family = AF_INET;
1075 imap_info("Resolving %s... ", srvc->host);
1076 he = gethostbyname(srvc->host);
1077 if (!he) {
1078 perror("gethostbyname");
1079 goto bail;
1081 imap_info("ok\n");
1083 addr.sin_addr.s_addr = *((int *) he->h_addr_list[0]);
1085 s = socket(PF_INET, SOCK_STREAM, 0);
1087 imap_info("Connecting to %s:%hu... ", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
1088 if (connect(s, (struct sockaddr *)&addr, sizeof(addr))) {
1089 close(s);
1090 s = -1;
1091 perror("connect");
1093 #endif
1094 if (s < 0) {
1095 fputs("Error: unable to connect to server.\n", stderr);
1096 goto bail;
1099 imap->buf.sock.fd = s;
1101 if (srvc->use_ssl &&
1102 ssl_socket_connect(&imap->buf.sock, 0, srvc->ssl_verify)) {
1103 close(s);
1104 goto bail;
1106 imap_info("ok\n");
1109 /* read the greeting string */
1110 if (buffer_gets(&imap->buf, &rsp)) {
1111 fprintf(stderr, "IMAP error: no greeting response\n");
1112 goto bail;
1114 arg = next_arg(&rsp);
1115 if (!arg || *arg != '*' || (arg = next_arg(&rsp)) == NULL) {
1116 fprintf(stderr, "IMAP error: invalid greeting response\n");
1117 goto bail;
1119 preauth = 0;
1120 if (!strcmp("PREAUTH", arg))
1121 preauth = 1;
1122 else if (strcmp("OK", arg) != 0) {
1123 fprintf(stderr, "IMAP error: unknown greeting response\n");
1124 goto bail;
1126 parse_response_code(ctx, NULL, rsp);
1127 if (!imap->caps && imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1128 goto bail;
1130 if (!preauth) {
1131 #ifndef NO_OPENSSL
1132 if (!srvc->use_ssl && CAP(STARTTLS)) {
1133 if (imap_exec(ctx, 0, "STARTTLS") != RESP_OK)
1134 goto bail;
1135 if (ssl_socket_connect(&imap->buf.sock, 1,
1136 srvc->ssl_verify))
1137 goto bail;
1138 /* capabilities may have changed, so get the new capabilities */
1139 if (imap_exec(ctx, 0, "CAPABILITY") != RESP_OK)
1140 goto bail;
1142 #endif
1143 imap_info("Logging in...\n");
1144 if (!srvc->user) {
1145 fprintf(stderr, "Skipping server %s, no user\n", srvc->host);
1146 goto bail;
1148 if (!srvc->pass) {
1149 char prompt[80];
1150 sprintf(prompt, "Password (%s@%s): ", srvc->user, srvc->host);
1151 arg = getpass(prompt);
1152 if (!arg) {
1153 perror("getpass");
1154 exit(1);
1156 if (!*arg) {
1157 fprintf(stderr, "Skipping account %s@%s, no password\n", srvc->user, srvc->host);
1158 goto bail;
1161 * getpass() returns a pointer to a static buffer. make a copy
1162 * for long term storage.
1164 srvc->pass = xstrdup(arg);
1166 if (CAP(NOLOGIN)) {
1167 fprintf(stderr, "Skipping account %s@%s, server forbids LOGIN\n", srvc->user, srvc->host);
1168 goto bail;
1170 if (!imap->buf.sock.ssl)
1171 imap_warn("*** IMAP Warning *** Password is being "
1172 "sent in the clear\n");
1173 if (imap_exec(ctx, NULL, "LOGIN \"%s\" \"%s\"", srvc->user, srvc->pass) != RESP_OK) {
1174 fprintf(stderr, "IMAP error: LOGIN failed\n");
1175 goto bail;
1177 } /* !preauth */
1179 ctx->prefix = "";
1180 ctx->trashnc = 1;
1181 return (struct store *)ctx;
1183 bail:
1184 imap_close_store(&ctx->gen);
1185 return NULL;
1188 static int imap_make_flags(int flags, char *buf)
1190 const char *s;
1191 unsigned i, d;
1193 for (i = d = 0; i < ARRAY_SIZE(Flags); i++)
1194 if (flags & (1 << i)) {
1195 buf[d++] = ' ';
1196 buf[d++] = '\\';
1197 for (s = Flags[i]; *s; s++)
1198 buf[d++] = *s;
1200 buf[0] = '(';
1201 buf[d++] = ')';
1202 return d;
1205 #define TUIDL 8
1207 static int imap_store_msg(struct store *gctx, struct msg_data *data, int *uid)
1209 struct imap_store *ctx = (struct imap_store *)gctx;
1210 struct imap *imap = ctx->imap;
1211 struct imap_cmd_cb cb;
1212 char *fmap, *buf;
1213 const char *prefix, *box;
1214 int ret, i, j, d, len, extra, nocr;
1215 int start, sbreak = 0, ebreak = 0;
1216 char flagstr[128], tuid[TUIDL * 2 + 1];
1218 memset(&cb, 0, sizeof(cb));
1220 fmap = data->data;
1221 len = data->len;
1222 nocr = !data->crlf;
1223 extra = 0, i = 0;
1224 if (!CAP(UIDPLUS) && uid) {
1225 nloop:
1226 start = i;
1227 while (i < len)
1228 if (fmap[i++] == '\n') {
1229 extra += nocr;
1230 if (i - 2 + nocr == start) {
1231 sbreak = ebreak = i - 2 + nocr;
1232 goto mktid;
1234 if (!memcmp(fmap + start, "X-TUID: ", 8)) {
1235 extra -= (ebreak = i) - (sbreak = start) + nocr;
1236 goto mktid;
1238 goto nloop;
1240 /* invalid message */
1241 free(fmap);
1242 return DRV_MSG_BAD;
1243 mktid:
1244 for (j = 0; j < TUIDL; j++)
1245 sprintf(tuid + j * 2, "%02x", arc4_getbyte());
1246 extra += 8 + TUIDL * 2 + 2;
1248 if (nocr)
1249 for (; i < len; i++)
1250 if (fmap[i] == '\n')
1251 extra++;
1253 cb.dlen = len + extra;
1254 buf = cb.data = xmalloc(cb.dlen);
1255 i = 0;
1256 if (!CAP(UIDPLUS) && uid) {
1257 if (nocr) {
1258 for (; i < sbreak; i++)
1259 if (fmap[i] == '\n') {
1260 *buf++ = '\r';
1261 *buf++ = '\n';
1262 } else
1263 *buf++ = fmap[i];
1264 } else {
1265 memcpy(buf, fmap, sbreak);
1266 buf += sbreak;
1268 memcpy(buf, "X-TUID: ", 8);
1269 buf += 8;
1270 memcpy(buf, tuid, TUIDL * 2);
1271 buf += TUIDL * 2;
1272 *buf++ = '\r';
1273 *buf++ = '\n';
1274 i = ebreak;
1276 if (nocr) {
1277 for (; i < len; i++)
1278 if (fmap[i] == '\n') {
1279 *buf++ = '\r';
1280 *buf++ = '\n';
1281 } else
1282 *buf++ = fmap[i];
1283 } else
1284 memcpy(buf, fmap + i, len - i);
1286 free(fmap);
1288 d = 0;
1289 if (data->flags) {
1290 d = imap_make_flags(data->flags, flagstr);
1291 flagstr[d++] = ' ';
1293 flagstr[d] = 0;
1295 if (!uid) {
1296 box = gctx->conf->trash;
1297 prefix = ctx->prefix;
1298 cb.create = 1;
1299 if (ctx->trashnc)
1300 imap->caps = imap->rcaps & ~(1 << LITERALPLUS);
1301 } else {
1302 box = gctx->name;
1303 prefix = !strcmp(box, "INBOX") ? "" : ctx->prefix;
1304 cb.create = 0;
1306 cb.ctx = uid;
1307 ret = imap_exec_m(ctx, &cb, "APPEND \"%s%s\" %s", prefix, box, flagstr);
1308 imap->caps = imap->rcaps;
1309 if (ret != DRV_OK)
1310 return ret;
1311 if (!uid)
1312 ctx->trashnc = 0;
1313 else
1314 gctx->count++;
1316 return DRV_OK;
1319 static void encode_html_chars(struct strbuf *p)
1321 int i;
1322 for (i = 0; i < p->len; i++) {
1323 if (p->buf[i] == '&')
1324 strbuf_splice(p, i, 1, "&amp;", 5);
1325 if (p->buf[i] == '<')
1326 strbuf_splice(p, i, 1, "&lt;", 4);
1327 if (p->buf[i] == '>')
1328 strbuf_splice(p, i, 1, "&gt;", 4);
1329 if (p->buf[i] == '"')
1330 strbuf_splice(p, i, 1, "&quot;", 6);
1333 static void wrap_in_html(struct msg_data *msg)
1335 struct strbuf buf = STRBUF_INIT;
1336 struct strbuf **lines;
1337 struct strbuf **p;
1338 static char *content_type = "Content-Type: text/html;\n";
1339 static char *pre_open = "<pre>\n";
1340 static char *pre_close = "</pre>\n";
1341 int added_header = 0;
1343 strbuf_attach(&buf, msg->data, msg->len, msg->len);
1344 lines = strbuf_split(&buf, '\n');
1345 strbuf_release(&buf);
1346 for (p = lines; *p; p++) {
1347 if (! added_header) {
1348 if ((*p)->len == 1 && *((*p)->buf) == '\n') {
1349 strbuf_addstr(&buf, content_type);
1350 strbuf_addbuf(&buf, *p);
1351 strbuf_addstr(&buf, pre_open);
1352 added_header = 1;
1353 continue;
1356 else
1357 encode_html_chars(*p);
1358 strbuf_addbuf(&buf, *p);
1360 strbuf_addstr(&buf, pre_close);
1361 strbuf_list_free(lines);
1362 msg->len = buf.len;
1363 msg->data = strbuf_detach(&buf, NULL);
1366 #define CHUNKSIZE 0x1000
1368 static int read_message(FILE *f, struct msg_data *msg)
1370 struct strbuf buf = STRBUF_INIT;
1372 memset(msg, 0, sizeof(*msg));
1374 do {
1375 if (strbuf_fread(&buf, CHUNKSIZE, f) <= 0)
1376 break;
1377 } while (!feof(f));
1379 msg->len = buf.len;
1380 msg->data = strbuf_detach(&buf, NULL);
1381 return msg->len;
1384 static int count_messages(struct msg_data *msg)
1386 int count = 0;
1387 char *p = msg->data;
1389 while (1) {
1390 if (!prefixcmp(p, "From ")) {
1391 count++;
1392 p += 5;
1394 p = strstr(p+5, "\nFrom ");
1395 if (!p)
1396 break;
1397 p++;
1399 return count;
1402 static int split_msg(struct msg_data *all_msgs, struct msg_data *msg, int *ofs)
1404 char *p, *data;
1406 memset(msg, 0, sizeof *msg);
1407 if (*ofs >= all_msgs->len)
1408 return 0;
1410 data = &all_msgs->data[*ofs];
1411 msg->len = all_msgs->len - *ofs;
1413 if (msg->len < 5 || prefixcmp(data, "From "))
1414 return 0;
1416 p = strchr(data, '\n');
1417 if (p) {
1418 p = &p[1];
1419 msg->len -= p-data;
1420 *ofs += p-data;
1421 data = p;
1424 p = strstr(data, "\nFrom ");
1425 if (p)
1426 msg->len = &p[1] - data;
1428 msg->data = xmemdupz(data, msg->len);
1429 *ofs += msg->len;
1430 return 1;
1433 static struct imap_server_conf server = {
1434 NULL, /* name */
1435 NULL, /* tunnel */
1436 NULL, /* host */
1437 0, /* port */
1438 NULL, /* user */
1439 NULL, /* pass */
1440 0, /* use_ssl */
1441 1, /* ssl_verify */
1442 0, /* use_html */
1445 static char *imap_folder;
1447 static int git_imap_config(const char *key, const char *val, void *cb)
1449 char imap_key[] = "imap.";
1451 if (strncmp(key, imap_key, sizeof imap_key - 1))
1452 return 0;
1454 if (!val)
1455 return config_error_nonbool(key);
1457 key += sizeof imap_key - 1;
1459 if (!strcmp("folder", key)) {
1460 imap_folder = xstrdup(val);
1461 } else if (!strcmp("host", key)) {
1462 if (!prefixcmp(val, "imap:"))
1463 val += 5;
1464 else if (!prefixcmp(val, "imaps:")) {
1465 val += 6;
1466 server.use_ssl = 1;
1468 if (!prefixcmp(val, "//"))
1469 val += 2;
1470 server.host = xstrdup(val);
1471 } else if (!strcmp("user", key))
1472 server.user = xstrdup(val);
1473 else if (!strcmp("pass", key))
1474 server.pass = xstrdup(val);
1475 else if (!strcmp("port", key))
1476 server.port = git_config_int(key, val);
1477 else if (!strcmp("tunnel", key))
1478 server.tunnel = xstrdup(val);
1479 else if (!strcmp("sslverify", key))
1480 server.ssl_verify = git_config_bool(key, val);
1481 else if (!strcmp("preformattedHTML", key))
1482 server.use_html = git_config_bool(key, val);
1483 return 0;
1486 int main(int argc, char **argv)
1488 struct msg_data all_msgs, msg;
1489 struct store *ctx = NULL;
1490 int uid = 0;
1491 int ofs = 0;
1492 int r;
1493 int total, n = 0;
1494 int nongit_ok;
1496 git_extract_argv0_path(argv[0]);
1498 /* init the random number generator */
1499 arc4_init();
1501 setup_git_directory_gently(&nongit_ok);
1502 git_config(git_imap_config, NULL);
1504 if (!server.port)
1505 server.port = server.use_ssl ? 993 : 143;
1507 if (!imap_folder) {
1508 fprintf(stderr, "no imap store specified\n");
1509 return 1;
1511 if (!server.host) {
1512 if (!server.tunnel) {
1513 fprintf(stderr, "no imap host specified\n");
1514 return 1;
1516 server.host = "tunnel";
1519 /* read the messages */
1520 if (!read_message(stdin, &all_msgs)) {
1521 fprintf(stderr, "nothing to send\n");
1522 return 1;
1525 total = count_messages(&all_msgs);
1526 if (!total) {
1527 fprintf(stderr, "no messages to send\n");
1528 return 1;
1531 /* write it to the imap server */
1532 ctx = imap_open_store(&server);
1533 if (!ctx) {
1534 fprintf(stderr, "failed to open store\n");
1535 return 1;
1538 fprintf(stderr, "sending %d message%s\n", total, (total != 1) ? "s" : "");
1539 ctx->name = imap_folder;
1540 while (1) {
1541 unsigned percent = n * 100 / total;
1542 fprintf(stderr, "%4u%% (%d/%d) done\r", percent, n, total);
1543 if (!split_msg(&all_msgs, &msg, &ofs))
1544 break;
1545 if (server.use_html)
1546 wrap_in_html(&msg);
1547 r = imap_store_msg(ctx, &msg, &uid);
1548 if (r != DRV_OK)
1549 break;
1550 n++;
1552 fprintf(stderr, "\n");
1554 imap_close_store(ctx);
1556 return 0;