Show usage string for 'git imap-send -h'
[git/wpalmer.git] / imap-send.c
blob04e537406e4113d5c1ead7b7e4a1a425c9b2bf09
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 static const char imap_send_usage[] = "git imap-send < <mbox>";
98 #define DRV_OK 0
99 #define DRV_MSG_BAD -1
100 #define DRV_BOX_BAD -2
101 #define DRV_STORE_BAD -3
103 static int Verbose, Quiet;
105 static void imap_info(const char *, ...);
106 static void imap_warn(const char *, ...);
108 static char *next_arg(char **);
110 static void free_generic_messages(struct message *);
112 static int nfsnprintf(char *buf, int blen, const char *fmt, ...);
114 static int nfvasprintf(char **strp, const char *fmt, va_list ap)
116 int len;
117 char tmp[8192];
119 len = vsnprintf(tmp, sizeof(tmp), fmt, ap);
120 if (len < 0)
121 die("Fatal: Out of memory");
122 if (len >= sizeof(tmp))
123 die("imap command overflow!");
124 *strp = xmemdupz(tmp, len);
125 return len;
128 static void arc4_init(void);
129 static unsigned char arc4_getbyte(void);
131 struct imap_server_conf {
132 char *name;
133 char *tunnel;
134 char *host;
135 int port;
136 char *user;
137 char *pass;
138 int use_ssl;
139 int ssl_verify;
140 int use_html;
143 struct imap_store_conf {
144 struct store_conf gen;
145 struct imap_server_conf *server;
146 unsigned use_namespace:1;
149 #define NIL (void *)0x1
150 #define LIST (void *)0x2
152 struct imap_list {
153 struct imap_list *next, *child;
154 char *val;
155 int len;
158 struct imap_socket {
159 int fd;
160 SSL *ssl;
163 struct imap_buffer {
164 struct imap_socket sock;
165 int bytes;
166 int offset;
167 char buf[1024];
170 struct imap_cmd;
172 struct imap {
173 int uidnext; /* from SELECT responses */
174 struct imap_list *ns_personal, *ns_other, *ns_shared; /* NAMESPACE info */
175 unsigned caps, rcaps; /* CAPABILITY results */
176 /* command queue */
177 int nexttag, num_in_progress, literal_pending;
178 struct imap_cmd *in_progress, **in_progress_append;
179 struct imap_buffer buf; /* this is BIG, so put it last */
182 struct imap_store {
183 struct store gen;
184 int uidvalidity;
185 struct imap *imap;
186 const char *prefix;
187 unsigned /*currentnc:1,*/ trashnc:1;
190 struct imap_cmd_cb {
191 int (*cont)(struct imap_store *ctx, struct imap_cmd *cmd, const char *prompt);
192 void (*done)(struct imap_store *ctx, struct imap_cmd *cmd, int response);
193 void *ctx;
194 char *data;
195 int dlen;
196 int uid;
197 unsigned create:1, trycreate:1;
200 struct imap_cmd {
201 struct imap_cmd *next;
202 struct imap_cmd_cb cb;
203 char *cmd;
204 int tag;
207 #define CAP(cap) (imap->caps & (1 << (cap)))
209 enum CAPABILITY {
210 NOLOGIN = 0,
211 UIDPLUS,
212 LITERALPLUS,
213 NAMESPACE,
214 STARTTLS,
217 static const char *cap_list[] = {
218 "LOGINDISABLED",
219 "UIDPLUS",
220 "LITERAL+",
221 "NAMESPACE",
222 "STARTTLS",
225 #define RESP_OK 0
226 #define RESP_NO 1
227 #define RESP_BAD 2
229 static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd);
232 static const char *Flags[] = {
233 "Draft",
234 "Flagged",
235 "Answered",
236 "Seen",
237 "Deleted",
240 #ifndef NO_OPENSSL
241 static void ssl_socket_perror(const char *func)
243 fprintf(stderr, "%s: %s\n", func, ERR_error_string(ERR_get_error(), NULL));
245 #endif
247 static void socket_perror(const char *func, struct imap_socket *sock, int ret)
249 #ifndef NO_OPENSSL
250 if (sock->ssl) {
251 int sslerr = SSL_get_error(sock->ssl, ret);
252 switch (sslerr) {
253 case SSL_ERROR_NONE:
254 break;
255 case SSL_ERROR_SYSCALL:
256 perror("SSL_connect");
257 break;
258 default:
259 ssl_socket_perror("SSL_connect");
260 break;
262 } else
263 #endif
265 if (ret < 0)
266 perror(func);
267 else
268 fprintf(stderr, "%s: unexpected EOF\n", func);
272 static int ssl_socket_connect(struct imap_socket *sock, int use_tls_only, int verify)
274 #ifdef NO_OPENSSL
275 fprintf(stderr, "SSL requested but SSL support not compiled in\n");
276 return -1;
277 #else
278 SSL_METHOD *meth;
279 SSL_CTX *ctx;
280 int ret;
282 SSL_library_init();
283 SSL_load_error_strings();
285 if (use_tls_only)
286 meth = TLSv1_method();
287 else
288 meth = SSLv23_method();
290 if (!meth) {
291 ssl_socket_perror("SSLv23_method");
292 return -1;
295 ctx = SSL_CTX_new(meth);
297 if (verify)
298 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
300 if (!SSL_CTX_set_default_verify_paths(ctx)) {
301 ssl_socket_perror("SSL_CTX_set_default_verify_paths");
302 return -1;
304 sock->ssl = SSL_new(ctx);
305 if (!sock->ssl) {
306 ssl_socket_perror("SSL_new");
307 return -1;
309 if (!SSL_set_fd(sock->ssl, sock->fd)) {
310 ssl_socket_perror("SSL_set_fd");
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, buf, len);
333 if (n <= 0) {
334 socket_perror("read", sock, n);
335 close(sock->fd);
336 sock->fd = -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, buf, len);
350 if (n != len) {
351 socket_perror("write", sock, n);
352 close(sock->fd);
353 sock->fd = -1;
355 return n;
358 static void socket_shutdown(struct imap_socket *sock)
360 #ifndef NO_OPENSSL
361 if (sock->ssl) {
362 SSL_shutdown(sock->ssl);
363 SSL_free(sock->ssl);
365 #endif
366 close(sock->fd);
369 /* simple line buffering */
370 static int buffer_gets(struct imap_buffer *b, char **s)
372 int n;
373 int start = b->offset;
375 *s = b->buf + start;
377 for (;;) {
378 /* make sure we have enough data to read the \r\n sequence */
379 if (b->offset + 1 >= b->bytes) {
380 if (start) {
381 /* shift down used bytes */
382 *s = b->buf;
384 assert(start <= b->bytes);
385 n = b->bytes - start;
387 if (n)
388 memmove(b->buf, b->buf + start, n);
389 b->offset -= start;
390 b->bytes = n;
391 start = 0;
394 n = socket_read(&b->sock, b->buf + b->bytes,
395 sizeof(b->buf) - b->bytes);
397 if (n <= 0)
398 return -1;
400 b->bytes += n;
403 if (b->buf[b->offset] == '\r') {
404 assert(b->offset + 1 < b->bytes);
405 if (b->buf[b->offset + 1] == '\n') {
406 b->buf[b->offset] = 0; /* terminate the string */
407 b->offset += 2; /* next line */
408 if (Verbose)
409 puts(*s);
410 return 0;
414 b->offset++;
416 /* not reached */
419 static void imap_info(const char *msg, ...)
421 va_list va;
423 if (!Quiet) {
424 va_start(va, msg);
425 vprintf(msg, va);
426 va_end(va);
427 fflush(stdout);
431 static void imap_warn(const char *msg, ...)
433 va_list va;
435 if (Quiet < 2) {
436 va_start(va, msg);
437 vfprintf(stderr, msg, va);
438 va_end(va);
442 static char *next_arg(char **s)
444 char *ret;
446 if (!s || !*s)
447 return NULL;
448 while (isspace((unsigned char) **s))
449 (*s)++;
450 if (!**s) {
451 *s = NULL;
452 return NULL;
454 if (**s == '"') {
455 ++*s;
456 ret = *s;
457 *s = strchr(*s, '"');
458 } else {
459 ret = *s;
460 while (**s && !isspace((unsigned char) **s))
461 (*s)++;
463 if (*s) {
464 if (**s)
465 *(*s)++ = 0;
466 if (!**s)
467 *s = NULL;
469 return ret;
472 static void free_generic_messages(struct message *msgs)
474 struct message *tmsg;
476 for (; msgs; msgs = tmsg) {
477 tmsg = msgs->next;
478 free(msgs);
482 static int nfsnprintf(char *buf, int blen, const char *fmt, ...)
484 int ret;
485 va_list va;
487 va_start(va, fmt);
488 if (blen <= 0 || (unsigned)(ret = vsnprintf(buf, blen, fmt, va)) >= (unsigned)blen)
489 die("Fatal: buffer too small. Please report a bug.");
490 va_end(va);
491 return ret;
494 static struct {
495 unsigned char i, j, s[256];
496 } rs;
498 static void arc4_init(void)
500 int i, fd;
501 unsigned char j, si, dat[128];
503 if ((fd = open("/dev/urandom", O_RDONLY)) < 0 && (fd = open("/dev/random", O_RDONLY)) < 0) {
504 fprintf(stderr, "Fatal: no random number source available.\n");
505 exit(3);
507 if (read_in_full(fd, dat, 128) != 128) {
508 fprintf(stderr, "Fatal: cannot read random number source.\n");
509 exit(3);
511 close(fd);
513 for (i = 0; i < 256; i++)
514 rs.s[i] = i;
515 for (i = j = 0; i < 256; i++) {
516 si = rs.s[i];
517 j += si + dat[i & 127];
518 rs.s[i] = rs.s[j];
519 rs.s[j] = si;
521 rs.i = rs.j = 0;
523 for (i = 0; i < 256; i++)
524 arc4_getbyte();
527 static unsigned char arc4_getbyte(void)
529 unsigned char si, sj;
531 rs.i++;
532 si = rs.s[rs.i];
533 rs.j += si;
534 sj = rs.s[rs.j];
535 rs.s[rs.i] = sj;
536 rs.s[rs.j] = si;
537 return rs.s[(si + sj) & 0xff];
540 static struct imap_cmd *v_issue_imap_cmd(struct imap_store *ctx,
541 struct imap_cmd_cb *cb,
542 const char *fmt, va_list ap)
544 struct imap *imap = ctx->imap;
545 struct imap_cmd *cmd;
546 int n, bufl;
547 char buf[1024];
549 cmd = xmalloc(sizeof(struct imap_cmd));
550 nfvasprintf(&cmd->cmd, fmt, ap);
551 cmd->tag = ++imap->nexttag;
553 if (cb)
554 cmd->cb = *cb;
555 else
556 memset(&cmd->cb, 0, sizeof(cmd->cb));
558 while (imap->literal_pending)
559 get_cmd_result(ctx, NULL);
561 bufl = nfsnprintf(buf, sizeof(buf), cmd->cb.data ? CAP(LITERALPLUS) ?
562 "%d %s{%d+}\r\n" : "%d %s{%d}\r\n" : "%d %s\r\n",
563 cmd->tag, cmd->cmd, cmd->cb.dlen);
564 if (Verbose) {
565 if (imap->num_in_progress)
566 printf("(%d in progress) ", imap->num_in_progress);
567 if (memcmp(cmd->cmd, "LOGIN", 5))
568 printf(">>> %s", buf);
569 else
570 printf(">>> %d LOGIN <user> <pass>\n", cmd->tag);
572 if (socket_write(&imap->buf.sock, buf, bufl) != bufl) {
573 free(cmd->cmd);
574 free(cmd);
575 if (cb)
576 free(cb->data);
577 return NULL;
579 if (cmd->cb.data) {
580 if (CAP(LITERALPLUS)) {
581 n = socket_write(&imap->buf.sock, cmd->cb.data, cmd->cb.dlen);
582 free(cmd->cb.data);
583 if (n != cmd->cb.dlen ||
584 socket_write(&imap->buf.sock, "\r\n", 2) != 2) {
585 free(cmd->cmd);
586 free(cmd);
587 return NULL;
589 cmd->cb.data = NULL;
590 } else
591 imap->literal_pending = 1;
592 } else if (cmd->cb.cont)
593 imap->literal_pending = 1;
594 cmd->next = NULL;
595 *imap->in_progress_append = cmd;
596 imap->in_progress_append = &cmd->next;
597 imap->num_in_progress++;
598 return cmd;
601 static struct imap_cmd *issue_imap_cmd(struct imap_store *ctx,
602 struct imap_cmd_cb *cb,
603 const char *fmt, ...)
605 struct imap_cmd *ret;
606 va_list ap;
608 va_start(ap, fmt);
609 ret = v_issue_imap_cmd(ctx, cb, fmt, ap);
610 va_end(ap);
611 return ret;
614 static int imap_exec(struct imap_store *ctx, struct imap_cmd_cb *cb,
615 const char *fmt, ...)
617 va_list ap;
618 struct imap_cmd *cmdp;
620 va_start(ap, fmt);
621 cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
622 va_end(ap);
623 if (!cmdp)
624 return RESP_BAD;
626 return get_cmd_result(ctx, cmdp);
629 static int imap_exec_m(struct imap_store *ctx, struct imap_cmd_cb *cb,
630 const char *fmt, ...)
632 va_list ap;
633 struct imap_cmd *cmdp;
635 va_start(ap, fmt);
636 cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
637 va_end(ap);
638 if (!cmdp)
639 return DRV_STORE_BAD;
641 switch (get_cmd_result(ctx, cmdp)) {
642 case RESP_BAD: return DRV_STORE_BAD;
643 case RESP_NO: return DRV_MSG_BAD;
644 default: return DRV_OK;
648 static int is_atom(struct imap_list *list)
650 return list && list->val && list->val != NIL && list->val != LIST;
653 static int is_list(struct imap_list *list)
655 return list && list->val == LIST;
658 static void free_list(struct imap_list *list)
660 struct imap_list *tmp;
662 for (; list; list = tmp) {
663 tmp = list->next;
664 if (is_list(list))
665 free_list(list->child);
666 else if (is_atom(list))
667 free(list->val);
668 free(list);
672 static int parse_imap_list_l(struct imap *imap, char **sp, struct imap_list **curp, int level)
674 struct imap_list *cur;
675 char *s = *sp, *p;
676 int n, bytes;
678 for (;;) {
679 while (isspace((unsigned char)*s))
680 s++;
681 if (level && *s == ')') {
682 s++;
683 break;
685 *curp = cur = xmalloc(sizeof(*cur));
686 curp = &cur->next;
687 cur->val = NULL; /* for clean bail */
688 if (*s == '(') {
689 /* sublist */
690 s++;
691 cur->val = LIST;
692 if (parse_imap_list_l(imap, &s, &cur->child, level + 1))
693 goto bail;
694 } else if (imap && *s == '{') {
695 /* literal */
696 bytes = cur->len = strtol(s + 1, &s, 10);
697 if (*s != '}')
698 goto bail;
700 s = cur->val = xmalloc(cur->len);
702 /* dump whats left over in the input buffer */
703 n = imap->buf.bytes - imap->buf.offset;
705 if (n > bytes)
706 /* the entire message fit in the buffer */
707 n = bytes;
709 memcpy(s, imap->buf.buf + imap->buf.offset, n);
710 s += n;
711 bytes -= n;
713 /* mark that we used part of the buffer */
714 imap->buf.offset += n;
716 /* now read the rest of the message */
717 while (bytes > 0) {
718 if ((n = socket_read(&imap->buf.sock, s, bytes)) <= 0)
719 goto bail;
720 s += n;
721 bytes -= n;
724 if (buffer_gets(&imap->buf, &s))
725 goto bail;
726 } else if (*s == '"') {
727 /* quoted string */
728 s++;
729 p = s;
730 for (; *s != '"'; s++)
731 if (!*s)
732 goto bail;
733 cur->len = s - p;
734 s++;
735 cur->val = xmemdupz(p, cur->len);
736 } else {
737 /* atom */
738 p = s;
739 for (; *s && !isspace((unsigned char)*s); s++)
740 if (level && *s == ')')
741 break;
742 cur->len = s - p;
743 if (cur->len == 3 && !memcmp("NIL", p, 3))
744 cur->val = NIL;
745 else
746 cur->val = xmemdupz(p, cur->len);
749 if (!level)
750 break;
751 if (!*s)
752 goto bail;
754 *sp = s;
755 *curp = NULL;
756 return 0;
758 bail:
759 *curp = NULL;
760 return -1;
763 static struct imap_list *parse_imap_list(struct imap *imap, char **sp)
765 struct imap_list *head;
767 if (!parse_imap_list_l(imap, sp, &head, 0))
768 return head;
769 free_list(head);
770 return NULL;
773 static struct imap_list *parse_list(char **sp)
775 return parse_imap_list(NULL, sp);
778 static void parse_capability(struct imap *imap, char *cmd)
780 char *arg;
781 unsigned i;
783 imap->caps = 0x80000000;
784 while ((arg = next_arg(&cmd)))
785 for (i = 0; i < ARRAY_SIZE(cap_list); i++)
786 if (!strcmp(cap_list[i], arg))
787 imap->caps |= 1 << i;
788 imap->rcaps = imap->caps;
791 static int parse_response_code(struct imap_store *ctx, struct imap_cmd_cb *cb,
792 char *s)
794 struct imap *imap = ctx->imap;
795 char *arg, *p;
797 if (*s != '[')
798 return RESP_OK; /* no response code */
799 s++;
800 if (!(p = strchr(s, ']'))) {
801 fprintf(stderr, "IMAP error: malformed response code\n");
802 return RESP_BAD;
804 *p++ = 0;
805 arg = next_arg(&s);
806 if (!strcmp("UIDVALIDITY", arg)) {
807 if (!(arg = next_arg(&s)) || !(ctx->gen.uidvalidity = atoi(arg))) {
808 fprintf(stderr, "IMAP error: malformed UIDVALIDITY status\n");
809 return RESP_BAD;
811 } else if (!strcmp("UIDNEXT", arg)) {
812 if (!(arg = next_arg(&s)) || !(imap->uidnext = atoi(arg))) {
813 fprintf(stderr, "IMAP error: malformed NEXTUID status\n");
814 return RESP_BAD;
816 } else if (!strcmp("CAPABILITY", arg)) {
817 parse_capability(imap, s);
818 } else if (!strcmp("ALERT", arg)) {
819 /* RFC2060 says that these messages MUST be displayed
820 * to the user
822 for (; isspace((unsigned char)*p); p++);
823 fprintf(stderr, "*** IMAP ALERT *** %s\n", p);
824 } else if (cb && cb->ctx && !strcmp("APPENDUID", arg)) {
825 if (!(arg = next_arg(&s)) || !(ctx->gen.uidvalidity = atoi(arg)) ||
826 !(arg = next_arg(&s)) || !(*(int *)cb->ctx = atoi(arg))) {
827 fprintf(stderr, "IMAP error: malformed APPENDUID status\n");
828 return RESP_BAD;
831 return RESP_OK;
834 static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd)
836 struct imap *imap = ctx->imap;
837 struct imap_cmd *cmdp, **pcmdp, *ncmdp;
838 char *cmd, *arg, *arg1, *p;
839 int n, resp, resp2, tag;
841 for (;;) {
842 if (buffer_gets(&imap->buf, &cmd))
843 return RESP_BAD;
845 arg = next_arg(&cmd);
846 if (*arg == '*') {
847 arg = next_arg(&cmd);
848 if (!arg) {
849 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
850 return RESP_BAD;
853 if (!strcmp("NAMESPACE", arg)) {
854 imap->ns_personal = parse_list(&cmd);
855 imap->ns_other = parse_list(&cmd);
856 imap->ns_shared = parse_list(&cmd);
857 } else if (!strcmp("OK", arg) || !strcmp("BAD", arg) ||
858 !strcmp("NO", arg) || !strcmp("BYE", arg)) {
859 if ((resp = parse_response_code(ctx, NULL, cmd)) != RESP_OK)
860 return resp;
861 } else if (!strcmp("CAPABILITY", arg))
862 parse_capability(imap, cmd);
863 else if ((arg1 = next_arg(&cmd))) {
864 if (!strcmp("EXISTS", arg1))
865 ctx->gen.count = atoi(arg);
866 else if (!strcmp("RECENT", arg1))
867 ctx->gen.recent = atoi(arg);
868 } else {
869 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
870 return RESP_BAD;
872 } else if (!imap->in_progress) {
873 fprintf(stderr, "IMAP error: unexpected reply: %s %s\n", arg, cmd ? cmd : "");
874 return RESP_BAD;
875 } else if (*arg == '+') {
876 /* This can happen only with the last command underway, as
877 it enforces a round-trip. */
878 cmdp = (struct imap_cmd *)((char *)imap->in_progress_append -
879 offsetof(struct imap_cmd, next));
880 if (cmdp->cb.data) {
881 n = socket_write(&imap->buf.sock, cmdp->cb.data, cmdp->cb.dlen);
882 free(cmdp->cb.data);
883 cmdp->cb.data = NULL;
884 if (n != (int)cmdp->cb.dlen)
885 return RESP_BAD;
886 } else if (cmdp->cb.cont) {
887 if (cmdp->cb.cont(ctx, cmdp, cmd))
888 return RESP_BAD;
889 } else {
890 fprintf(stderr, "IMAP error: unexpected command continuation request\n");
891 return RESP_BAD;
893 if (socket_write(&imap->buf.sock, "\r\n", 2) != 2)
894 return RESP_BAD;
895 if (!cmdp->cb.cont)
896 imap->literal_pending = 0;
897 if (!tcmd)
898 return DRV_OK;
899 } else {
900 tag = atoi(arg);
901 for (pcmdp = &imap->in_progress; (cmdp = *pcmdp); pcmdp = &cmdp->next)
902 if (cmdp->tag == tag)
903 goto gottag;
904 fprintf(stderr, "IMAP error: unexpected tag %s\n", arg);
905 return RESP_BAD;
906 gottag:
907 if (!(*pcmdp = cmdp->next))
908 imap->in_progress_append = pcmdp;
909 imap->num_in_progress--;
910 if (cmdp->cb.cont || cmdp->cb.data)
911 imap->literal_pending = 0;
912 arg = next_arg(&cmd);
913 if (!strcmp("OK", arg))
914 resp = DRV_OK;
915 else {
916 if (!strcmp("NO", arg)) {
917 if (cmdp->cb.create && cmd && (cmdp->cb.trycreate || !memcmp(cmd, "[TRYCREATE]", 11))) { /* SELECT, APPEND or UID COPY */
918 p = strchr(cmdp->cmd, '"');
919 if (!issue_imap_cmd(ctx, NULL, "CREATE \"%.*s\"", strchr(p + 1, '"') - p + 1, p)) {
920 resp = RESP_BAD;
921 goto normal;
923 /* not waiting here violates the spec, but a server that does not
924 grok this nonetheless violates it too. */
925 cmdp->cb.create = 0;
926 if (!(ncmdp = issue_imap_cmd(ctx, &cmdp->cb, "%s", cmdp->cmd))) {
927 resp = RESP_BAD;
928 goto normal;
930 free(cmdp->cmd);
931 free(cmdp);
932 if (!tcmd)
933 return 0; /* ignored */
934 if (cmdp == tcmd)
935 tcmd = ncmdp;
936 continue;
938 resp = RESP_NO;
939 } else /*if (!strcmp("BAD", arg))*/
940 resp = RESP_BAD;
941 fprintf(stderr, "IMAP command '%s' returned response (%s) - %s\n",
942 memcmp(cmdp->cmd, "LOGIN", 5) ?
943 cmdp->cmd : "LOGIN <user> <pass>",
944 arg, cmd ? cmd : "");
946 if ((resp2 = parse_response_code(ctx, &cmdp->cb, cmd)) > resp)
947 resp = resp2;
948 normal:
949 if (cmdp->cb.done)
950 cmdp->cb.done(ctx, cmdp, resp);
951 free(cmdp->cb.data);
952 free(cmdp->cmd);
953 free(cmdp);
954 if (!tcmd || tcmd == cmdp)
955 return resp;
958 /* not reached */
961 static void imap_close_server(struct imap_store *ictx)
963 struct imap *imap = ictx->imap;
965 if (imap->buf.sock.fd != -1) {
966 imap_exec(ictx, NULL, "LOGOUT");
967 socket_shutdown(&imap->buf.sock);
969 free_list(imap->ns_personal);
970 free_list(imap->ns_other);
971 free_list(imap->ns_shared);
972 free(imap);
975 static void imap_close_store(struct store *ctx)
977 imap_close_server((struct imap_store *)ctx);
978 free_generic_messages(ctx->msgs);
979 free(ctx);
982 static struct store *imap_open_store(struct imap_server_conf *srvc)
984 struct imap_store *ctx;
985 struct imap *imap;
986 char *arg, *rsp;
987 int s = -1, a[2], preauth;
988 pid_t pid;
990 ctx = xcalloc(sizeof(*ctx), 1);
992 ctx->imap = imap = xcalloc(sizeof(*imap), 1);
993 imap->buf.sock.fd = -1;
994 imap->in_progress_append = &imap->in_progress;
996 /* open connection to IMAP server */
998 if (srvc->tunnel) {
999 imap_info("Starting tunnel '%s'... ", srvc->tunnel);
1001 if (socketpair(PF_UNIX, SOCK_STREAM, 0, a)) {
1002 perror("socketpair");
1003 exit(1);
1006 pid = fork();
1007 if (pid < 0)
1008 _exit(127);
1009 if (!pid) {
1010 if (dup2(a[0], 0) == -1 || dup2(a[0], 1) == -1)
1011 _exit(127);
1012 close(a[0]);
1013 close(a[1]);
1014 execl("/bin/sh", "sh", "-c", srvc->tunnel, NULL);
1015 _exit(127);
1018 close(a[0]);
1020 imap->buf.sock.fd = a[1];
1022 imap_info("ok\n");
1023 } else {
1024 #ifndef NO_IPV6
1025 struct addrinfo hints, *ai0, *ai;
1026 int gai;
1027 char portstr[6];
1029 snprintf(portstr, sizeof(portstr), "%hu", srvc->port);
1031 memset(&hints, 0, sizeof(hints));
1032 hints.ai_socktype = SOCK_STREAM;
1033 hints.ai_protocol = IPPROTO_TCP;
1035 imap_info("Resolving %s... ", srvc->host);
1036 gai = getaddrinfo(srvc->host, portstr, &hints, &ai);
1037 if (gai) {
1038 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai));
1039 goto bail;
1041 imap_info("ok\n");
1043 for (ai0 = ai; ai; ai = ai->ai_next) {
1044 char addr[NI_MAXHOST];
1046 s = socket(ai->ai_family, ai->ai_socktype,
1047 ai->ai_protocol);
1048 if (s < 0)
1049 continue;
1051 getnameinfo(ai->ai_addr, ai->ai_addrlen, addr,
1052 sizeof(addr), NULL, 0, NI_NUMERICHOST);
1053 imap_info("Connecting to [%s]:%s... ", addr, portstr);
1055 if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0) {
1056 close(s);
1057 s = -1;
1058 perror("connect");
1059 continue;
1062 break;
1064 freeaddrinfo(ai0);
1065 #else /* NO_IPV6 */
1066 struct hostent *he;
1067 struct sockaddr_in addr;
1069 memset(&addr, 0, sizeof(addr));
1070 addr.sin_port = htons(srvc->port);
1071 addr.sin_family = AF_INET;
1073 imap_info("Resolving %s... ", srvc->host);
1074 he = gethostbyname(srvc->host);
1075 if (!he) {
1076 perror("gethostbyname");
1077 goto bail;
1079 imap_info("ok\n");
1081 addr.sin_addr.s_addr = *((int *) he->h_addr_list[0]);
1083 s = socket(PF_INET, SOCK_STREAM, 0);
1085 imap_info("Connecting to %s:%hu... ", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
1086 if (connect(s, (struct sockaddr *)&addr, sizeof(addr))) {
1087 close(s);
1088 s = -1;
1089 perror("connect");
1091 #endif
1092 if (s < 0) {
1093 fputs("Error: unable to connect to server.\n", stderr);
1094 goto bail;
1097 imap->buf.sock.fd = s;
1099 if (srvc->use_ssl &&
1100 ssl_socket_connect(&imap->buf.sock, 0, srvc->ssl_verify)) {
1101 close(s);
1102 goto bail;
1104 imap_info("ok\n");
1107 /* read the greeting string */
1108 if (buffer_gets(&imap->buf, &rsp)) {
1109 fprintf(stderr, "IMAP error: no greeting response\n");
1110 goto bail;
1112 arg = next_arg(&rsp);
1113 if (!arg || *arg != '*' || (arg = next_arg(&rsp)) == NULL) {
1114 fprintf(stderr, "IMAP error: invalid greeting response\n");
1115 goto bail;
1117 preauth = 0;
1118 if (!strcmp("PREAUTH", arg))
1119 preauth = 1;
1120 else if (strcmp("OK", arg) != 0) {
1121 fprintf(stderr, "IMAP error: unknown greeting response\n");
1122 goto bail;
1124 parse_response_code(ctx, NULL, rsp);
1125 if (!imap->caps && imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1126 goto bail;
1128 if (!preauth) {
1129 #ifndef NO_OPENSSL
1130 if (!srvc->use_ssl && CAP(STARTTLS)) {
1131 if (imap_exec(ctx, 0, "STARTTLS") != RESP_OK)
1132 goto bail;
1133 if (ssl_socket_connect(&imap->buf.sock, 1,
1134 srvc->ssl_verify))
1135 goto bail;
1136 /* capabilities may have changed, so get the new capabilities */
1137 if (imap_exec(ctx, 0, "CAPABILITY") != RESP_OK)
1138 goto bail;
1140 #endif
1141 imap_info("Logging in...\n");
1142 if (!srvc->user) {
1143 fprintf(stderr, "Skipping server %s, no user\n", srvc->host);
1144 goto bail;
1146 if (!srvc->pass) {
1147 char prompt[80];
1148 sprintf(prompt, "Password (%s@%s): ", srvc->user, srvc->host);
1149 arg = getpass(prompt);
1150 if (!arg) {
1151 perror("getpass");
1152 exit(1);
1154 if (!*arg) {
1155 fprintf(stderr, "Skipping account %s@%s, no password\n", srvc->user, srvc->host);
1156 goto bail;
1159 * getpass() returns a pointer to a static buffer. make a copy
1160 * for long term storage.
1162 srvc->pass = xstrdup(arg);
1164 if (CAP(NOLOGIN)) {
1165 fprintf(stderr, "Skipping account %s@%s, server forbids LOGIN\n", srvc->user, srvc->host);
1166 goto bail;
1168 if (!imap->buf.sock.ssl)
1169 imap_warn("*** IMAP Warning *** Password is being "
1170 "sent in the clear\n");
1171 if (imap_exec(ctx, NULL, "LOGIN \"%s\" \"%s\"", srvc->user, srvc->pass) != RESP_OK) {
1172 fprintf(stderr, "IMAP error: LOGIN failed\n");
1173 goto bail;
1175 } /* !preauth */
1177 ctx->prefix = "";
1178 ctx->trashnc = 1;
1179 return (struct store *)ctx;
1181 bail:
1182 imap_close_store(&ctx->gen);
1183 return NULL;
1186 static int imap_make_flags(int flags, char *buf)
1188 const char *s;
1189 unsigned i, d;
1191 for (i = d = 0; i < ARRAY_SIZE(Flags); i++)
1192 if (flags & (1 << i)) {
1193 buf[d++] = ' ';
1194 buf[d++] = '\\';
1195 for (s = Flags[i]; *s; s++)
1196 buf[d++] = *s;
1198 buf[0] = '(';
1199 buf[d++] = ')';
1200 return d;
1203 #define TUIDL 8
1205 static int imap_store_msg(struct store *gctx, struct msg_data *data, int *uid)
1207 struct imap_store *ctx = (struct imap_store *)gctx;
1208 struct imap *imap = ctx->imap;
1209 struct imap_cmd_cb cb;
1210 char *fmap, *buf;
1211 const char *prefix, *box;
1212 int ret, i, j, d, len, extra, nocr;
1213 int start, sbreak = 0, ebreak = 0;
1214 char flagstr[128], tuid[TUIDL * 2 + 1];
1216 memset(&cb, 0, sizeof(cb));
1218 fmap = data->data;
1219 len = data->len;
1220 nocr = !data->crlf;
1221 extra = 0, i = 0;
1222 if (!CAP(UIDPLUS) && uid) {
1223 nloop:
1224 start = i;
1225 while (i < len)
1226 if (fmap[i++] == '\n') {
1227 extra += nocr;
1228 if (i - 2 + nocr == start) {
1229 sbreak = ebreak = i - 2 + nocr;
1230 goto mktid;
1232 if (!memcmp(fmap + start, "X-TUID: ", 8)) {
1233 extra -= (ebreak = i) - (sbreak = start) + nocr;
1234 goto mktid;
1236 goto nloop;
1238 /* invalid message */
1239 free(fmap);
1240 return DRV_MSG_BAD;
1241 mktid:
1242 for (j = 0; j < TUIDL; j++)
1243 sprintf(tuid + j * 2, "%02x", arc4_getbyte());
1244 extra += 8 + TUIDL * 2 + 2;
1246 if (nocr)
1247 for (; i < len; i++)
1248 if (fmap[i] == '\n')
1249 extra++;
1251 cb.dlen = len + extra;
1252 buf = cb.data = xmalloc(cb.dlen);
1253 i = 0;
1254 if (!CAP(UIDPLUS) && uid) {
1255 if (nocr) {
1256 for (; i < sbreak; i++)
1257 if (fmap[i] == '\n') {
1258 *buf++ = '\r';
1259 *buf++ = '\n';
1260 } else
1261 *buf++ = fmap[i];
1262 } else {
1263 memcpy(buf, fmap, sbreak);
1264 buf += sbreak;
1266 memcpy(buf, "X-TUID: ", 8);
1267 buf += 8;
1268 memcpy(buf, tuid, TUIDL * 2);
1269 buf += TUIDL * 2;
1270 *buf++ = '\r';
1271 *buf++ = '\n';
1272 i = ebreak;
1274 if (nocr) {
1275 for (; i < len; i++)
1276 if (fmap[i] == '\n') {
1277 *buf++ = '\r';
1278 *buf++ = '\n';
1279 } else
1280 *buf++ = fmap[i];
1281 } else
1282 memcpy(buf, fmap + i, len - i);
1284 free(fmap);
1286 d = 0;
1287 if (data->flags) {
1288 d = imap_make_flags(data->flags, flagstr);
1289 flagstr[d++] = ' ';
1291 flagstr[d] = 0;
1293 if (!uid) {
1294 box = gctx->conf->trash;
1295 prefix = ctx->prefix;
1296 cb.create = 1;
1297 if (ctx->trashnc)
1298 imap->caps = imap->rcaps & ~(1 << LITERALPLUS);
1299 } else {
1300 box = gctx->name;
1301 prefix = !strcmp(box, "INBOX") ? "" : ctx->prefix;
1302 cb.create = 0;
1304 cb.ctx = uid;
1305 ret = imap_exec_m(ctx, &cb, "APPEND \"%s%s\" %s", prefix, box, flagstr);
1306 imap->caps = imap->rcaps;
1307 if (ret != DRV_OK)
1308 return ret;
1309 if (!uid)
1310 ctx->trashnc = 0;
1311 else
1312 gctx->count++;
1314 return DRV_OK;
1317 static void encode_html_chars(struct strbuf *p)
1319 int i;
1320 for (i = 0; i < p->len; i++) {
1321 if (p->buf[i] == '&')
1322 strbuf_splice(p, i, 1, "&amp;", 5);
1323 if (p->buf[i] == '<')
1324 strbuf_splice(p, i, 1, "&lt;", 4);
1325 if (p->buf[i] == '>')
1326 strbuf_splice(p, i, 1, "&gt;", 4);
1327 if (p->buf[i] == '"')
1328 strbuf_splice(p, i, 1, "&quot;", 6);
1331 static void wrap_in_html(struct msg_data *msg)
1333 struct strbuf buf = STRBUF_INIT;
1334 struct strbuf **lines;
1335 struct strbuf **p;
1336 static char *content_type = "Content-Type: text/html;\n";
1337 static char *pre_open = "<pre>\n";
1338 static char *pre_close = "</pre>\n";
1339 int added_header = 0;
1341 strbuf_attach(&buf, msg->data, msg->len, msg->len);
1342 lines = strbuf_split(&buf, '\n');
1343 strbuf_release(&buf);
1344 for (p = lines; *p; p++) {
1345 if (! added_header) {
1346 if ((*p)->len == 1 && *((*p)->buf) == '\n') {
1347 strbuf_addstr(&buf, content_type);
1348 strbuf_addbuf(&buf, *p);
1349 strbuf_addstr(&buf, pre_open);
1350 added_header = 1;
1351 continue;
1354 else
1355 encode_html_chars(*p);
1356 strbuf_addbuf(&buf, *p);
1358 strbuf_addstr(&buf, pre_close);
1359 strbuf_list_free(lines);
1360 msg->len = buf.len;
1361 msg->data = strbuf_detach(&buf, NULL);
1364 #define CHUNKSIZE 0x1000
1366 static int read_message(FILE *f, struct msg_data *msg)
1368 struct strbuf buf = STRBUF_INIT;
1370 memset(msg, 0, sizeof(*msg));
1372 do {
1373 if (strbuf_fread(&buf, CHUNKSIZE, f) <= 0)
1374 break;
1375 } while (!feof(f));
1377 msg->len = buf.len;
1378 msg->data = strbuf_detach(&buf, NULL);
1379 return msg->len;
1382 static int count_messages(struct msg_data *msg)
1384 int count = 0;
1385 char *p = msg->data;
1387 while (1) {
1388 if (!prefixcmp(p, "From ")) {
1389 count++;
1390 p += 5;
1392 p = strstr(p+5, "\nFrom ");
1393 if (!p)
1394 break;
1395 p++;
1397 return count;
1400 static int split_msg(struct msg_data *all_msgs, struct msg_data *msg, int *ofs)
1402 char *p, *data;
1404 memset(msg, 0, sizeof *msg);
1405 if (*ofs >= all_msgs->len)
1406 return 0;
1408 data = &all_msgs->data[*ofs];
1409 msg->len = all_msgs->len - *ofs;
1411 if (msg->len < 5 || prefixcmp(data, "From "))
1412 return 0;
1414 p = strchr(data, '\n');
1415 if (p) {
1416 p = &p[1];
1417 msg->len -= p-data;
1418 *ofs += p-data;
1419 data = p;
1422 p = strstr(data, "\nFrom ");
1423 if (p)
1424 msg->len = &p[1] - data;
1426 msg->data = xmemdupz(data, msg->len);
1427 *ofs += msg->len;
1428 return 1;
1431 static struct imap_server_conf server = {
1432 NULL, /* name */
1433 NULL, /* tunnel */
1434 NULL, /* host */
1435 0, /* port */
1436 NULL, /* user */
1437 NULL, /* pass */
1438 0, /* use_ssl */
1439 1, /* ssl_verify */
1440 0, /* use_html */
1443 static char *imap_folder;
1445 static int git_imap_config(const char *key, const char *val, void *cb)
1447 char imap_key[] = "imap.";
1449 if (strncmp(key, imap_key, sizeof imap_key - 1))
1450 return 0;
1452 if (!val)
1453 return config_error_nonbool(key);
1455 key += sizeof imap_key - 1;
1457 if (!strcmp("folder", key)) {
1458 imap_folder = xstrdup(val);
1459 } else if (!strcmp("host", key)) {
1460 if (!prefixcmp(val, "imap:"))
1461 val += 5;
1462 else if (!prefixcmp(val, "imaps:")) {
1463 val += 6;
1464 server.use_ssl = 1;
1466 if (!prefixcmp(val, "//"))
1467 val += 2;
1468 server.host = xstrdup(val);
1469 } else if (!strcmp("user", key))
1470 server.user = xstrdup(val);
1471 else if (!strcmp("pass", key))
1472 server.pass = xstrdup(val);
1473 else if (!strcmp("port", key))
1474 server.port = git_config_int(key, val);
1475 else if (!strcmp("tunnel", key))
1476 server.tunnel = xstrdup(val);
1477 else if (!strcmp("sslverify", key))
1478 server.ssl_verify = git_config_bool(key, val);
1479 else if (!strcmp("preformattedHTML", key))
1480 server.use_html = git_config_bool(key, val);
1481 return 0;
1484 int main(int argc, char **argv)
1486 struct msg_data all_msgs, msg;
1487 struct store *ctx = NULL;
1488 int uid = 0;
1489 int ofs = 0;
1490 int r;
1491 int total, n = 0;
1492 int nongit_ok;
1494 git_extract_argv0_path(argv[0]);
1496 if (argc != 1)
1497 usage(imap_send_usage);
1499 /* init the random number generator */
1500 arc4_init();
1502 setup_git_directory_gently(&nongit_ok);
1503 git_config(git_imap_config, NULL);
1505 if (!server.port)
1506 server.port = server.use_ssl ? 993 : 143;
1508 if (!imap_folder) {
1509 fprintf(stderr, "no imap store specified\n");
1510 return 1;
1512 if (!server.host) {
1513 if (!server.tunnel) {
1514 fprintf(stderr, "no imap host specified\n");
1515 return 1;
1517 server.host = "tunnel";
1520 /* read the messages */
1521 if (!read_message(stdin, &all_msgs)) {
1522 fprintf(stderr, "nothing to send\n");
1523 return 1;
1526 total = count_messages(&all_msgs);
1527 if (!total) {
1528 fprintf(stderr, "no messages to send\n");
1529 return 1;
1532 /* write it to the imap server */
1533 ctx = imap_open_store(&server);
1534 if (!ctx) {
1535 fprintf(stderr, "failed to open store\n");
1536 return 1;
1539 fprintf(stderr, "sending %d message%s\n", total, (total != 1) ? "s" : "");
1540 ctx->name = imap_folder;
1541 while (1) {
1542 unsigned percent = n * 100 / total;
1543 fprintf(stderr, "%4u%% (%d/%d) done\r", percent, n, total);
1544 if (!split_msg(&all_msgs, &msg, &ofs))
1545 break;
1546 if (server.use_html)
1547 wrap_in_html(&msg);
1548 r = imap_store_msg(ctx, &msg, &uid);
1549 if (r != DRV_OK)
1550 break;
1551 n++;
1553 fprintf(stderr, "\n");
1555 imap_close_store(ctx);
1557 return 0;