Smart-http tests: Improve coverage in test t5560
[git/jnareb-git.git] / imap-send.c
blobde8114bac010ef095cf9de17671566e248366dcb
1 /*
2 * git-imap-send - drops patches into an imap Drafts folder
3 * derived from isync/mbsync - mailbox synchronizer
5 * Copyright (C) 2000-2002 Michael R. Elkins <me@mutt.org>
6 * Copyright (C) 2002-2004 Oswald Buddenhagen <ossi@users.sf.net>
7 * Copyright (C) 2004 Theodore Y. Ts'o <tytso@mit.edu>
8 * Copyright (C) 2006 Mike McCormack
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, write to the Free Software
22 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 #include "cache.h"
26 #include "exec_cmd.h"
27 #include "run-command.h"
28 #ifdef NO_OPENSSL
29 typedef void *SSL;
30 #endif
32 struct store_conf {
33 char *name;
34 const char *path; /* should this be here? its interpretation is driver-specific */
35 char *map_inbox;
36 char *trash;
37 unsigned max_size; /* off_t is overkill */
38 unsigned trash_remote_new:1, trash_only_new:1;
41 struct string_list {
42 struct string_list *next;
43 char string[1];
46 struct channel_conf {
47 struct channel_conf *next;
48 char *name;
49 struct store_conf *master, *slave;
50 char *master_name, *slave_name;
51 char *sync_state;
52 struct string_list *patterns;
53 int mops, sops;
54 unsigned max_messages; /* for slave only */
57 struct group_conf {
58 struct group_conf *next;
59 char *name;
60 struct string_list *channels;
63 /* For message->status */
64 #define M_RECENT (1<<0) /* unsyncable flag; maildir_* depend on this being 1<<0 */
65 #define M_DEAD (1<<1) /* expunged */
66 #define M_FLAGS (1<<2) /* flags fetched */
68 struct message {
69 struct message *next;
70 /* struct string_list *keywords; */
71 size_t size; /* zero implies "not fetched" */
72 int uid;
73 unsigned char flags, status;
76 struct store {
77 struct store_conf *conf; /* foreign */
79 /* currently open mailbox */
80 const char *name; /* foreign! maybe preset? */
81 char *path; /* own */
82 struct message *msgs; /* own */
83 int uidvalidity;
84 unsigned char opts; /* maybe preset? */
85 /* note that the following do _not_ reflect stats from msgs, but mailbox totals */
86 int count; /* # of messages */
87 int recent; /* # of recent messages - don't trust this beyond the initial read */
90 struct msg_data {
91 char *data;
92 int len;
93 unsigned char flags;
94 unsigned int crlf:1;
97 static const char imap_send_usage[] = "git imap-send < <mbox>";
99 #undef DRV_OK
100 #define DRV_OK 0
101 #define DRV_MSG_BAD -1
102 #define DRV_BOX_BAD -2
103 #define DRV_STORE_BAD -3
105 static int Verbose, Quiet;
107 __attribute__((format (printf, 1, 2)))
108 static void imap_info(const char *, ...);
109 __attribute__((format (printf, 1, 2)))
110 static void imap_warn(const char *, ...);
112 static char *next_arg(char **);
114 static void free_generic_messages(struct message *);
116 __attribute__((format (printf, 3, 4)))
117 static int nfsnprintf(char *buf, int blen, const char *fmt, ...);
119 static int nfvasprintf(char **strp, const char *fmt, va_list ap)
121 int len;
122 char tmp[8192];
124 len = vsnprintf(tmp, sizeof(tmp), fmt, ap);
125 if (len < 0)
126 die("Fatal: Out of memory");
127 if (len >= sizeof(tmp))
128 die("imap command overflow!");
129 *strp = xmemdupz(tmp, len);
130 return len;
133 struct imap_server_conf {
134 char *name;
135 char *tunnel;
136 char *host;
137 int port;
138 char *user;
139 char *pass;
140 int use_ssl;
141 int ssl_verify;
142 int use_html;
145 struct imap_store_conf {
146 struct store_conf gen;
147 struct imap_server_conf *server;
148 unsigned use_namespace:1;
151 #define NIL (void *)0x1
152 #define LIST (void *)0x2
154 struct imap_list {
155 struct imap_list *next, *child;
156 char *val;
157 int len;
160 struct imap_socket {
161 int fd[2];
162 SSL *ssl;
165 struct imap_buffer {
166 struct imap_socket sock;
167 int bytes;
168 int offset;
169 char buf[1024];
172 struct imap_cmd;
174 struct imap {
175 int uidnext; /* from SELECT responses */
176 struct imap_list *ns_personal, *ns_other, *ns_shared; /* NAMESPACE info */
177 unsigned caps, rcaps; /* CAPABILITY results */
178 /* command queue */
179 int nexttag, num_in_progress, literal_pending;
180 struct imap_cmd *in_progress, **in_progress_append;
181 struct imap_buffer buf; /* this is BIG, so put it last */
184 struct imap_store {
185 struct store gen;
186 int uidvalidity;
187 struct imap *imap;
188 const char *prefix;
189 unsigned /*currentnc:1,*/ trashnc:1;
192 struct imap_cmd_cb {
193 int (*cont)(struct imap_store *ctx, struct imap_cmd *cmd, const char *prompt);
194 void (*done)(struct imap_store *ctx, struct imap_cmd *cmd, int response);
195 void *ctx;
196 char *data;
197 int dlen;
198 int uid;
199 unsigned create:1, trycreate:1;
202 struct imap_cmd {
203 struct imap_cmd *next;
204 struct imap_cmd_cb cb;
205 char *cmd;
206 int tag;
209 #define CAP(cap) (imap->caps & (1 << (cap)))
211 enum CAPABILITY {
212 NOLOGIN = 0,
213 UIDPLUS,
214 LITERALPLUS,
215 NAMESPACE,
216 STARTTLS,
219 static const char *cap_list[] = {
220 "LOGINDISABLED",
221 "UIDPLUS",
222 "LITERAL+",
223 "NAMESPACE",
224 "STARTTLS",
227 #define RESP_OK 0
228 #define RESP_NO 1
229 #define RESP_BAD 2
231 static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd);
234 static const char *Flags[] = {
235 "Draft",
236 "Flagged",
237 "Answered",
238 "Seen",
239 "Deleted",
242 #ifndef NO_OPENSSL
243 static void ssl_socket_perror(const char *func)
245 fprintf(stderr, "%s: %s\n", func, ERR_error_string(ERR_get_error(), NULL));
247 #endif
249 static void socket_perror(const char *func, struct imap_socket *sock, int ret)
251 #ifndef NO_OPENSSL
252 if (sock->ssl) {
253 int sslerr = SSL_get_error(sock->ssl, ret);
254 switch (sslerr) {
255 case SSL_ERROR_NONE:
256 break;
257 case SSL_ERROR_SYSCALL:
258 perror("SSL_connect");
259 break;
260 default:
261 ssl_socket_perror("SSL_connect");
262 break;
264 } else
265 #endif
267 if (ret < 0)
268 perror(func);
269 else
270 fprintf(stderr, "%s: unexpected EOF\n", func);
274 static int ssl_socket_connect(struct imap_socket *sock, int use_tls_only, int verify)
276 #ifdef NO_OPENSSL
277 fprintf(stderr, "SSL requested but SSL support not compiled in\n");
278 return -1;
279 #else
280 #if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
281 const SSL_METHOD *meth;
282 #else
283 SSL_METHOD *meth;
284 #endif
285 SSL_CTX *ctx;
286 int ret;
288 SSL_library_init();
289 SSL_load_error_strings();
291 if (use_tls_only)
292 meth = TLSv1_method();
293 else
294 meth = SSLv23_method();
296 if (!meth) {
297 ssl_socket_perror("SSLv23_method");
298 return -1;
301 ctx = SSL_CTX_new(meth);
303 if (verify)
304 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
306 if (!SSL_CTX_set_default_verify_paths(ctx)) {
307 ssl_socket_perror("SSL_CTX_set_default_verify_paths");
308 return -1;
310 sock->ssl = SSL_new(ctx);
311 if (!sock->ssl) {
312 ssl_socket_perror("SSL_new");
313 return -1;
315 if (!SSL_set_rfd(sock->ssl, sock->fd[0])) {
316 ssl_socket_perror("SSL_set_rfd");
317 return -1;
319 if (!SSL_set_wfd(sock->ssl, sock->fd[1])) {
320 ssl_socket_perror("SSL_set_wfd");
321 return -1;
324 ret = SSL_connect(sock->ssl);
325 if (ret <= 0) {
326 socket_perror("SSL_connect", sock, ret);
327 return -1;
330 return 0;
331 #endif
334 static int socket_read(struct imap_socket *sock, char *buf, int len)
336 ssize_t n;
337 #ifndef NO_OPENSSL
338 if (sock->ssl)
339 n = SSL_read(sock->ssl, buf, len);
340 else
341 #endif
342 n = xread(sock->fd[0], buf, len);
343 if (n <= 0) {
344 socket_perror("read", sock, n);
345 close(sock->fd[0]);
346 close(sock->fd[1]);
347 sock->fd[0] = sock->fd[1] = -1;
349 return n;
352 static int socket_write(struct imap_socket *sock, const char *buf, int len)
354 int n;
355 #ifndef NO_OPENSSL
356 if (sock->ssl)
357 n = SSL_write(sock->ssl, buf, len);
358 else
359 #endif
360 n = write_in_full(sock->fd[1], buf, len);
361 if (n != len) {
362 socket_perror("write", sock, n);
363 close(sock->fd[0]);
364 close(sock->fd[1]);
365 sock->fd[0] = sock->fd[1] = -1;
367 return n;
370 static void socket_shutdown(struct imap_socket *sock)
372 #ifndef NO_OPENSSL
373 if (sock->ssl) {
374 SSL_shutdown(sock->ssl);
375 SSL_free(sock->ssl);
377 #endif
378 close(sock->fd[0]);
379 close(sock->fd[1]);
382 /* simple line buffering */
383 static int buffer_gets(struct imap_buffer *b, char **s)
385 int n;
386 int start = b->offset;
388 *s = b->buf + start;
390 for (;;) {
391 /* make sure we have enough data to read the \r\n sequence */
392 if (b->offset + 1 >= b->bytes) {
393 if (start) {
394 /* shift down used bytes */
395 *s = b->buf;
397 assert(start <= b->bytes);
398 n = b->bytes - start;
400 if (n)
401 memmove(b->buf, b->buf + start, n);
402 b->offset -= start;
403 b->bytes = n;
404 start = 0;
407 n = socket_read(&b->sock, b->buf + b->bytes,
408 sizeof(b->buf) - b->bytes);
410 if (n <= 0)
411 return -1;
413 b->bytes += n;
416 if (b->buf[b->offset] == '\r') {
417 assert(b->offset + 1 < b->bytes);
418 if (b->buf[b->offset + 1] == '\n') {
419 b->buf[b->offset] = 0; /* terminate the string */
420 b->offset += 2; /* next line */
421 if (Verbose)
422 puts(*s);
423 return 0;
427 b->offset++;
429 /* not reached */
432 static void imap_info(const char *msg, ...)
434 va_list va;
436 if (!Quiet) {
437 va_start(va, msg);
438 vprintf(msg, va);
439 va_end(va);
440 fflush(stdout);
444 static void imap_warn(const char *msg, ...)
446 va_list va;
448 if (Quiet < 2) {
449 va_start(va, msg);
450 vfprintf(stderr, msg, va);
451 va_end(va);
455 static char *next_arg(char **s)
457 char *ret;
459 if (!s || !*s)
460 return NULL;
461 while (isspace((unsigned char) **s))
462 (*s)++;
463 if (!**s) {
464 *s = NULL;
465 return NULL;
467 if (**s == '"') {
468 ++*s;
469 ret = *s;
470 *s = strchr(*s, '"');
471 } else {
472 ret = *s;
473 while (**s && !isspace((unsigned char) **s))
474 (*s)++;
476 if (*s) {
477 if (**s)
478 *(*s)++ = 0;
479 if (!**s)
480 *s = NULL;
482 return ret;
485 static void free_generic_messages(struct message *msgs)
487 struct message *tmsg;
489 for (; msgs; msgs = tmsg) {
490 tmsg = msgs->next;
491 free(msgs);
495 static int nfsnprintf(char *buf, int blen, const char *fmt, ...)
497 int ret;
498 va_list va;
500 va_start(va, fmt);
501 if (blen <= 0 || (unsigned)(ret = vsnprintf(buf, blen, fmt, va)) >= (unsigned)blen)
502 die("Fatal: buffer too small. Please report a bug.");
503 va_end(va);
504 return ret;
507 static struct imap_cmd *v_issue_imap_cmd(struct imap_store *ctx,
508 struct imap_cmd_cb *cb,
509 const char *fmt, va_list ap)
511 struct imap *imap = ctx->imap;
512 struct imap_cmd *cmd;
513 int n, bufl;
514 char buf[1024];
516 cmd = xmalloc(sizeof(struct imap_cmd));
517 nfvasprintf(&cmd->cmd, fmt, ap);
518 cmd->tag = ++imap->nexttag;
520 if (cb)
521 cmd->cb = *cb;
522 else
523 memset(&cmd->cb, 0, sizeof(cmd->cb));
525 while (imap->literal_pending)
526 get_cmd_result(ctx, NULL);
528 bufl = nfsnprintf(buf, sizeof(buf), cmd->cb.data ? CAP(LITERALPLUS) ?
529 "%d %s{%d+}\r\n" : "%d %s{%d}\r\n" : "%d %s\r\n",
530 cmd->tag, cmd->cmd, cmd->cb.dlen);
531 if (Verbose) {
532 if (imap->num_in_progress)
533 printf("(%d in progress) ", imap->num_in_progress);
534 if (memcmp(cmd->cmd, "LOGIN", 5))
535 printf(">>> %s", buf);
536 else
537 printf(">>> %d LOGIN <user> <pass>\n", cmd->tag);
539 if (socket_write(&imap->buf.sock, buf, bufl) != bufl) {
540 free(cmd->cmd);
541 free(cmd);
542 if (cb)
543 free(cb->data);
544 return NULL;
546 if (cmd->cb.data) {
547 if (CAP(LITERALPLUS)) {
548 n = socket_write(&imap->buf.sock, cmd->cb.data, cmd->cb.dlen);
549 free(cmd->cb.data);
550 if (n != cmd->cb.dlen ||
551 socket_write(&imap->buf.sock, "\r\n", 2) != 2) {
552 free(cmd->cmd);
553 free(cmd);
554 return NULL;
556 cmd->cb.data = NULL;
557 } else
558 imap->literal_pending = 1;
559 } else if (cmd->cb.cont)
560 imap->literal_pending = 1;
561 cmd->next = NULL;
562 *imap->in_progress_append = cmd;
563 imap->in_progress_append = &cmd->next;
564 imap->num_in_progress++;
565 return cmd;
568 __attribute__((format (printf, 3, 4)))
569 static struct imap_cmd *issue_imap_cmd(struct imap_store *ctx,
570 struct imap_cmd_cb *cb,
571 const char *fmt, ...)
573 struct imap_cmd *ret;
574 va_list ap;
576 va_start(ap, fmt);
577 ret = v_issue_imap_cmd(ctx, cb, fmt, ap);
578 va_end(ap);
579 return ret;
582 __attribute__((format (printf, 3, 4)))
583 static int imap_exec(struct imap_store *ctx, struct imap_cmd_cb *cb,
584 const char *fmt, ...)
586 va_list ap;
587 struct imap_cmd *cmdp;
589 va_start(ap, fmt);
590 cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
591 va_end(ap);
592 if (!cmdp)
593 return RESP_BAD;
595 return get_cmd_result(ctx, cmdp);
598 __attribute__((format (printf, 3, 4)))
599 static int imap_exec_m(struct imap_store *ctx, struct imap_cmd_cb *cb,
600 const char *fmt, ...)
602 va_list ap;
603 struct imap_cmd *cmdp;
605 va_start(ap, fmt);
606 cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
607 va_end(ap);
608 if (!cmdp)
609 return DRV_STORE_BAD;
611 switch (get_cmd_result(ctx, cmdp)) {
612 case RESP_BAD: return DRV_STORE_BAD;
613 case RESP_NO: return DRV_MSG_BAD;
614 default: return DRV_OK;
618 static int is_atom(struct imap_list *list)
620 return list && list->val && list->val != NIL && list->val != LIST;
623 static int is_list(struct imap_list *list)
625 return list && list->val == LIST;
628 static void free_list(struct imap_list *list)
630 struct imap_list *tmp;
632 for (; list; list = tmp) {
633 tmp = list->next;
634 if (is_list(list))
635 free_list(list->child);
636 else if (is_atom(list))
637 free(list->val);
638 free(list);
642 static int parse_imap_list_l(struct imap *imap, char **sp, struct imap_list **curp, int level)
644 struct imap_list *cur;
645 char *s = *sp, *p;
646 int n, bytes;
648 for (;;) {
649 while (isspace((unsigned char)*s))
650 s++;
651 if (level && *s == ')') {
652 s++;
653 break;
655 *curp = cur = xmalloc(sizeof(*cur));
656 curp = &cur->next;
657 cur->val = NULL; /* for clean bail */
658 if (*s == '(') {
659 /* sublist */
660 s++;
661 cur->val = LIST;
662 if (parse_imap_list_l(imap, &s, &cur->child, level + 1))
663 goto bail;
664 } else if (imap && *s == '{') {
665 /* literal */
666 bytes = cur->len = strtol(s + 1, &s, 10);
667 if (*s != '}')
668 goto bail;
670 s = cur->val = xmalloc(cur->len);
672 /* dump whats left over in the input buffer */
673 n = imap->buf.bytes - imap->buf.offset;
675 if (n > bytes)
676 /* the entire message fit in the buffer */
677 n = bytes;
679 memcpy(s, imap->buf.buf + imap->buf.offset, n);
680 s += n;
681 bytes -= n;
683 /* mark that we used part of the buffer */
684 imap->buf.offset += n;
686 /* now read the rest of the message */
687 while (bytes > 0) {
688 if ((n = socket_read(&imap->buf.sock, s, bytes)) <= 0)
689 goto bail;
690 s += n;
691 bytes -= n;
694 if (buffer_gets(&imap->buf, &s))
695 goto bail;
696 } else if (*s == '"') {
697 /* quoted string */
698 s++;
699 p = s;
700 for (; *s != '"'; s++)
701 if (!*s)
702 goto bail;
703 cur->len = s - p;
704 s++;
705 cur->val = xmemdupz(p, cur->len);
706 } else {
707 /* atom */
708 p = s;
709 for (; *s && !isspace((unsigned char)*s); s++)
710 if (level && *s == ')')
711 break;
712 cur->len = s - p;
713 if (cur->len == 3 && !memcmp("NIL", p, 3))
714 cur->val = NIL;
715 else
716 cur->val = xmemdupz(p, cur->len);
719 if (!level)
720 break;
721 if (!*s)
722 goto bail;
724 *sp = s;
725 *curp = NULL;
726 return 0;
728 bail:
729 *curp = NULL;
730 return -1;
733 static struct imap_list *parse_imap_list(struct imap *imap, char **sp)
735 struct imap_list *head;
737 if (!parse_imap_list_l(imap, sp, &head, 0))
738 return head;
739 free_list(head);
740 return NULL;
743 static struct imap_list *parse_list(char **sp)
745 return parse_imap_list(NULL, sp);
748 static void parse_capability(struct imap *imap, char *cmd)
750 char *arg;
751 unsigned i;
753 imap->caps = 0x80000000;
754 while ((arg = next_arg(&cmd)))
755 for (i = 0; i < ARRAY_SIZE(cap_list); i++)
756 if (!strcmp(cap_list[i], arg))
757 imap->caps |= 1 << i;
758 imap->rcaps = imap->caps;
761 static int parse_response_code(struct imap_store *ctx, struct imap_cmd_cb *cb,
762 char *s)
764 struct imap *imap = ctx->imap;
765 char *arg, *p;
767 if (*s != '[')
768 return RESP_OK; /* no response code */
769 s++;
770 if (!(p = strchr(s, ']'))) {
771 fprintf(stderr, "IMAP error: malformed response code\n");
772 return RESP_BAD;
774 *p++ = 0;
775 arg = next_arg(&s);
776 if (!strcmp("UIDVALIDITY", arg)) {
777 if (!(arg = next_arg(&s)) || !(ctx->gen.uidvalidity = atoi(arg))) {
778 fprintf(stderr, "IMAP error: malformed UIDVALIDITY status\n");
779 return RESP_BAD;
781 } else if (!strcmp("UIDNEXT", arg)) {
782 if (!(arg = next_arg(&s)) || !(imap->uidnext = atoi(arg))) {
783 fprintf(stderr, "IMAP error: malformed NEXTUID status\n");
784 return RESP_BAD;
786 } else if (!strcmp("CAPABILITY", arg)) {
787 parse_capability(imap, s);
788 } else if (!strcmp("ALERT", arg)) {
789 /* RFC2060 says that these messages MUST be displayed
790 * to the user
792 for (; isspace((unsigned char)*p); p++);
793 fprintf(stderr, "*** IMAP ALERT *** %s\n", p);
794 } else if (cb && cb->ctx && !strcmp("APPENDUID", arg)) {
795 if (!(arg = next_arg(&s)) || !(ctx->gen.uidvalidity = atoi(arg)) ||
796 !(arg = next_arg(&s)) || !(*(int *)cb->ctx = atoi(arg))) {
797 fprintf(stderr, "IMAP error: malformed APPENDUID status\n");
798 return RESP_BAD;
801 return RESP_OK;
804 static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd)
806 struct imap *imap = ctx->imap;
807 struct imap_cmd *cmdp, **pcmdp, *ncmdp;
808 char *cmd, *arg, *arg1, *p;
809 int n, resp, resp2, tag;
811 for (;;) {
812 if (buffer_gets(&imap->buf, &cmd))
813 return RESP_BAD;
815 arg = next_arg(&cmd);
816 if (*arg == '*') {
817 arg = next_arg(&cmd);
818 if (!arg) {
819 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
820 return RESP_BAD;
823 if (!strcmp("NAMESPACE", arg)) {
824 imap->ns_personal = parse_list(&cmd);
825 imap->ns_other = parse_list(&cmd);
826 imap->ns_shared = parse_list(&cmd);
827 } else if (!strcmp("OK", arg) || !strcmp("BAD", arg) ||
828 !strcmp("NO", arg) || !strcmp("BYE", arg)) {
829 if ((resp = parse_response_code(ctx, NULL, cmd)) != RESP_OK)
830 return resp;
831 } else if (!strcmp("CAPABILITY", arg))
832 parse_capability(imap, cmd);
833 else if ((arg1 = next_arg(&cmd))) {
834 if (!strcmp("EXISTS", arg1))
835 ctx->gen.count = atoi(arg);
836 else if (!strcmp("RECENT", arg1))
837 ctx->gen.recent = atoi(arg);
838 } else {
839 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
840 return RESP_BAD;
842 } else if (!imap->in_progress) {
843 fprintf(stderr, "IMAP error: unexpected reply: %s %s\n", arg, cmd ? cmd : "");
844 return RESP_BAD;
845 } else if (*arg == '+') {
846 /* This can happen only with the last command underway, as
847 it enforces a round-trip. */
848 cmdp = (struct imap_cmd *)((char *)imap->in_progress_append -
849 offsetof(struct imap_cmd, next));
850 if (cmdp->cb.data) {
851 n = socket_write(&imap->buf.sock, cmdp->cb.data, cmdp->cb.dlen);
852 free(cmdp->cb.data);
853 cmdp->cb.data = NULL;
854 if (n != (int)cmdp->cb.dlen)
855 return RESP_BAD;
856 } else if (cmdp->cb.cont) {
857 if (cmdp->cb.cont(ctx, cmdp, cmd))
858 return RESP_BAD;
859 } else {
860 fprintf(stderr, "IMAP error: unexpected command continuation request\n");
861 return RESP_BAD;
863 if (socket_write(&imap->buf.sock, "\r\n", 2) != 2)
864 return RESP_BAD;
865 if (!cmdp->cb.cont)
866 imap->literal_pending = 0;
867 if (!tcmd)
868 return DRV_OK;
869 } else {
870 tag = atoi(arg);
871 for (pcmdp = &imap->in_progress; (cmdp = *pcmdp); pcmdp = &cmdp->next)
872 if (cmdp->tag == tag)
873 goto gottag;
874 fprintf(stderr, "IMAP error: unexpected tag %s\n", arg);
875 return RESP_BAD;
876 gottag:
877 if (!(*pcmdp = cmdp->next))
878 imap->in_progress_append = pcmdp;
879 imap->num_in_progress--;
880 if (cmdp->cb.cont || cmdp->cb.data)
881 imap->literal_pending = 0;
882 arg = next_arg(&cmd);
883 if (!strcmp("OK", arg))
884 resp = DRV_OK;
885 else {
886 if (!strcmp("NO", arg)) {
887 if (cmdp->cb.create && cmd && (cmdp->cb.trycreate || !memcmp(cmd, "[TRYCREATE]", 11))) { /* SELECT, APPEND or UID COPY */
888 p = strchr(cmdp->cmd, '"');
889 if (!issue_imap_cmd(ctx, NULL, "CREATE \"%.*s\"", (int)(strchr(p + 1, '"') - p + 1), p)) {
890 resp = RESP_BAD;
891 goto normal;
893 /* not waiting here violates the spec, but a server that does not
894 grok this nonetheless violates it too. */
895 cmdp->cb.create = 0;
896 if (!(ncmdp = issue_imap_cmd(ctx, &cmdp->cb, "%s", cmdp->cmd))) {
897 resp = RESP_BAD;
898 goto normal;
900 free(cmdp->cmd);
901 free(cmdp);
902 if (!tcmd)
903 return 0; /* ignored */
904 if (cmdp == tcmd)
905 tcmd = ncmdp;
906 continue;
908 resp = RESP_NO;
909 } else /*if (!strcmp("BAD", arg))*/
910 resp = RESP_BAD;
911 fprintf(stderr, "IMAP command '%s' returned response (%s) - %s\n",
912 memcmp(cmdp->cmd, "LOGIN", 5) ?
913 cmdp->cmd : "LOGIN <user> <pass>",
914 arg, cmd ? cmd : "");
916 if ((resp2 = parse_response_code(ctx, &cmdp->cb, cmd)) > resp)
917 resp = resp2;
918 normal:
919 if (cmdp->cb.done)
920 cmdp->cb.done(ctx, cmdp, resp);
921 free(cmdp->cb.data);
922 free(cmdp->cmd);
923 free(cmdp);
924 if (!tcmd || tcmd == cmdp)
925 return resp;
928 /* not reached */
931 static void imap_close_server(struct imap_store *ictx)
933 struct imap *imap = ictx->imap;
935 if (imap->buf.sock.fd[0] != -1) {
936 imap_exec(ictx, NULL, "LOGOUT");
937 socket_shutdown(&imap->buf.sock);
939 free_list(imap->ns_personal);
940 free_list(imap->ns_other);
941 free_list(imap->ns_shared);
942 free(imap);
945 static void imap_close_store(struct store *ctx)
947 imap_close_server((struct imap_store *)ctx);
948 free_generic_messages(ctx->msgs);
949 free(ctx);
952 static struct store *imap_open_store(struct imap_server_conf *srvc)
954 struct imap_store *ctx;
955 struct imap *imap;
956 char *arg, *rsp;
957 int s = -1, preauth;
959 ctx = xcalloc(sizeof(*ctx), 1);
961 ctx->imap = imap = xcalloc(sizeof(*imap), 1);
962 imap->buf.sock.fd[0] = imap->buf.sock.fd[1] = -1;
963 imap->in_progress_append = &imap->in_progress;
965 /* open connection to IMAP server */
967 if (srvc->tunnel) {
968 const char *argv[4];
969 struct child_process tunnel = {0};
971 imap_info("Starting tunnel '%s'... ", srvc->tunnel);
973 argv[0] = "sh";
974 argv[1] = "-c";
975 argv[2] = srvc->tunnel;
976 argv[3] = NULL;
978 tunnel.argv = argv;
979 tunnel.in = -1;
980 tunnel.out = -1;
981 if (start_command(&tunnel))
982 die("cannot start proxy %s", argv[0]);
984 imap->buf.sock.fd[0] = tunnel.out;
985 imap->buf.sock.fd[1] = tunnel.in;
987 imap_info("ok\n");
988 } else {
989 #ifndef NO_IPV6
990 struct addrinfo hints, *ai0, *ai;
991 int gai;
992 char portstr[6];
994 snprintf(portstr, sizeof(portstr), "%hu", srvc->port);
996 memset(&hints, 0, sizeof(hints));
997 hints.ai_socktype = SOCK_STREAM;
998 hints.ai_protocol = IPPROTO_TCP;
1000 imap_info("Resolving %s... ", srvc->host);
1001 gai = getaddrinfo(srvc->host, portstr, &hints, &ai);
1002 if (gai) {
1003 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai));
1004 goto bail;
1006 imap_info("ok\n");
1008 for (ai0 = ai; ai; ai = ai->ai_next) {
1009 char addr[NI_MAXHOST];
1011 s = socket(ai->ai_family, ai->ai_socktype,
1012 ai->ai_protocol);
1013 if (s < 0)
1014 continue;
1016 getnameinfo(ai->ai_addr, ai->ai_addrlen, addr,
1017 sizeof(addr), NULL, 0, NI_NUMERICHOST);
1018 imap_info("Connecting to [%s]:%s... ", addr, portstr);
1020 if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0) {
1021 close(s);
1022 s = -1;
1023 perror("connect");
1024 continue;
1027 break;
1029 freeaddrinfo(ai0);
1030 #else /* NO_IPV6 */
1031 struct hostent *he;
1032 struct sockaddr_in addr;
1034 memset(&addr, 0, sizeof(addr));
1035 addr.sin_port = htons(srvc->port);
1036 addr.sin_family = AF_INET;
1038 imap_info("Resolving %s... ", srvc->host);
1039 he = gethostbyname(srvc->host);
1040 if (!he) {
1041 perror("gethostbyname");
1042 goto bail;
1044 imap_info("ok\n");
1046 addr.sin_addr.s_addr = *((int *) he->h_addr_list[0]);
1048 s = socket(PF_INET, SOCK_STREAM, 0);
1050 imap_info("Connecting to %s:%hu... ", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
1051 if (connect(s, (struct sockaddr *)&addr, sizeof(addr))) {
1052 close(s);
1053 s = -1;
1054 perror("connect");
1056 #endif
1057 if (s < 0) {
1058 fputs("Error: unable to connect to server.\n", stderr);
1059 goto bail;
1062 imap->buf.sock.fd[0] = s;
1063 imap->buf.sock.fd[1] = dup(s);
1065 if (srvc->use_ssl &&
1066 ssl_socket_connect(&imap->buf.sock, 0, srvc->ssl_verify)) {
1067 close(s);
1068 goto bail;
1070 imap_info("ok\n");
1073 /* read the greeting string */
1074 if (buffer_gets(&imap->buf, &rsp)) {
1075 fprintf(stderr, "IMAP error: no greeting response\n");
1076 goto bail;
1078 arg = next_arg(&rsp);
1079 if (!arg || *arg != '*' || (arg = next_arg(&rsp)) == NULL) {
1080 fprintf(stderr, "IMAP error: invalid greeting response\n");
1081 goto bail;
1083 preauth = 0;
1084 if (!strcmp("PREAUTH", arg))
1085 preauth = 1;
1086 else if (strcmp("OK", arg) != 0) {
1087 fprintf(stderr, "IMAP error: unknown greeting response\n");
1088 goto bail;
1090 parse_response_code(ctx, NULL, rsp);
1091 if (!imap->caps && imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1092 goto bail;
1094 if (!preauth) {
1095 #ifndef NO_OPENSSL
1096 if (!srvc->use_ssl && CAP(STARTTLS)) {
1097 if (imap_exec(ctx, 0, "STARTTLS") != RESP_OK)
1098 goto bail;
1099 if (ssl_socket_connect(&imap->buf.sock, 1,
1100 srvc->ssl_verify))
1101 goto bail;
1102 /* capabilities may have changed, so get the new capabilities */
1103 if (imap_exec(ctx, 0, "CAPABILITY") != RESP_OK)
1104 goto bail;
1106 #endif
1107 imap_info("Logging in...\n");
1108 if (!srvc->user) {
1109 fprintf(stderr, "Skipping server %s, no user\n", srvc->host);
1110 goto bail;
1112 if (!srvc->pass) {
1113 char prompt[80];
1114 sprintf(prompt, "Password (%s@%s): ", srvc->user, srvc->host);
1115 arg = getpass(prompt);
1116 if (!arg) {
1117 perror("getpass");
1118 exit(1);
1120 if (!*arg) {
1121 fprintf(stderr, "Skipping account %s@%s, no password\n", srvc->user, srvc->host);
1122 goto bail;
1125 * getpass() returns a pointer to a static buffer. make a copy
1126 * for long term storage.
1128 srvc->pass = xstrdup(arg);
1130 if (CAP(NOLOGIN)) {
1131 fprintf(stderr, "Skipping account %s@%s, server forbids LOGIN\n", srvc->user, srvc->host);
1132 goto bail;
1134 if (!imap->buf.sock.ssl)
1135 imap_warn("*** IMAP Warning *** Password is being "
1136 "sent in the clear\n");
1137 if (imap_exec(ctx, NULL, "LOGIN \"%s\" \"%s\"", srvc->user, srvc->pass) != RESP_OK) {
1138 fprintf(stderr, "IMAP error: LOGIN failed\n");
1139 goto bail;
1141 } /* !preauth */
1143 ctx->prefix = "";
1144 ctx->trashnc = 1;
1145 return (struct store *)ctx;
1147 bail:
1148 imap_close_store(&ctx->gen);
1149 return NULL;
1152 static int imap_make_flags(int flags, char *buf)
1154 const char *s;
1155 unsigned i, d;
1157 for (i = d = 0; i < ARRAY_SIZE(Flags); i++)
1158 if (flags & (1 << i)) {
1159 buf[d++] = ' ';
1160 buf[d++] = '\\';
1161 for (s = Flags[i]; *s; s++)
1162 buf[d++] = *s;
1164 buf[0] = '(';
1165 buf[d++] = ')';
1166 return d;
1169 static int imap_store_msg(struct store *gctx, struct msg_data *data)
1171 struct imap_store *ctx = (struct imap_store *)gctx;
1172 struct imap *imap = ctx->imap;
1173 struct imap_cmd_cb cb;
1174 const char *prefix, *box;
1175 int ret, d;
1176 char flagstr[128];
1178 memset(&cb, 0, sizeof(cb));
1180 cb.dlen = data->len;
1181 cb.data = xmalloc(cb.dlen);
1182 memcpy(cb.data, data->data, data->len);
1184 d = 0;
1185 if (data->flags) {
1186 d = imap_make_flags(data->flags, flagstr);
1187 flagstr[d++] = ' ';
1189 flagstr[d] = 0;
1191 box = gctx->name;
1192 prefix = !strcmp(box, "INBOX") ? "" : ctx->prefix;
1193 cb.create = 0;
1194 ret = imap_exec_m(ctx, &cb, "APPEND \"%s%s\" %s", prefix, box, flagstr);
1195 imap->caps = imap->rcaps;
1196 if (ret != DRV_OK)
1197 return ret;
1198 gctx->count++;
1200 return DRV_OK;
1203 static void encode_html_chars(struct strbuf *p)
1205 int i;
1206 for (i = 0; i < p->len; i++) {
1207 if (p->buf[i] == '&')
1208 strbuf_splice(p, i, 1, "&amp;", 5);
1209 if (p->buf[i] == '<')
1210 strbuf_splice(p, i, 1, "&lt;", 4);
1211 if (p->buf[i] == '>')
1212 strbuf_splice(p, i, 1, "&gt;", 4);
1213 if (p->buf[i] == '"')
1214 strbuf_splice(p, i, 1, "&quot;", 6);
1217 static void wrap_in_html(struct msg_data *msg)
1219 struct strbuf buf = STRBUF_INIT;
1220 struct strbuf **lines;
1221 struct strbuf **p;
1222 static char *content_type = "Content-Type: text/html;\n";
1223 static char *pre_open = "<pre>\n";
1224 static char *pre_close = "</pre>\n";
1225 int added_header = 0;
1227 strbuf_attach(&buf, msg->data, msg->len, msg->len);
1228 lines = strbuf_split(&buf, '\n');
1229 strbuf_release(&buf);
1230 for (p = lines; *p; p++) {
1231 if (! added_header) {
1232 if ((*p)->len == 1 && *((*p)->buf) == '\n') {
1233 strbuf_addstr(&buf, content_type);
1234 strbuf_addbuf(&buf, *p);
1235 strbuf_addstr(&buf, pre_open);
1236 added_header = 1;
1237 continue;
1240 else
1241 encode_html_chars(*p);
1242 strbuf_addbuf(&buf, *p);
1244 strbuf_addstr(&buf, pre_close);
1245 strbuf_list_free(lines);
1246 msg->len = buf.len;
1247 msg->data = strbuf_detach(&buf, NULL);
1250 #define CHUNKSIZE 0x1000
1252 static int read_message(FILE *f, struct msg_data *msg)
1254 struct strbuf buf = STRBUF_INIT;
1256 memset(msg, 0, sizeof(*msg));
1258 do {
1259 if (strbuf_fread(&buf, CHUNKSIZE, f) <= 0)
1260 break;
1261 } while (!feof(f));
1263 msg->len = buf.len;
1264 msg->data = strbuf_detach(&buf, NULL);
1265 return msg->len;
1268 static int count_messages(struct msg_data *msg)
1270 int count = 0;
1271 char *p = msg->data;
1273 while (1) {
1274 if (!prefixcmp(p, "From ")) {
1275 count++;
1276 p += 5;
1278 p = strstr(p+5, "\nFrom ");
1279 if (!p)
1280 break;
1281 p++;
1283 return count;
1286 static int split_msg(struct msg_data *all_msgs, struct msg_data *msg, int *ofs)
1288 char *p, *data;
1290 memset(msg, 0, sizeof *msg);
1291 if (*ofs >= all_msgs->len)
1292 return 0;
1294 data = &all_msgs->data[*ofs];
1295 msg->len = all_msgs->len - *ofs;
1297 if (msg->len < 5 || prefixcmp(data, "From "))
1298 return 0;
1300 p = strchr(data, '\n');
1301 if (p) {
1302 p = &p[1];
1303 msg->len -= p-data;
1304 *ofs += p-data;
1305 data = p;
1308 p = strstr(data, "\nFrom ");
1309 if (p)
1310 msg->len = &p[1] - data;
1312 msg->data = xmemdupz(data, msg->len);
1313 *ofs += msg->len;
1314 return 1;
1317 static struct imap_server_conf server = {
1318 NULL, /* name */
1319 NULL, /* tunnel */
1320 NULL, /* host */
1321 0, /* port */
1322 NULL, /* user */
1323 NULL, /* pass */
1324 0, /* use_ssl */
1325 1, /* ssl_verify */
1326 0, /* use_html */
1329 static char *imap_folder;
1331 static int git_imap_config(const char *key, const char *val, void *cb)
1333 char imap_key[] = "imap.";
1335 if (strncmp(key, imap_key, sizeof imap_key - 1))
1336 return 0;
1338 if (!val)
1339 return config_error_nonbool(key);
1341 key += sizeof imap_key - 1;
1343 if (!strcmp("folder", key)) {
1344 imap_folder = xstrdup(val);
1345 } else if (!strcmp("host", key)) {
1346 if (!prefixcmp(val, "imap:"))
1347 val += 5;
1348 else if (!prefixcmp(val, "imaps:")) {
1349 val += 6;
1350 server.use_ssl = 1;
1352 if (!prefixcmp(val, "//"))
1353 val += 2;
1354 server.host = xstrdup(val);
1355 } else if (!strcmp("user", key))
1356 server.user = xstrdup(val);
1357 else if (!strcmp("pass", key))
1358 server.pass = xstrdup(val);
1359 else if (!strcmp("port", key))
1360 server.port = git_config_int(key, val);
1361 else if (!strcmp("tunnel", key))
1362 server.tunnel = xstrdup(val);
1363 else if (!strcmp("sslverify", key))
1364 server.ssl_verify = git_config_bool(key, val);
1365 else if (!strcmp("preformattedHTML", key))
1366 server.use_html = git_config_bool(key, val);
1367 return 0;
1370 int main(int argc, char **argv)
1372 struct msg_data all_msgs, msg;
1373 struct store *ctx = NULL;
1374 int ofs = 0;
1375 int r;
1376 int total, n = 0;
1377 int nongit_ok;
1379 git_extract_argv0_path(argv[0]);
1381 if (argc != 1)
1382 usage(imap_send_usage);
1384 setup_git_directory_gently(&nongit_ok);
1385 git_config(git_imap_config, NULL);
1387 if (!server.port)
1388 server.port = server.use_ssl ? 993 : 143;
1390 if (!imap_folder) {
1391 fprintf(stderr, "no imap store specified\n");
1392 return 1;
1394 if (!server.host) {
1395 if (!server.tunnel) {
1396 fprintf(stderr, "no imap host specified\n");
1397 return 1;
1399 server.host = "tunnel";
1402 /* read the messages */
1403 if (!read_message(stdin, &all_msgs)) {
1404 fprintf(stderr, "nothing to send\n");
1405 return 1;
1408 total = count_messages(&all_msgs);
1409 if (!total) {
1410 fprintf(stderr, "no messages to send\n");
1411 return 1;
1414 /* write it to the imap server */
1415 ctx = imap_open_store(&server);
1416 if (!ctx) {
1417 fprintf(stderr, "failed to open store\n");
1418 return 1;
1421 fprintf(stderr, "sending %d message%s\n", total, (total != 1) ? "s" : "");
1422 ctx->name = imap_folder;
1423 while (1) {
1424 unsigned percent = n * 100 / total;
1425 fprintf(stderr, "%4u%% (%d/%d) done\r", percent, n, total);
1426 if (!split_msg(&all_msgs, &msg, &ofs))
1427 break;
1428 if (server.use_html)
1429 wrap_in_html(&msg);
1430 r = imap_store_msg(ctx, &msg);
1431 if (r != DRV_OK)
1432 break;
1433 n++;
1435 fprintf(stderr, "\n");
1437 imap_close_store(ctx);
1439 return 0;