Merge branch 'jl/submodule-add-noname'
[git/raj.git] / imap-send.c
blob834301cf409c311d47b22a0f7504917a32847647
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 static void imap_info(const char *, ...);
108 static void imap_warn(const char *, ...);
110 static char *next_arg(char **);
112 static void free_generic_messages(struct message *);
114 static int nfsnprintf(char *buf, int blen, const char *fmt, ...);
116 static int nfvasprintf(char **strp, const char *fmt, va_list ap)
118 int len;
119 char tmp[8192];
121 len = vsnprintf(tmp, sizeof(tmp), fmt, ap);
122 if (len < 0)
123 die("Fatal: Out of memory");
124 if (len >= sizeof(tmp))
125 die("imap command overflow!");
126 *strp = xmemdupz(tmp, len);
127 return len;
130 struct imap_server_conf {
131 char *name;
132 char *tunnel;
133 char *host;
134 int port;
135 char *user;
136 char *pass;
137 int use_ssl;
138 int ssl_verify;
139 int use_html;
142 struct imap_store_conf {
143 struct store_conf gen;
144 struct imap_server_conf *server;
145 unsigned use_namespace:1;
148 #define NIL (void *)0x1
149 #define LIST (void *)0x2
151 struct imap_list {
152 struct imap_list *next, *child;
153 char *val;
154 int len;
157 struct imap_socket {
158 int fd[2];
159 SSL *ssl;
162 struct imap_buffer {
163 struct imap_socket sock;
164 int bytes;
165 int offset;
166 char buf[1024];
169 struct imap_cmd;
171 struct imap {
172 int uidnext; /* from SELECT responses */
173 struct imap_list *ns_personal, *ns_other, *ns_shared; /* NAMESPACE info */
174 unsigned caps, rcaps; /* CAPABILITY results */
175 /* command queue */
176 int nexttag, num_in_progress, literal_pending;
177 struct imap_cmd *in_progress, **in_progress_append;
178 struct imap_buffer buf; /* this is BIG, so put it last */
181 struct imap_store {
182 struct store gen;
183 int uidvalidity;
184 struct imap *imap;
185 const char *prefix;
186 unsigned /*currentnc:1,*/ trashnc:1;
189 struct imap_cmd_cb {
190 int (*cont)(struct imap_store *ctx, struct imap_cmd *cmd, const char *prompt);
191 void (*done)(struct imap_store *ctx, struct imap_cmd *cmd, int response);
192 void *ctx;
193 char *data;
194 int dlen;
195 int uid;
196 unsigned create:1, trycreate:1;
199 struct imap_cmd {
200 struct imap_cmd *next;
201 struct imap_cmd_cb cb;
202 char *cmd;
203 int tag;
206 #define CAP(cap) (imap->caps & (1 << (cap)))
208 enum CAPABILITY {
209 NOLOGIN = 0,
210 UIDPLUS,
211 LITERALPLUS,
212 NAMESPACE,
213 STARTTLS,
216 static const char *cap_list[] = {
217 "LOGINDISABLED",
218 "UIDPLUS",
219 "LITERAL+",
220 "NAMESPACE",
221 "STARTTLS",
224 #define RESP_OK 0
225 #define RESP_NO 1
226 #define RESP_BAD 2
228 static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd);
231 static const char *Flags[] = {
232 "Draft",
233 "Flagged",
234 "Answered",
235 "Seen",
236 "Deleted",
239 #ifndef NO_OPENSSL
240 static void ssl_socket_perror(const char *func)
242 fprintf(stderr, "%s: %s\n", func, ERR_error_string(ERR_get_error(), NULL));
244 #endif
246 static void socket_perror(const char *func, struct imap_socket *sock, int ret)
248 #ifndef NO_OPENSSL
249 if (sock->ssl) {
250 int sslerr = SSL_get_error(sock->ssl, ret);
251 switch (sslerr) {
252 case SSL_ERROR_NONE:
253 break;
254 case SSL_ERROR_SYSCALL:
255 perror("SSL_connect");
256 break;
257 default:
258 ssl_socket_perror("SSL_connect");
259 break;
261 } else
262 #endif
264 if (ret < 0)
265 perror(func);
266 else
267 fprintf(stderr, "%s: unexpected EOF\n", func);
271 static int ssl_socket_connect(struct imap_socket *sock, int use_tls_only, int verify)
273 #ifdef NO_OPENSSL
274 fprintf(stderr, "SSL requested but SSL support not compiled in\n");
275 return -1;
276 #else
277 #if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
278 const SSL_METHOD *meth;
279 #else
280 SSL_METHOD *meth;
281 #endif
282 SSL_CTX *ctx;
283 int ret;
285 SSL_library_init();
286 SSL_load_error_strings();
288 if (use_tls_only)
289 meth = TLSv1_method();
290 else
291 meth = SSLv23_method();
293 if (!meth) {
294 ssl_socket_perror("SSLv23_method");
295 return -1;
298 ctx = SSL_CTX_new(meth);
300 if (verify)
301 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
303 if (!SSL_CTX_set_default_verify_paths(ctx)) {
304 ssl_socket_perror("SSL_CTX_set_default_verify_paths");
305 return -1;
307 sock->ssl = SSL_new(ctx);
308 if (!sock->ssl) {
309 ssl_socket_perror("SSL_new");
310 return -1;
312 if (!SSL_set_rfd(sock->ssl, sock->fd[0])) {
313 ssl_socket_perror("SSL_set_rfd");
314 return -1;
316 if (!SSL_set_wfd(sock->ssl, sock->fd[1])) {
317 ssl_socket_perror("SSL_set_wfd");
318 return -1;
321 ret = SSL_connect(sock->ssl);
322 if (ret <= 0) {
323 socket_perror("SSL_connect", sock, ret);
324 return -1;
327 return 0;
328 #endif
331 static int socket_read(struct imap_socket *sock, char *buf, int len)
333 ssize_t n;
334 #ifndef NO_OPENSSL
335 if (sock->ssl)
336 n = SSL_read(sock->ssl, buf, len);
337 else
338 #endif
339 n = xread(sock->fd[0], buf, len);
340 if (n <= 0) {
341 socket_perror("read", sock, n);
342 close(sock->fd[0]);
343 close(sock->fd[1]);
344 sock->fd[0] = sock->fd[1] = -1;
346 return n;
349 static int socket_write(struct imap_socket *sock, const char *buf, int len)
351 int n;
352 #ifndef NO_OPENSSL
353 if (sock->ssl)
354 n = SSL_write(sock->ssl, buf, len);
355 else
356 #endif
357 n = write_in_full(sock->fd[1], buf, len);
358 if (n != len) {
359 socket_perror("write", sock, n);
360 close(sock->fd[0]);
361 close(sock->fd[1]);
362 sock->fd[0] = sock->fd[1] = -1;
364 return n;
367 static void socket_shutdown(struct imap_socket *sock)
369 #ifndef NO_OPENSSL
370 if (sock->ssl) {
371 SSL_shutdown(sock->ssl);
372 SSL_free(sock->ssl);
374 #endif
375 close(sock->fd[0]);
376 close(sock->fd[1]);
379 /* simple line buffering */
380 static int buffer_gets(struct imap_buffer *b, char **s)
382 int n;
383 int start = b->offset;
385 *s = b->buf + start;
387 for (;;) {
388 /* make sure we have enough data to read the \r\n sequence */
389 if (b->offset + 1 >= b->bytes) {
390 if (start) {
391 /* shift down used bytes */
392 *s = b->buf;
394 assert(start <= b->bytes);
395 n = b->bytes - start;
397 if (n)
398 memmove(b->buf, b->buf + start, n);
399 b->offset -= start;
400 b->bytes = n;
401 start = 0;
404 n = socket_read(&b->sock, b->buf + b->bytes,
405 sizeof(b->buf) - b->bytes);
407 if (n <= 0)
408 return -1;
410 b->bytes += n;
413 if (b->buf[b->offset] == '\r') {
414 assert(b->offset + 1 < b->bytes);
415 if (b->buf[b->offset + 1] == '\n') {
416 b->buf[b->offset] = 0; /* terminate the string */
417 b->offset += 2; /* next line */
418 if (Verbose)
419 puts(*s);
420 return 0;
424 b->offset++;
426 /* not reached */
429 static void imap_info(const char *msg, ...)
431 va_list va;
433 if (!Quiet) {
434 va_start(va, msg);
435 vprintf(msg, va);
436 va_end(va);
437 fflush(stdout);
441 static void imap_warn(const char *msg, ...)
443 va_list va;
445 if (Quiet < 2) {
446 va_start(va, msg);
447 vfprintf(stderr, msg, va);
448 va_end(va);
452 static char *next_arg(char **s)
454 char *ret;
456 if (!s || !*s)
457 return NULL;
458 while (isspace((unsigned char) **s))
459 (*s)++;
460 if (!**s) {
461 *s = NULL;
462 return NULL;
464 if (**s == '"') {
465 ++*s;
466 ret = *s;
467 *s = strchr(*s, '"');
468 } else {
469 ret = *s;
470 while (**s && !isspace((unsigned char) **s))
471 (*s)++;
473 if (*s) {
474 if (**s)
475 *(*s)++ = 0;
476 if (!**s)
477 *s = NULL;
479 return ret;
482 static void free_generic_messages(struct message *msgs)
484 struct message *tmsg;
486 for (; msgs; msgs = tmsg) {
487 tmsg = msgs->next;
488 free(msgs);
492 static int nfsnprintf(char *buf, int blen, const char *fmt, ...)
494 int ret;
495 va_list va;
497 va_start(va, fmt);
498 if (blen <= 0 || (unsigned)(ret = vsnprintf(buf, blen, fmt, va)) >= (unsigned)blen)
499 die("Fatal: buffer too small. Please report a bug.");
500 va_end(va);
501 return ret;
504 static struct imap_cmd *v_issue_imap_cmd(struct imap_store *ctx,
505 struct imap_cmd_cb *cb,
506 const char *fmt, va_list ap)
508 struct imap *imap = ctx->imap;
509 struct imap_cmd *cmd;
510 int n, bufl;
511 char buf[1024];
513 cmd = xmalloc(sizeof(struct imap_cmd));
514 nfvasprintf(&cmd->cmd, fmt, ap);
515 cmd->tag = ++imap->nexttag;
517 if (cb)
518 cmd->cb = *cb;
519 else
520 memset(&cmd->cb, 0, sizeof(cmd->cb));
522 while (imap->literal_pending)
523 get_cmd_result(ctx, NULL);
525 bufl = nfsnprintf(buf, sizeof(buf), cmd->cb.data ? CAP(LITERALPLUS) ?
526 "%d %s{%d+}\r\n" : "%d %s{%d}\r\n" : "%d %s\r\n",
527 cmd->tag, cmd->cmd, cmd->cb.dlen);
528 if (Verbose) {
529 if (imap->num_in_progress)
530 printf("(%d in progress) ", imap->num_in_progress);
531 if (memcmp(cmd->cmd, "LOGIN", 5))
532 printf(">>> %s", buf);
533 else
534 printf(">>> %d LOGIN <user> <pass>\n", cmd->tag);
536 if (socket_write(&imap->buf.sock, buf, bufl) != bufl) {
537 free(cmd->cmd);
538 free(cmd);
539 if (cb)
540 free(cb->data);
541 return NULL;
543 if (cmd->cb.data) {
544 if (CAP(LITERALPLUS)) {
545 n = socket_write(&imap->buf.sock, cmd->cb.data, cmd->cb.dlen);
546 free(cmd->cb.data);
547 if (n != cmd->cb.dlen ||
548 socket_write(&imap->buf.sock, "\r\n", 2) != 2) {
549 free(cmd->cmd);
550 free(cmd);
551 return NULL;
553 cmd->cb.data = NULL;
554 } else
555 imap->literal_pending = 1;
556 } else if (cmd->cb.cont)
557 imap->literal_pending = 1;
558 cmd->next = NULL;
559 *imap->in_progress_append = cmd;
560 imap->in_progress_append = &cmd->next;
561 imap->num_in_progress++;
562 return cmd;
565 static struct imap_cmd *issue_imap_cmd(struct imap_store *ctx,
566 struct imap_cmd_cb *cb,
567 const char *fmt, ...)
569 struct imap_cmd *ret;
570 va_list ap;
572 va_start(ap, fmt);
573 ret = v_issue_imap_cmd(ctx, cb, fmt, ap);
574 va_end(ap);
575 return ret;
578 static int imap_exec(struct imap_store *ctx, struct imap_cmd_cb *cb,
579 const char *fmt, ...)
581 va_list ap;
582 struct imap_cmd *cmdp;
584 va_start(ap, fmt);
585 cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
586 va_end(ap);
587 if (!cmdp)
588 return RESP_BAD;
590 return get_cmd_result(ctx, cmdp);
593 static int imap_exec_m(struct imap_store *ctx, struct imap_cmd_cb *cb,
594 const char *fmt, ...)
596 va_list ap;
597 struct imap_cmd *cmdp;
599 va_start(ap, fmt);
600 cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
601 va_end(ap);
602 if (!cmdp)
603 return DRV_STORE_BAD;
605 switch (get_cmd_result(ctx, cmdp)) {
606 case RESP_BAD: return DRV_STORE_BAD;
607 case RESP_NO: return DRV_MSG_BAD;
608 default: return DRV_OK;
612 static int is_atom(struct imap_list *list)
614 return list && list->val && list->val != NIL && list->val != LIST;
617 static int is_list(struct imap_list *list)
619 return list && list->val == LIST;
622 static void free_list(struct imap_list *list)
624 struct imap_list *tmp;
626 for (; list; list = tmp) {
627 tmp = list->next;
628 if (is_list(list))
629 free_list(list->child);
630 else if (is_atom(list))
631 free(list->val);
632 free(list);
636 static int parse_imap_list_l(struct imap *imap, char **sp, struct imap_list **curp, int level)
638 struct imap_list *cur;
639 char *s = *sp, *p;
640 int n, bytes;
642 for (;;) {
643 while (isspace((unsigned char)*s))
644 s++;
645 if (level && *s == ')') {
646 s++;
647 break;
649 *curp = cur = xmalloc(sizeof(*cur));
650 curp = &cur->next;
651 cur->val = NULL; /* for clean bail */
652 if (*s == '(') {
653 /* sublist */
654 s++;
655 cur->val = LIST;
656 if (parse_imap_list_l(imap, &s, &cur->child, level + 1))
657 goto bail;
658 } else if (imap && *s == '{') {
659 /* literal */
660 bytes = cur->len = strtol(s + 1, &s, 10);
661 if (*s != '}')
662 goto bail;
664 s = cur->val = xmalloc(cur->len);
666 /* dump whats left over in the input buffer */
667 n = imap->buf.bytes - imap->buf.offset;
669 if (n > bytes)
670 /* the entire message fit in the buffer */
671 n = bytes;
673 memcpy(s, imap->buf.buf + imap->buf.offset, n);
674 s += n;
675 bytes -= n;
677 /* mark that we used part of the buffer */
678 imap->buf.offset += n;
680 /* now read the rest of the message */
681 while (bytes > 0) {
682 if ((n = socket_read(&imap->buf.sock, s, bytes)) <= 0)
683 goto bail;
684 s += n;
685 bytes -= n;
688 if (buffer_gets(&imap->buf, &s))
689 goto bail;
690 } else if (*s == '"') {
691 /* quoted string */
692 s++;
693 p = s;
694 for (; *s != '"'; s++)
695 if (!*s)
696 goto bail;
697 cur->len = s - p;
698 s++;
699 cur->val = xmemdupz(p, cur->len);
700 } else {
701 /* atom */
702 p = s;
703 for (; *s && !isspace((unsigned char)*s); s++)
704 if (level && *s == ')')
705 break;
706 cur->len = s - p;
707 if (cur->len == 3 && !memcmp("NIL", p, 3))
708 cur->val = NIL;
709 else
710 cur->val = xmemdupz(p, cur->len);
713 if (!level)
714 break;
715 if (!*s)
716 goto bail;
718 *sp = s;
719 *curp = NULL;
720 return 0;
722 bail:
723 *curp = NULL;
724 return -1;
727 static struct imap_list *parse_imap_list(struct imap *imap, char **sp)
729 struct imap_list *head;
731 if (!parse_imap_list_l(imap, sp, &head, 0))
732 return head;
733 free_list(head);
734 return NULL;
737 static struct imap_list *parse_list(char **sp)
739 return parse_imap_list(NULL, sp);
742 static void parse_capability(struct imap *imap, char *cmd)
744 char *arg;
745 unsigned i;
747 imap->caps = 0x80000000;
748 while ((arg = next_arg(&cmd)))
749 for (i = 0; i < ARRAY_SIZE(cap_list); i++)
750 if (!strcmp(cap_list[i], arg))
751 imap->caps |= 1 << i;
752 imap->rcaps = imap->caps;
755 static int parse_response_code(struct imap_store *ctx, struct imap_cmd_cb *cb,
756 char *s)
758 struct imap *imap = ctx->imap;
759 char *arg, *p;
761 if (*s != '[')
762 return RESP_OK; /* no response code */
763 s++;
764 if (!(p = strchr(s, ']'))) {
765 fprintf(stderr, "IMAP error: malformed response code\n");
766 return RESP_BAD;
768 *p++ = 0;
769 arg = next_arg(&s);
770 if (!strcmp("UIDVALIDITY", arg)) {
771 if (!(arg = next_arg(&s)) || !(ctx->gen.uidvalidity = atoi(arg))) {
772 fprintf(stderr, "IMAP error: malformed UIDVALIDITY status\n");
773 return RESP_BAD;
775 } else if (!strcmp("UIDNEXT", arg)) {
776 if (!(arg = next_arg(&s)) || !(imap->uidnext = atoi(arg))) {
777 fprintf(stderr, "IMAP error: malformed NEXTUID status\n");
778 return RESP_BAD;
780 } else if (!strcmp("CAPABILITY", arg)) {
781 parse_capability(imap, s);
782 } else if (!strcmp("ALERT", arg)) {
783 /* RFC2060 says that these messages MUST be displayed
784 * to the user
786 for (; isspace((unsigned char)*p); p++);
787 fprintf(stderr, "*** IMAP ALERT *** %s\n", p);
788 } else if (cb && cb->ctx && !strcmp("APPENDUID", arg)) {
789 if (!(arg = next_arg(&s)) || !(ctx->gen.uidvalidity = atoi(arg)) ||
790 !(arg = next_arg(&s)) || !(*(int *)cb->ctx = atoi(arg))) {
791 fprintf(stderr, "IMAP error: malformed APPENDUID status\n");
792 return RESP_BAD;
795 return RESP_OK;
798 static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd)
800 struct imap *imap = ctx->imap;
801 struct imap_cmd *cmdp, **pcmdp, *ncmdp;
802 char *cmd, *arg, *arg1, *p;
803 int n, resp, resp2, tag;
805 for (;;) {
806 if (buffer_gets(&imap->buf, &cmd))
807 return RESP_BAD;
809 arg = next_arg(&cmd);
810 if (*arg == '*') {
811 arg = next_arg(&cmd);
812 if (!arg) {
813 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
814 return RESP_BAD;
817 if (!strcmp("NAMESPACE", arg)) {
818 imap->ns_personal = parse_list(&cmd);
819 imap->ns_other = parse_list(&cmd);
820 imap->ns_shared = parse_list(&cmd);
821 } else if (!strcmp("OK", arg) || !strcmp("BAD", arg) ||
822 !strcmp("NO", arg) || !strcmp("BYE", arg)) {
823 if ((resp = parse_response_code(ctx, NULL, cmd)) != RESP_OK)
824 return resp;
825 } else if (!strcmp("CAPABILITY", arg))
826 parse_capability(imap, cmd);
827 else if ((arg1 = next_arg(&cmd))) {
828 if (!strcmp("EXISTS", arg1))
829 ctx->gen.count = atoi(arg);
830 else if (!strcmp("RECENT", arg1))
831 ctx->gen.recent = atoi(arg);
832 } else {
833 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
834 return RESP_BAD;
836 } else if (!imap->in_progress) {
837 fprintf(stderr, "IMAP error: unexpected reply: %s %s\n", arg, cmd ? cmd : "");
838 return RESP_BAD;
839 } else if (*arg == '+') {
840 /* This can happen only with the last command underway, as
841 it enforces a round-trip. */
842 cmdp = (struct imap_cmd *)((char *)imap->in_progress_append -
843 offsetof(struct imap_cmd, next));
844 if (cmdp->cb.data) {
845 n = socket_write(&imap->buf.sock, cmdp->cb.data, cmdp->cb.dlen);
846 free(cmdp->cb.data);
847 cmdp->cb.data = NULL;
848 if (n != (int)cmdp->cb.dlen)
849 return RESP_BAD;
850 } else if (cmdp->cb.cont) {
851 if (cmdp->cb.cont(ctx, cmdp, cmd))
852 return RESP_BAD;
853 } else {
854 fprintf(stderr, "IMAP error: unexpected command continuation request\n");
855 return RESP_BAD;
857 if (socket_write(&imap->buf.sock, "\r\n", 2) != 2)
858 return RESP_BAD;
859 if (!cmdp->cb.cont)
860 imap->literal_pending = 0;
861 if (!tcmd)
862 return DRV_OK;
863 } else {
864 tag = atoi(arg);
865 for (pcmdp = &imap->in_progress; (cmdp = *pcmdp); pcmdp = &cmdp->next)
866 if (cmdp->tag == tag)
867 goto gottag;
868 fprintf(stderr, "IMAP error: unexpected tag %s\n", arg);
869 return RESP_BAD;
870 gottag:
871 if (!(*pcmdp = cmdp->next))
872 imap->in_progress_append = pcmdp;
873 imap->num_in_progress--;
874 if (cmdp->cb.cont || cmdp->cb.data)
875 imap->literal_pending = 0;
876 arg = next_arg(&cmd);
877 if (!strcmp("OK", arg))
878 resp = DRV_OK;
879 else {
880 if (!strcmp("NO", arg)) {
881 if (cmdp->cb.create && cmd && (cmdp->cb.trycreate || !memcmp(cmd, "[TRYCREATE]", 11))) { /* SELECT, APPEND or UID COPY */
882 p = strchr(cmdp->cmd, '"');
883 if (!issue_imap_cmd(ctx, NULL, "CREATE \"%.*s\"", strchr(p + 1, '"') - p + 1, p)) {
884 resp = RESP_BAD;
885 goto normal;
887 /* not waiting here violates the spec, but a server that does not
888 grok this nonetheless violates it too. */
889 cmdp->cb.create = 0;
890 if (!(ncmdp = issue_imap_cmd(ctx, &cmdp->cb, "%s", cmdp->cmd))) {
891 resp = RESP_BAD;
892 goto normal;
894 free(cmdp->cmd);
895 free(cmdp);
896 if (!tcmd)
897 return 0; /* ignored */
898 if (cmdp == tcmd)
899 tcmd = ncmdp;
900 continue;
902 resp = RESP_NO;
903 } else /*if (!strcmp("BAD", arg))*/
904 resp = RESP_BAD;
905 fprintf(stderr, "IMAP command '%s' returned response (%s) - %s\n",
906 memcmp(cmdp->cmd, "LOGIN", 5) ?
907 cmdp->cmd : "LOGIN <user> <pass>",
908 arg, cmd ? cmd : "");
910 if ((resp2 = parse_response_code(ctx, &cmdp->cb, cmd)) > resp)
911 resp = resp2;
912 normal:
913 if (cmdp->cb.done)
914 cmdp->cb.done(ctx, cmdp, resp);
915 free(cmdp->cb.data);
916 free(cmdp->cmd);
917 free(cmdp);
918 if (!tcmd || tcmd == cmdp)
919 return resp;
922 /* not reached */
925 static void imap_close_server(struct imap_store *ictx)
927 struct imap *imap = ictx->imap;
929 if (imap->buf.sock.fd[0] != -1) {
930 imap_exec(ictx, NULL, "LOGOUT");
931 socket_shutdown(&imap->buf.sock);
933 free_list(imap->ns_personal);
934 free_list(imap->ns_other);
935 free_list(imap->ns_shared);
936 free(imap);
939 static void imap_close_store(struct store *ctx)
941 imap_close_server((struct imap_store *)ctx);
942 free_generic_messages(ctx->msgs);
943 free(ctx);
946 static struct store *imap_open_store(struct imap_server_conf *srvc)
948 struct imap_store *ctx;
949 struct imap *imap;
950 char *arg, *rsp;
951 int s = -1, preauth;
953 ctx = xcalloc(sizeof(*ctx), 1);
955 ctx->imap = imap = xcalloc(sizeof(*imap), 1);
956 imap->buf.sock.fd[0] = imap->buf.sock.fd[1] = -1;
957 imap->in_progress_append = &imap->in_progress;
959 /* open connection to IMAP server */
961 if (srvc->tunnel) {
962 const char *argv[4];
963 struct child_process tunnel = {0};
965 imap_info("Starting tunnel '%s'... ", srvc->tunnel);
967 argv[0] = "sh";
968 argv[1] = "-c";
969 argv[2] = srvc->tunnel;
970 argv[3] = NULL;
972 tunnel.argv = argv;
973 tunnel.in = -1;
974 tunnel.out = -1;
975 if (start_command(&tunnel))
976 die("cannot start proxy %s", argv[0]);
978 imap->buf.sock.fd[0] = tunnel.out;
979 imap->buf.sock.fd[1] = tunnel.in;
981 imap_info("ok\n");
982 } else {
983 #ifndef NO_IPV6
984 struct addrinfo hints, *ai0, *ai;
985 int gai;
986 char portstr[6];
988 snprintf(portstr, sizeof(portstr), "%hu", srvc->port);
990 memset(&hints, 0, sizeof(hints));
991 hints.ai_socktype = SOCK_STREAM;
992 hints.ai_protocol = IPPROTO_TCP;
994 imap_info("Resolving %s... ", srvc->host);
995 gai = getaddrinfo(srvc->host, portstr, &hints, &ai);
996 if (gai) {
997 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai));
998 goto bail;
1000 imap_info("ok\n");
1002 for (ai0 = ai; ai; ai = ai->ai_next) {
1003 char addr[NI_MAXHOST];
1005 s = socket(ai->ai_family, ai->ai_socktype,
1006 ai->ai_protocol);
1007 if (s < 0)
1008 continue;
1010 getnameinfo(ai->ai_addr, ai->ai_addrlen, addr,
1011 sizeof(addr), NULL, 0, NI_NUMERICHOST);
1012 imap_info("Connecting to [%s]:%s... ", addr, portstr);
1014 if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0) {
1015 close(s);
1016 s = -1;
1017 perror("connect");
1018 continue;
1021 break;
1023 freeaddrinfo(ai0);
1024 #else /* NO_IPV6 */
1025 struct hostent *he;
1026 struct sockaddr_in addr;
1028 memset(&addr, 0, sizeof(addr));
1029 addr.sin_port = htons(srvc->port);
1030 addr.sin_family = AF_INET;
1032 imap_info("Resolving %s... ", srvc->host);
1033 he = gethostbyname(srvc->host);
1034 if (!he) {
1035 perror("gethostbyname");
1036 goto bail;
1038 imap_info("ok\n");
1040 addr.sin_addr.s_addr = *((int *) he->h_addr_list[0]);
1042 s = socket(PF_INET, SOCK_STREAM, 0);
1044 imap_info("Connecting to %s:%hu... ", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
1045 if (connect(s, (struct sockaddr *)&addr, sizeof(addr))) {
1046 close(s);
1047 s = -1;
1048 perror("connect");
1050 #endif
1051 if (s < 0) {
1052 fputs("Error: unable to connect to server.\n", stderr);
1053 goto bail;
1056 imap->buf.sock.fd[0] = s;
1057 imap->buf.sock.fd[1] = dup(s);
1059 if (srvc->use_ssl &&
1060 ssl_socket_connect(&imap->buf.sock, 0, srvc->ssl_verify)) {
1061 close(s);
1062 goto bail;
1064 imap_info("ok\n");
1067 /* read the greeting string */
1068 if (buffer_gets(&imap->buf, &rsp)) {
1069 fprintf(stderr, "IMAP error: no greeting response\n");
1070 goto bail;
1072 arg = next_arg(&rsp);
1073 if (!arg || *arg != '*' || (arg = next_arg(&rsp)) == NULL) {
1074 fprintf(stderr, "IMAP error: invalid greeting response\n");
1075 goto bail;
1077 preauth = 0;
1078 if (!strcmp("PREAUTH", arg))
1079 preauth = 1;
1080 else if (strcmp("OK", arg) != 0) {
1081 fprintf(stderr, "IMAP error: unknown greeting response\n");
1082 goto bail;
1084 parse_response_code(ctx, NULL, rsp);
1085 if (!imap->caps && imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1086 goto bail;
1088 if (!preauth) {
1089 #ifndef NO_OPENSSL
1090 if (!srvc->use_ssl && CAP(STARTTLS)) {
1091 if (imap_exec(ctx, 0, "STARTTLS") != RESP_OK)
1092 goto bail;
1093 if (ssl_socket_connect(&imap->buf.sock, 1,
1094 srvc->ssl_verify))
1095 goto bail;
1096 /* capabilities may have changed, so get the new capabilities */
1097 if (imap_exec(ctx, 0, "CAPABILITY") != RESP_OK)
1098 goto bail;
1100 #endif
1101 imap_info("Logging in...\n");
1102 if (!srvc->user) {
1103 fprintf(stderr, "Skipping server %s, no user\n", srvc->host);
1104 goto bail;
1106 if (!srvc->pass) {
1107 char prompt[80];
1108 sprintf(prompt, "Password (%s@%s): ", srvc->user, srvc->host);
1109 arg = getpass(prompt);
1110 if (!arg) {
1111 perror("getpass");
1112 exit(1);
1114 if (!*arg) {
1115 fprintf(stderr, "Skipping account %s@%s, no password\n", srvc->user, srvc->host);
1116 goto bail;
1119 * getpass() returns a pointer to a static buffer. make a copy
1120 * for long term storage.
1122 srvc->pass = xstrdup(arg);
1124 if (CAP(NOLOGIN)) {
1125 fprintf(stderr, "Skipping account %s@%s, server forbids LOGIN\n", srvc->user, srvc->host);
1126 goto bail;
1128 if (!imap->buf.sock.ssl)
1129 imap_warn("*** IMAP Warning *** Password is being "
1130 "sent in the clear\n");
1131 if (imap_exec(ctx, NULL, "LOGIN \"%s\" \"%s\"", srvc->user, srvc->pass) != RESP_OK) {
1132 fprintf(stderr, "IMAP error: LOGIN failed\n");
1133 goto bail;
1135 } /* !preauth */
1137 ctx->prefix = "";
1138 ctx->trashnc = 1;
1139 return (struct store *)ctx;
1141 bail:
1142 imap_close_store(&ctx->gen);
1143 return NULL;
1146 static int imap_make_flags(int flags, char *buf)
1148 const char *s;
1149 unsigned i, d;
1151 for (i = d = 0; i < ARRAY_SIZE(Flags); i++)
1152 if (flags & (1 << i)) {
1153 buf[d++] = ' ';
1154 buf[d++] = '\\';
1155 for (s = Flags[i]; *s; s++)
1156 buf[d++] = *s;
1158 buf[0] = '(';
1159 buf[d++] = ')';
1160 return d;
1163 static int imap_store_msg(struct store *gctx, struct msg_data *data)
1165 struct imap_store *ctx = (struct imap_store *)gctx;
1166 struct imap *imap = ctx->imap;
1167 struct imap_cmd_cb cb;
1168 const char *prefix, *box;
1169 int ret, d;
1170 char flagstr[128];
1172 memset(&cb, 0, sizeof(cb));
1174 cb.dlen = data->len;
1175 cb.data = xmalloc(cb.dlen);
1176 memcpy(cb.data, data->data, data->len);
1178 d = 0;
1179 if (data->flags) {
1180 d = imap_make_flags(data->flags, flagstr);
1181 flagstr[d++] = ' ';
1183 flagstr[d] = 0;
1185 box = gctx->name;
1186 prefix = !strcmp(box, "INBOX") ? "" : ctx->prefix;
1187 cb.create = 0;
1188 ret = imap_exec_m(ctx, &cb, "APPEND \"%s%s\" %s", prefix, box, flagstr);
1189 imap->caps = imap->rcaps;
1190 if (ret != DRV_OK)
1191 return ret;
1192 gctx->count++;
1194 return DRV_OK;
1197 static void encode_html_chars(struct strbuf *p)
1199 int i;
1200 for (i = 0; i < p->len; i++) {
1201 if (p->buf[i] == '&')
1202 strbuf_splice(p, i, 1, "&amp;", 5);
1203 if (p->buf[i] == '<')
1204 strbuf_splice(p, i, 1, "&lt;", 4);
1205 if (p->buf[i] == '>')
1206 strbuf_splice(p, i, 1, "&gt;", 4);
1207 if (p->buf[i] == '"')
1208 strbuf_splice(p, i, 1, "&quot;", 6);
1211 static void wrap_in_html(struct msg_data *msg)
1213 struct strbuf buf = STRBUF_INIT;
1214 struct strbuf **lines;
1215 struct strbuf **p;
1216 static char *content_type = "Content-Type: text/html;\n";
1217 static char *pre_open = "<pre>\n";
1218 static char *pre_close = "</pre>\n";
1219 int added_header = 0;
1221 strbuf_attach(&buf, msg->data, msg->len, msg->len);
1222 lines = strbuf_split(&buf, '\n');
1223 strbuf_release(&buf);
1224 for (p = lines; *p; p++) {
1225 if (! added_header) {
1226 if ((*p)->len == 1 && *((*p)->buf) == '\n') {
1227 strbuf_addstr(&buf, content_type);
1228 strbuf_addbuf(&buf, *p);
1229 strbuf_addstr(&buf, pre_open);
1230 added_header = 1;
1231 continue;
1234 else
1235 encode_html_chars(*p);
1236 strbuf_addbuf(&buf, *p);
1238 strbuf_addstr(&buf, pre_close);
1239 strbuf_list_free(lines);
1240 msg->len = buf.len;
1241 msg->data = strbuf_detach(&buf, NULL);
1244 #define CHUNKSIZE 0x1000
1246 static int read_message(FILE *f, struct msg_data *msg)
1248 struct strbuf buf = STRBUF_INIT;
1250 memset(msg, 0, sizeof(*msg));
1252 do {
1253 if (strbuf_fread(&buf, CHUNKSIZE, f) <= 0)
1254 break;
1255 } while (!feof(f));
1257 msg->len = buf.len;
1258 msg->data = strbuf_detach(&buf, NULL);
1259 return msg->len;
1262 static int count_messages(struct msg_data *msg)
1264 int count = 0;
1265 char *p = msg->data;
1267 while (1) {
1268 if (!prefixcmp(p, "From ")) {
1269 count++;
1270 p += 5;
1272 p = strstr(p+5, "\nFrom ");
1273 if (!p)
1274 break;
1275 p++;
1277 return count;
1280 static int split_msg(struct msg_data *all_msgs, struct msg_data *msg, int *ofs)
1282 char *p, *data;
1284 memset(msg, 0, sizeof *msg);
1285 if (*ofs >= all_msgs->len)
1286 return 0;
1288 data = &all_msgs->data[*ofs];
1289 msg->len = all_msgs->len - *ofs;
1291 if (msg->len < 5 || prefixcmp(data, "From "))
1292 return 0;
1294 p = strchr(data, '\n');
1295 if (p) {
1296 p = &p[1];
1297 msg->len -= p-data;
1298 *ofs += p-data;
1299 data = p;
1302 p = strstr(data, "\nFrom ");
1303 if (p)
1304 msg->len = &p[1] - data;
1306 msg->data = xmemdupz(data, msg->len);
1307 *ofs += msg->len;
1308 return 1;
1311 static struct imap_server_conf server = {
1312 NULL, /* name */
1313 NULL, /* tunnel */
1314 NULL, /* host */
1315 0, /* port */
1316 NULL, /* user */
1317 NULL, /* pass */
1318 0, /* use_ssl */
1319 1, /* ssl_verify */
1320 0, /* use_html */
1323 static char *imap_folder;
1325 static int git_imap_config(const char *key, const char *val, void *cb)
1327 char imap_key[] = "imap.";
1329 if (strncmp(key, imap_key, sizeof imap_key - 1))
1330 return 0;
1332 if (!val)
1333 return config_error_nonbool(key);
1335 key += sizeof imap_key - 1;
1337 if (!strcmp("folder", key)) {
1338 imap_folder = xstrdup(val);
1339 } else if (!strcmp("host", key)) {
1340 if (!prefixcmp(val, "imap:"))
1341 val += 5;
1342 else if (!prefixcmp(val, "imaps:")) {
1343 val += 6;
1344 server.use_ssl = 1;
1346 if (!prefixcmp(val, "//"))
1347 val += 2;
1348 server.host = xstrdup(val);
1349 } else if (!strcmp("user", key))
1350 server.user = xstrdup(val);
1351 else if (!strcmp("pass", key))
1352 server.pass = xstrdup(val);
1353 else if (!strcmp("port", key))
1354 server.port = git_config_int(key, val);
1355 else if (!strcmp("tunnel", key))
1356 server.tunnel = xstrdup(val);
1357 else if (!strcmp("sslverify", key))
1358 server.ssl_verify = git_config_bool(key, val);
1359 else if (!strcmp("preformattedHTML", key))
1360 server.use_html = git_config_bool(key, val);
1361 return 0;
1364 int main(int argc, char **argv)
1366 struct msg_data all_msgs, msg;
1367 struct store *ctx = NULL;
1368 int ofs = 0;
1369 int r;
1370 int total, n = 0;
1371 int nongit_ok;
1373 git_extract_argv0_path(argv[0]);
1375 if (argc != 1)
1376 usage(imap_send_usage);
1378 setup_git_directory_gently(&nongit_ok);
1379 git_config(git_imap_config, NULL);
1381 if (!server.port)
1382 server.port = server.use_ssl ? 993 : 143;
1384 if (!imap_folder) {
1385 fprintf(stderr, "no imap store specified\n");
1386 return 1;
1388 if (!server.host) {
1389 if (!server.tunnel) {
1390 fprintf(stderr, "no imap host specified\n");
1391 return 1;
1393 server.host = "tunnel";
1396 /* read the messages */
1397 if (!read_message(stdin, &all_msgs)) {
1398 fprintf(stderr, "nothing to send\n");
1399 return 1;
1402 total = count_messages(&all_msgs);
1403 if (!total) {
1404 fprintf(stderr, "no messages to send\n");
1405 return 1;
1408 /* write it to the imap server */
1409 ctx = imap_open_store(&server);
1410 if (!ctx) {
1411 fprintf(stderr, "failed to open store\n");
1412 return 1;
1415 fprintf(stderr, "sending %d message%s\n", total, (total != 1) ? "s" : "");
1416 ctx->name = imap_folder;
1417 while (1) {
1418 unsigned percent = n * 100 / total;
1419 fprintf(stderr, "%4u%% (%d/%d) done\r", percent, n, total);
1420 if (!split_msg(&all_msgs, &msg, &ofs))
1421 break;
1422 if (server.use_html)
1423 wrap_in_html(&msg);
1424 r = imap_store_msg(ctx, &msg);
1425 if (r != DRV_OK)
1426 break;
1427 n++;
1429 fprintf(stderr, "\n");
1431 imap_close_store(ctx);
1433 return 0;