Document the --histogram diff option
[git/mingw/4msysgit.git] / imap-send.c
blob9992233b96ba50f5dec590e3cebb4e628f3d5c5a
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 #else
31 #include <openssl/evp.h>
32 #include <openssl/hmac.h>
33 #endif
35 struct store_conf {
36 char *name;
37 const char *path; /* should this be here? its interpretation is driver-specific */
38 char *map_inbox;
39 char *trash;
40 unsigned max_size; /* off_t is overkill */
41 unsigned trash_remote_new:1, trash_only_new:1;
44 /* For message->status */
45 #define M_RECENT (1<<0) /* unsyncable flag; maildir_* depend on this being 1<<0 */
46 #define M_DEAD (1<<1) /* expunged */
47 #define M_FLAGS (1<<2) /* flags fetched */
49 struct message {
50 struct message *next;
51 size_t size; /* zero implies "not fetched" */
52 int uid;
53 unsigned char flags, status;
56 struct store {
57 struct store_conf *conf; /* foreign */
59 /* currently open mailbox */
60 const char *name; /* foreign! maybe preset? */
61 char *path; /* own */
62 struct message *msgs; /* own */
63 int uidvalidity;
64 unsigned char opts; /* maybe preset? */
65 /* note that the following do _not_ reflect stats from msgs, but mailbox totals */
66 int count; /* # of messages */
67 int recent; /* # of recent messages - don't trust this beyond the initial read */
70 struct msg_data {
71 char *data;
72 int len;
73 unsigned char flags;
76 static const char imap_send_usage[] = "git imap-send < <mbox>";
78 #undef DRV_OK
79 #define DRV_OK 0
80 #define DRV_MSG_BAD -1
81 #define DRV_BOX_BAD -2
82 #define DRV_STORE_BAD -3
84 static int Verbose, Quiet;
86 __attribute__((format (printf, 1, 2)))
87 static void imap_info(const char *, ...);
88 __attribute__((format (printf, 1, 2)))
89 static void imap_warn(const char *, ...);
91 static char *next_arg(char **);
93 static void free_generic_messages(struct message *);
95 __attribute__((format (printf, 3, 4)))
96 static int nfsnprintf(char *buf, int blen, const char *fmt, ...);
98 static int nfvasprintf(char **strp, const char *fmt, va_list ap)
100 int len;
101 char tmp[8192];
103 len = vsnprintf(tmp, sizeof(tmp), fmt, ap);
104 if (len < 0)
105 die("Fatal: Out of memory");
106 if (len >= sizeof(tmp))
107 die("imap command overflow!");
108 *strp = xmemdupz(tmp, len);
109 return len;
112 struct imap_server_conf {
113 char *name;
114 char *tunnel;
115 char *host;
116 int port;
117 char *user;
118 char *pass;
119 int use_ssl;
120 int ssl_verify;
121 int use_html;
122 char *auth_method;
125 static struct imap_server_conf server = {
126 NULL, /* name */
127 NULL, /* tunnel */
128 NULL, /* host */
129 0, /* port */
130 NULL, /* user */
131 NULL, /* pass */
132 0, /* use_ssl */
133 1, /* ssl_verify */
134 0, /* use_html */
135 NULL, /* auth_method */
138 struct imap_store_conf {
139 struct store_conf gen;
140 struct imap_server_conf *server;
141 unsigned use_namespace:1;
144 #define NIL (void *)0x1
145 #define LIST (void *)0x2
147 struct imap_list {
148 struct imap_list *next, *child;
149 char *val;
150 int len;
153 struct imap_socket {
154 int fd[2];
155 SSL *ssl;
158 struct imap_buffer {
159 struct imap_socket sock;
160 int bytes;
161 int offset;
162 char buf[1024];
165 struct imap_cmd;
167 struct imap {
168 int uidnext; /* from SELECT responses */
169 struct imap_list *ns_personal, *ns_other, *ns_shared; /* NAMESPACE info */
170 unsigned caps, rcaps; /* CAPABILITY results */
171 /* command queue */
172 int nexttag, num_in_progress, literal_pending;
173 struct imap_cmd *in_progress, **in_progress_append;
174 struct imap_buffer buf; /* this is BIG, so put it last */
177 struct imap_store {
178 struct store gen;
179 int uidvalidity;
180 struct imap *imap;
181 const char *prefix;
182 unsigned /*currentnc:1,*/ trashnc:1;
185 struct imap_cmd_cb {
186 int (*cont)(struct imap_store *ctx, struct imap_cmd *cmd, const char *prompt);
187 void (*done)(struct imap_store *ctx, struct imap_cmd *cmd, int response);
188 void *ctx;
189 char *data;
190 int dlen;
191 int uid;
192 unsigned create:1, trycreate:1;
195 struct imap_cmd {
196 struct imap_cmd *next;
197 struct imap_cmd_cb cb;
198 char *cmd;
199 int tag;
202 #define CAP(cap) (imap->caps & (1 << (cap)))
204 enum CAPABILITY {
205 NOLOGIN = 0,
206 UIDPLUS,
207 LITERALPLUS,
208 NAMESPACE,
209 STARTTLS,
210 AUTH_CRAM_MD5
213 static const char *cap_list[] = {
214 "LOGINDISABLED",
215 "UIDPLUS",
216 "LITERAL+",
217 "NAMESPACE",
218 "STARTTLS",
219 "AUTH=CRAM-MD5",
222 #define RESP_OK 0
223 #define RESP_NO 1
224 #define RESP_BAD 2
226 static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd);
229 static const char *Flags[] = {
230 "Draft",
231 "Flagged",
232 "Answered",
233 "Seen",
234 "Deleted",
237 #ifndef NO_OPENSSL
238 static void ssl_socket_perror(const char *func)
240 fprintf(stderr, "%s: %s\n", func, ERR_error_string(ERR_get_error(), NULL));
242 #endif
244 static void socket_perror(const char *func, struct imap_socket *sock, int ret)
246 #ifndef NO_OPENSSL
247 if (sock->ssl) {
248 int sslerr = SSL_get_error(sock->ssl, ret);
249 switch (sslerr) {
250 case SSL_ERROR_NONE:
251 break;
252 case SSL_ERROR_SYSCALL:
253 perror("SSL_connect");
254 break;
255 default:
256 ssl_socket_perror("SSL_connect");
257 break;
259 } else
260 #endif
262 if (ret < 0)
263 perror(func);
264 else
265 fprintf(stderr, "%s: unexpected EOF\n", func);
269 static int ssl_socket_connect(struct imap_socket *sock, int use_tls_only, int verify)
271 #ifdef NO_OPENSSL
272 fprintf(stderr, "SSL requested but SSL support not compiled in\n");
273 return -1;
274 #else
275 #if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
276 const SSL_METHOD *meth;
277 #else
278 SSL_METHOD *meth;
279 #endif
280 SSL_CTX *ctx;
281 int ret;
283 SSL_library_init();
284 SSL_load_error_strings();
286 if (use_tls_only)
287 meth = TLSv1_method();
288 else
289 meth = SSLv23_method();
291 if (!meth) {
292 ssl_socket_perror("SSLv23_method");
293 return -1;
296 ctx = SSL_CTX_new(meth);
298 if (verify)
299 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
301 if (!SSL_CTX_set_default_verify_paths(ctx)) {
302 ssl_socket_perror("SSL_CTX_set_default_verify_paths");
303 return -1;
305 sock->ssl = SSL_new(ctx);
306 if (!sock->ssl) {
307 ssl_socket_perror("SSL_new");
308 return -1;
310 if (!SSL_set_rfd(sock->ssl, sock->fd[0])) {
311 ssl_socket_perror("SSL_set_rfd");
312 return -1;
314 if (!SSL_set_wfd(sock->ssl, sock->fd[1])) {
315 ssl_socket_perror("SSL_set_wfd");
316 return -1;
319 ret = SSL_connect(sock->ssl);
320 if (ret <= 0) {
321 socket_perror("SSL_connect", sock, ret);
322 return -1;
325 return 0;
326 #endif
329 static int socket_read(struct imap_socket *sock, char *buf, int len)
331 ssize_t n;
332 #ifndef NO_OPENSSL
333 if (sock->ssl)
334 n = SSL_read(sock->ssl, buf, len);
335 else
336 #endif
337 n = xread(sock->fd[0], buf, len);
338 if (n <= 0) {
339 socket_perror("read", sock, n);
340 close(sock->fd[0]);
341 close(sock->fd[1]);
342 sock->fd[0] = sock->fd[1] = -1;
344 return n;
347 static int socket_write(struct imap_socket *sock, const char *buf, int len)
349 int n;
350 #ifndef NO_OPENSSL
351 if (sock->ssl)
352 n = SSL_write(sock->ssl, buf, len);
353 else
354 #endif
355 n = write_in_full(sock->fd[1], buf, len);
356 if (n != len) {
357 socket_perror("write", sock, n);
358 close(sock->fd[0]);
359 close(sock->fd[1]);
360 sock->fd[0] = sock->fd[1] = -1;
362 return n;
365 static void socket_shutdown(struct imap_socket *sock)
367 #ifndef NO_OPENSSL
368 if (sock->ssl) {
369 SSL_shutdown(sock->ssl);
370 SSL_free(sock->ssl);
372 #endif
373 close(sock->fd[0]);
374 close(sock->fd[1]);
377 /* simple line buffering */
378 static int buffer_gets(struct imap_buffer *b, char **s)
380 int n;
381 int start = b->offset;
383 *s = b->buf + start;
385 for (;;) {
386 /* make sure we have enough data to read the \r\n sequence */
387 if (b->offset + 1 >= b->bytes) {
388 if (start) {
389 /* shift down used bytes */
390 *s = b->buf;
392 assert(start <= b->bytes);
393 n = b->bytes - start;
395 if (n)
396 memmove(b->buf, b->buf + start, n);
397 b->offset -= start;
398 b->bytes = n;
399 start = 0;
402 n = socket_read(&b->sock, b->buf + b->bytes,
403 sizeof(b->buf) - b->bytes);
405 if (n <= 0)
406 return -1;
408 b->bytes += n;
411 if (b->buf[b->offset] == '\r') {
412 assert(b->offset + 1 < b->bytes);
413 if (b->buf[b->offset + 1] == '\n') {
414 b->buf[b->offset] = 0; /* terminate the string */
415 b->offset += 2; /* next line */
416 if (Verbose)
417 puts(*s);
418 return 0;
422 b->offset++;
424 /* not reached */
427 static void imap_info(const char *msg, ...)
429 va_list va;
431 if (!Quiet) {
432 va_start(va, msg);
433 vprintf(msg, va);
434 va_end(va);
435 fflush(stdout);
439 static void imap_warn(const char *msg, ...)
441 va_list va;
443 if (Quiet < 2) {
444 va_start(va, msg);
445 vfprintf(stderr, msg, va);
446 va_end(va);
450 static char *next_arg(char **s)
452 char *ret;
454 if (!s || !*s)
455 return NULL;
456 while (isspace((unsigned char) **s))
457 (*s)++;
458 if (!**s) {
459 *s = NULL;
460 return NULL;
462 if (**s == '"') {
463 ++*s;
464 ret = *s;
465 *s = strchr(*s, '"');
466 } else {
467 ret = *s;
468 while (**s && !isspace((unsigned char) **s))
469 (*s)++;
471 if (*s) {
472 if (**s)
473 *(*s)++ = 0;
474 if (!**s)
475 *s = NULL;
477 return ret;
480 static void free_generic_messages(struct message *msgs)
482 struct message *tmsg;
484 for (; msgs; msgs = tmsg) {
485 tmsg = msgs->next;
486 free(msgs);
490 static int nfsnprintf(char *buf, int blen, const char *fmt, ...)
492 int ret;
493 va_list va;
495 va_start(va, fmt);
496 if (blen <= 0 || (unsigned)(ret = vsnprintf(buf, blen, fmt, va)) >= (unsigned)blen)
497 die("Fatal: buffer too small. Please report a bug.");
498 va_end(va);
499 return ret;
502 static struct imap_cmd *v_issue_imap_cmd(struct imap_store *ctx,
503 struct imap_cmd_cb *cb,
504 const char *fmt, va_list ap)
506 struct imap *imap = ctx->imap;
507 struct imap_cmd *cmd;
508 int n, bufl;
509 char buf[1024];
511 cmd = xmalloc(sizeof(struct imap_cmd));
512 nfvasprintf(&cmd->cmd, fmt, ap);
513 cmd->tag = ++imap->nexttag;
515 if (cb)
516 cmd->cb = *cb;
517 else
518 memset(&cmd->cb, 0, sizeof(cmd->cb));
520 while (imap->literal_pending)
521 get_cmd_result(ctx, NULL);
523 if (!cmd->cb.data)
524 bufl = nfsnprintf(buf, sizeof(buf), "%d %s\r\n", cmd->tag, cmd->cmd);
525 else
526 bufl = nfsnprintf(buf, sizeof(buf), "%d %s{%d%s}\r\n",
527 cmd->tag, cmd->cmd, cmd->cb.dlen,
528 CAP(LITERALPLUS) ? "+" : "");
530 if (Verbose) {
531 if (imap->num_in_progress)
532 printf("(%d in progress) ", imap->num_in_progress);
533 if (memcmp(cmd->cmd, "LOGIN", 5))
534 printf(">>> %s", buf);
535 else
536 printf(">>> %d LOGIN <user> <pass>\n", cmd->tag);
538 if (socket_write(&imap->buf.sock, buf, bufl) != bufl) {
539 free(cmd->cmd);
540 free(cmd);
541 if (cb)
542 free(cb->data);
543 return NULL;
545 if (cmd->cb.data) {
546 if (CAP(LITERALPLUS)) {
547 n = socket_write(&imap->buf.sock, cmd->cb.data, cmd->cb.dlen);
548 free(cmd->cb.data);
549 if (n != cmd->cb.dlen ||
550 socket_write(&imap->buf.sock, "\r\n", 2) != 2) {
551 free(cmd->cmd);
552 free(cmd);
553 return NULL;
555 cmd->cb.data = NULL;
556 } else
557 imap->literal_pending = 1;
558 } else if (cmd->cb.cont)
559 imap->literal_pending = 1;
560 cmd->next = NULL;
561 *imap->in_progress_append = cmd;
562 imap->in_progress_append = &cmd->next;
563 imap->num_in_progress++;
564 return cmd;
567 __attribute__((format (printf, 3, 4)))
568 static struct imap_cmd *issue_imap_cmd(struct imap_store *ctx,
569 struct imap_cmd_cb *cb,
570 const char *fmt, ...)
572 struct imap_cmd *ret;
573 va_list ap;
575 va_start(ap, fmt);
576 ret = v_issue_imap_cmd(ctx, cb, fmt, ap);
577 va_end(ap);
578 return ret;
581 __attribute__((format (printf, 3, 4)))
582 static int imap_exec(struct imap_store *ctx, struct imap_cmd_cb *cb,
583 const char *fmt, ...)
585 va_list ap;
586 struct imap_cmd *cmdp;
588 va_start(ap, fmt);
589 cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
590 va_end(ap);
591 if (!cmdp)
592 return RESP_BAD;
594 return get_cmd_result(ctx, cmdp);
597 __attribute__((format (printf, 3, 4)))
598 static int imap_exec_m(struct imap_store *ctx, struct imap_cmd_cb *cb,
599 const char *fmt, ...)
601 va_list ap;
602 struct imap_cmd *cmdp;
604 va_start(ap, fmt);
605 cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
606 va_end(ap);
607 if (!cmdp)
608 return DRV_STORE_BAD;
610 switch (get_cmd_result(ctx, cmdp)) {
611 case RESP_BAD: return DRV_STORE_BAD;
612 case RESP_NO: return DRV_MSG_BAD;
613 default: return DRV_OK;
617 static int is_atom(struct imap_list *list)
619 return list && list->val && list->val != NIL && list->val != LIST;
622 static int is_list(struct imap_list *list)
624 return list && list->val == LIST;
627 static void free_list(struct imap_list *list)
629 struct imap_list *tmp;
631 for (; list; list = tmp) {
632 tmp = list->next;
633 if (is_list(list))
634 free_list(list->child);
635 else if (is_atom(list))
636 free(list->val);
637 free(list);
641 static int parse_imap_list_l(struct imap *imap, char **sp, struct imap_list **curp, int level)
643 struct imap_list *cur;
644 char *s = *sp, *p;
645 int n, bytes;
647 for (;;) {
648 while (isspace((unsigned char)*s))
649 s++;
650 if (level && *s == ')') {
651 s++;
652 break;
654 *curp = cur = xmalloc(sizeof(*cur));
655 curp = &cur->next;
656 cur->val = NULL; /* for clean bail */
657 if (*s == '(') {
658 /* sublist */
659 s++;
660 cur->val = LIST;
661 if (parse_imap_list_l(imap, &s, &cur->child, level + 1))
662 goto bail;
663 } else if (imap && *s == '{') {
664 /* literal */
665 bytes = cur->len = strtol(s + 1, &s, 10);
666 if (*s != '}')
667 goto bail;
669 s = cur->val = xmalloc(cur->len);
671 /* dump whats left over in the input buffer */
672 n = imap->buf.bytes - imap->buf.offset;
674 if (n > bytes)
675 /* the entire message fit in the buffer */
676 n = bytes;
678 memcpy(s, imap->buf.buf + imap->buf.offset, n);
679 s += n;
680 bytes -= n;
682 /* mark that we used part of the buffer */
683 imap->buf.offset += n;
685 /* now read the rest of the message */
686 while (bytes > 0) {
687 if ((n = socket_read(&imap->buf.sock, s, bytes)) <= 0)
688 goto bail;
689 s += n;
690 bytes -= n;
693 if (buffer_gets(&imap->buf, &s))
694 goto bail;
695 } else if (*s == '"') {
696 /* quoted string */
697 s++;
698 p = s;
699 for (; *s != '"'; s++)
700 if (!*s)
701 goto bail;
702 cur->len = s - p;
703 s++;
704 cur->val = xmemdupz(p, cur->len);
705 } else {
706 /* atom */
707 p = s;
708 for (; *s && !isspace((unsigned char)*s); s++)
709 if (level && *s == ')')
710 break;
711 cur->len = s - p;
712 if (cur->len == 3 && !memcmp("NIL", p, 3))
713 cur->val = NIL;
714 else
715 cur->val = xmemdupz(p, cur->len);
718 if (!level)
719 break;
720 if (!*s)
721 goto bail;
723 *sp = s;
724 *curp = NULL;
725 return 0;
727 bail:
728 *curp = NULL;
729 return -1;
732 static struct imap_list *parse_imap_list(struct imap *imap, char **sp)
734 struct imap_list *head;
736 if (!parse_imap_list_l(imap, sp, &head, 0))
737 return head;
738 free_list(head);
739 return NULL;
742 static struct imap_list *parse_list(char **sp)
744 return parse_imap_list(NULL, sp);
747 static void parse_capability(struct imap *imap, char *cmd)
749 char *arg;
750 unsigned i;
752 imap->caps = 0x80000000;
753 while ((arg = next_arg(&cmd)))
754 for (i = 0; i < ARRAY_SIZE(cap_list); i++)
755 if (!strcmp(cap_list[i], arg))
756 imap->caps |= 1 << i;
757 imap->rcaps = imap->caps;
760 static int parse_response_code(struct imap_store *ctx, struct imap_cmd_cb *cb,
761 char *s)
763 struct imap *imap = ctx->imap;
764 char *arg, *p;
766 if (*s != '[')
767 return RESP_OK; /* no response code */
768 s++;
769 if (!(p = strchr(s, ']'))) {
770 fprintf(stderr, "IMAP error: malformed response code\n");
771 return RESP_BAD;
773 *p++ = 0;
774 arg = next_arg(&s);
775 if (!strcmp("UIDVALIDITY", arg)) {
776 if (!(arg = next_arg(&s)) || !(ctx->gen.uidvalidity = atoi(arg))) {
777 fprintf(stderr, "IMAP error: malformed UIDVALIDITY status\n");
778 return RESP_BAD;
780 } else if (!strcmp("UIDNEXT", arg)) {
781 if (!(arg = next_arg(&s)) || !(imap->uidnext = atoi(arg))) {
782 fprintf(stderr, "IMAP error: malformed NEXTUID status\n");
783 return RESP_BAD;
785 } else if (!strcmp("CAPABILITY", arg)) {
786 parse_capability(imap, s);
787 } else if (!strcmp("ALERT", arg)) {
788 /* RFC2060 says that these messages MUST be displayed
789 * to the user
791 for (; isspace((unsigned char)*p); p++);
792 fprintf(stderr, "*** IMAP ALERT *** %s\n", p);
793 } else if (cb && cb->ctx && !strcmp("APPENDUID", arg)) {
794 if (!(arg = next_arg(&s)) || !(ctx->gen.uidvalidity = atoi(arg)) ||
795 !(arg = next_arg(&s)) || !(*(int *)cb->ctx = atoi(arg))) {
796 fprintf(stderr, "IMAP error: malformed APPENDUID status\n");
797 return RESP_BAD;
800 return RESP_OK;
803 static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd)
805 struct imap *imap = ctx->imap;
806 struct imap_cmd *cmdp, **pcmdp, *ncmdp;
807 char *cmd, *arg, *arg1, *p;
808 int n, resp, resp2, tag;
810 for (;;) {
811 if (buffer_gets(&imap->buf, &cmd))
812 return RESP_BAD;
814 arg = next_arg(&cmd);
815 if (*arg == '*') {
816 arg = next_arg(&cmd);
817 if (!arg) {
818 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
819 return RESP_BAD;
822 if (!strcmp("NAMESPACE", arg)) {
823 imap->ns_personal = parse_list(&cmd);
824 imap->ns_other = parse_list(&cmd);
825 imap->ns_shared = parse_list(&cmd);
826 } else if (!strcmp("OK", arg) || !strcmp("BAD", arg) ||
827 !strcmp("NO", arg) || !strcmp("BYE", arg)) {
828 if ((resp = parse_response_code(ctx, NULL, cmd)) != RESP_OK)
829 return resp;
830 } else if (!strcmp("CAPABILITY", arg))
831 parse_capability(imap, cmd);
832 else if ((arg1 = next_arg(&cmd))) {
833 if (!strcmp("EXISTS", arg1))
834 ctx->gen.count = atoi(arg);
835 else if (!strcmp("RECENT", arg1))
836 ctx->gen.recent = atoi(arg);
837 } else {
838 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
839 return RESP_BAD;
841 } else if (!imap->in_progress) {
842 fprintf(stderr, "IMAP error: unexpected reply: %s %s\n", arg, cmd ? cmd : "");
843 return RESP_BAD;
844 } else if (*arg == '+') {
845 /* This can happen only with the last command underway, as
846 it enforces a round-trip. */
847 cmdp = (struct imap_cmd *)((char *)imap->in_progress_append -
848 offsetof(struct imap_cmd, next));
849 if (cmdp->cb.data) {
850 n = socket_write(&imap->buf.sock, cmdp->cb.data, cmdp->cb.dlen);
851 free(cmdp->cb.data);
852 cmdp->cb.data = NULL;
853 if (n != (int)cmdp->cb.dlen)
854 return RESP_BAD;
855 } else if (cmdp->cb.cont) {
856 if (cmdp->cb.cont(ctx, cmdp, cmd))
857 return RESP_BAD;
858 } else {
859 fprintf(stderr, "IMAP error: unexpected command continuation request\n");
860 return RESP_BAD;
862 if (socket_write(&imap->buf.sock, "\r\n", 2) != 2)
863 return RESP_BAD;
864 if (!cmdp->cb.cont)
865 imap->literal_pending = 0;
866 if (!tcmd)
867 return DRV_OK;
868 } else {
869 tag = atoi(arg);
870 for (pcmdp = &imap->in_progress; (cmdp = *pcmdp); pcmdp = &cmdp->next)
871 if (cmdp->tag == tag)
872 goto gottag;
873 fprintf(stderr, "IMAP error: unexpected tag %s\n", arg);
874 return RESP_BAD;
875 gottag:
876 if (!(*pcmdp = cmdp->next))
877 imap->in_progress_append = pcmdp;
878 imap->num_in_progress--;
879 if (cmdp->cb.cont || cmdp->cb.data)
880 imap->literal_pending = 0;
881 arg = next_arg(&cmd);
882 if (!strcmp("OK", arg))
883 resp = DRV_OK;
884 else {
885 if (!strcmp("NO", arg)) {
886 if (cmdp->cb.create && cmd && (cmdp->cb.trycreate || !memcmp(cmd, "[TRYCREATE]", 11))) { /* SELECT, APPEND or UID COPY */
887 p = strchr(cmdp->cmd, '"');
888 if (!issue_imap_cmd(ctx, NULL, "CREATE \"%.*s\"", (int)(strchr(p + 1, '"') - p + 1), p)) {
889 resp = RESP_BAD;
890 goto normal;
892 /* not waiting here violates the spec, but a server that does not
893 grok this nonetheless violates it too. */
894 cmdp->cb.create = 0;
895 if (!(ncmdp = issue_imap_cmd(ctx, &cmdp->cb, "%s", cmdp->cmd))) {
896 resp = RESP_BAD;
897 goto normal;
899 free(cmdp->cmd);
900 free(cmdp);
901 if (!tcmd)
902 return 0; /* ignored */
903 if (cmdp == tcmd)
904 tcmd = ncmdp;
905 continue;
907 resp = RESP_NO;
908 } else /*if (!strcmp("BAD", arg))*/
909 resp = RESP_BAD;
910 fprintf(stderr, "IMAP command '%s' returned response (%s) - %s\n",
911 memcmp(cmdp->cmd, "LOGIN", 5) ?
912 cmdp->cmd : "LOGIN <user> <pass>",
913 arg, cmd ? cmd : "");
915 if ((resp2 = parse_response_code(ctx, &cmdp->cb, cmd)) > resp)
916 resp = resp2;
917 normal:
918 if (cmdp->cb.done)
919 cmdp->cb.done(ctx, cmdp, resp);
920 free(cmdp->cb.data);
921 free(cmdp->cmd);
922 free(cmdp);
923 if (!tcmd || tcmd == cmdp)
924 return resp;
927 /* not reached */
930 static void imap_close_server(struct imap_store *ictx)
932 struct imap *imap = ictx->imap;
934 if (imap->buf.sock.fd[0] != -1) {
935 imap_exec(ictx, NULL, "LOGOUT");
936 socket_shutdown(&imap->buf.sock);
938 free_list(imap->ns_personal);
939 free_list(imap->ns_other);
940 free_list(imap->ns_shared);
941 free(imap);
944 static void imap_close_store(struct store *ctx)
946 imap_close_server((struct imap_store *)ctx);
947 free_generic_messages(ctx->msgs);
948 free(ctx);
951 #ifndef NO_OPENSSL
954 * hexchar() and cram() functions are based on the code from the isync
955 * project (http://isync.sf.net/).
957 static char hexchar(unsigned int b)
959 return b < 10 ? '0' + b : 'a' + (b - 10);
962 #define ENCODED_SIZE(n) (4*((n+2)/3))
963 static char *cram(const char *challenge_64, const char *user, const char *pass)
965 int i, resp_len, encoded_len, decoded_len;
966 HMAC_CTX hmac;
967 unsigned char hash[16];
968 char hex[33];
969 char *response, *response_64, *challenge;
972 * length of challenge_64 (i.e. base-64 encoded string) is a good
973 * enough upper bound for challenge (decoded result).
975 encoded_len = strlen(challenge_64);
976 challenge = xmalloc(encoded_len);
977 decoded_len = EVP_DecodeBlock((unsigned char *)challenge,
978 (unsigned char *)challenge_64, encoded_len);
979 if (decoded_len < 0)
980 die("invalid challenge %s", challenge_64);
981 HMAC_Init(&hmac, (unsigned char *)pass, strlen(pass), EVP_md5());
982 HMAC_Update(&hmac, (unsigned char *)challenge, decoded_len);
983 HMAC_Final(&hmac, hash, NULL);
984 HMAC_CTX_cleanup(&hmac);
986 hex[32] = 0;
987 for (i = 0; i < 16; i++) {
988 hex[2 * i] = hexchar((hash[i] >> 4) & 0xf);
989 hex[2 * i + 1] = hexchar(hash[i] & 0xf);
992 /* response: "<user> <digest in hex>" */
993 resp_len = strlen(user) + 1 + strlen(hex) + 1;
994 response = xmalloc(resp_len);
995 sprintf(response, "%s %s", user, hex);
997 response_64 = xmalloc(ENCODED_SIZE(resp_len) + 1);
998 encoded_len = EVP_EncodeBlock((unsigned char *)response_64,
999 (unsigned char *)response, resp_len);
1000 if (encoded_len < 0)
1001 die("EVP_EncodeBlock error");
1002 response_64[encoded_len] = '\0';
1003 return (char *)response_64;
1006 #else
1008 static char *cram(const char *challenge_64, const char *user, const char *pass)
1010 die("If you want to use CRAM-MD5 authenticate method, "
1011 "you have to build git-imap-send with OpenSSL library.");
1014 #endif
1016 static int auth_cram_md5(struct imap_store *ctx, struct imap_cmd *cmd, const char *prompt)
1018 int ret;
1019 char *response;
1021 response = cram(prompt, server.user, server.pass);
1023 ret = socket_write(&ctx->imap->buf.sock, response, strlen(response));
1024 if (ret != strlen(response))
1025 return error("IMAP error: sending response failed\n");
1027 free(response);
1029 return 0;
1032 static struct store *imap_open_store(struct imap_server_conf *srvc)
1034 struct imap_store *ctx;
1035 struct imap *imap;
1036 char *arg, *rsp;
1037 int s = -1, preauth;
1039 ctx = xcalloc(sizeof(*ctx), 1);
1041 ctx->imap = imap = xcalloc(sizeof(*imap), 1);
1042 imap->buf.sock.fd[0] = imap->buf.sock.fd[1] = -1;
1043 imap->in_progress_append = &imap->in_progress;
1045 /* open connection to IMAP server */
1047 if (srvc->tunnel) {
1048 const char *argv[] = { srvc->tunnel, NULL };
1049 struct child_process tunnel = {NULL};
1051 imap_info("Starting tunnel '%s'... ", srvc->tunnel);
1053 tunnel.argv = argv;
1054 tunnel.use_shell = 1;
1055 tunnel.in = -1;
1056 tunnel.out = -1;
1057 if (start_command(&tunnel))
1058 die("cannot start proxy %s", argv[0]);
1060 imap->buf.sock.fd[0] = tunnel.out;
1061 imap->buf.sock.fd[1] = tunnel.in;
1063 imap_info("ok\n");
1064 } else {
1065 #ifndef NO_IPV6
1066 struct addrinfo hints, *ai0, *ai;
1067 int gai;
1068 char portstr[6];
1070 snprintf(portstr, sizeof(portstr), "%d", srvc->port);
1072 memset(&hints, 0, sizeof(hints));
1073 hints.ai_socktype = SOCK_STREAM;
1074 hints.ai_protocol = IPPROTO_TCP;
1076 imap_info("Resolving %s... ", srvc->host);
1077 gai = getaddrinfo(srvc->host, portstr, &hints, &ai);
1078 if (gai) {
1079 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai));
1080 goto bail;
1082 imap_info("ok\n");
1084 for (ai0 = ai; ai; ai = ai->ai_next) {
1085 char addr[NI_MAXHOST];
1087 s = socket(ai->ai_family, ai->ai_socktype,
1088 ai->ai_protocol);
1089 if (s < 0)
1090 continue;
1092 getnameinfo(ai->ai_addr, ai->ai_addrlen, addr,
1093 sizeof(addr), NULL, 0, NI_NUMERICHOST);
1094 imap_info("Connecting to [%s]:%s... ", addr, portstr);
1096 if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0) {
1097 close(s);
1098 s = -1;
1099 perror("connect");
1100 continue;
1103 break;
1105 freeaddrinfo(ai0);
1106 #else /* NO_IPV6 */
1107 struct hostent *he;
1108 struct sockaddr_in addr;
1110 memset(&addr, 0, sizeof(addr));
1111 addr.sin_port = htons(srvc->port);
1112 addr.sin_family = AF_INET;
1114 imap_info("Resolving %s... ", srvc->host);
1115 he = gethostbyname(srvc->host);
1116 if (!he) {
1117 perror("gethostbyname");
1118 goto bail;
1120 imap_info("ok\n");
1122 addr.sin_addr.s_addr = *((int *) he->h_addr_list[0]);
1124 s = socket(PF_INET, SOCK_STREAM, 0);
1126 imap_info("Connecting to %s:%hu... ", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
1127 if (connect(s, (struct sockaddr *)&addr, sizeof(addr))) {
1128 close(s);
1129 s = -1;
1130 perror("connect");
1132 #endif
1133 if (s < 0) {
1134 fputs("Error: unable to connect to server.\n", stderr);
1135 goto bail;
1138 imap->buf.sock.fd[0] = s;
1139 imap->buf.sock.fd[1] = dup(s);
1141 if (srvc->use_ssl &&
1142 ssl_socket_connect(&imap->buf.sock, 0, srvc->ssl_verify)) {
1143 close(s);
1144 goto bail;
1146 imap_info("ok\n");
1149 /* read the greeting string */
1150 if (buffer_gets(&imap->buf, &rsp)) {
1151 fprintf(stderr, "IMAP error: no greeting response\n");
1152 goto bail;
1154 arg = next_arg(&rsp);
1155 if (!arg || *arg != '*' || (arg = next_arg(&rsp)) == NULL) {
1156 fprintf(stderr, "IMAP error: invalid greeting response\n");
1157 goto bail;
1159 preauth = 0;
1160 if (!strcmp("PREAUTH", arg))
1161 preauth = 1;
1162 else if (strcmp("OK", arg) != 0) {
1163 fprintf(stderr, "IMAP error: unknown greeting response\n");
1164 goto bail;
1166 parse_response_code(ctx, NULL, rsp);
1167 if (!imap->caps && imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1168 goto bail;
1170 if (!preauth) {
1171 #ifndef NO_OPENSSL
1172 if (!srvc->use_ssl && CAP(STARTTLS)) {
1173 if (imap_exec(ctx, NULL, "STARTTLS") != RESP_OK)
1174 goto bail;
1175 if (ssl_socket_connect(&imap->buf.sock, 1,
1176 srvc->ssl_verify))
1177 goto bail;
1178 /* capabilities may have changed, so get the new capabilities */
1179 if (imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1180 goto bail;
1182 #endif
1183 imap_info("Logging in...\n");
1184 if (!srvc->user) {
1185 fprintf(stderr, "Skipping server %s, no user\n", srvc->host);
1186 goto bail;
1188 if (!srvc->pass) {
1189 char prompt[80];
1190 sprintf(prompt, "Password (%s@%s): ", srvc->user, srvc->host);
1191 arg = git_getpass(prompt);
1192 if (!arg) {
1193 perror("getpass");
1194 exit(1);
1196 if (!*arg) {
1197 fprintf(stderr, "Skipping account %s@%s, no password\n", srvc->user, srvc->host);
1198 goto bail;
1201 * getpass() returns a pointer to a static buffer. make a copy
1202 * for long term storage.
1204 srvc->pass = xstrdup(arg);
1206 if (CAP(NOLOGIN)) {
1207 fprintf(stderr, "Skipping account %s@%s, server forbids LOGIN\n", srvc->user, srvc->host);
1208 goto bail;
1211 if (srvc->auth_method) {
1212 struct imap_cmd_cb cb;
1214 if (!strcmp(srvc->auth_method, "CRAM-MD5")) {
1215 if (!CAP(AUTH_CRAM_MD5)) {
1216 fprintf(stderr, "You specified"
1217 "CRAM-MD5 as authentication method, "
1218 "but %s doesn't support it.\n", srvc->host);
1219 goto bail;
1221 /* CRAM-MD5 */
1223 memset(&cb, 0, sizeof(cb));
1224 cb.cont = auth_cram_md5;
1225 if (imap_exec(ctx, &cb, "AUTHENTICATE CRAM-MD5") != RESP_OK) {
1226 fprintf(stderr, "IMAP error: AUTHENTICATE CRAM-MD5 failed\n");
1227 goto bail;
1229 } else {
1230 fprintf(stderr, "Unknown authentication method:%s\n", srvc->host);
1231 goto bail;
1233 } else {
1234 if (!imap->buf.sock.ssl)
1235 imap_warn("*** IMAP Warning *** Password is being "
1236 "sent in the clear\n");
1237 if (imap_exec(ctx, NULL, "LOGIN \"%s\" \"%s\"", srvc->user, srvc->pass) != RESP_OK) {
1238 fprintf(stderr, "IMAP error: LOGIN failed\n");
1239 goto bail;
1242 } /* !preauth */
1244 ctx->prefix = "";
1245 ctx->trashnc = 1;
1246 return (struct store *)ctx;
1248 bail:
1249 imap_close_store(&ctx->gen);
1250 return NULL;
1253 static int imap_make_flags(int flags, char *buf)
1255 const char *s;
1256 unsigned i, d;
1258 for (i = d = 0; i < ARRAY_SIZE(Flags); i++)
1259 if (flags & (1 << i)) {
1260 buf[d++] = ' ';
1261 buf[d++] = '\\';
1262 for (s = Flags[i]; *s; s++)
1263 buf[d++] = *s;
1265 buf[0] = '(';
1266 buf[d++] = ')';
1267 return d;
1270 static void lf_to_crlf(struct msg_data *msg)
1272 char *new;
1273 int i, j, lfnum = 0;
1275 if (msg->data[0] == '\n')
1276 lfnum++;
1277 for (i = 1; i < msg->len; i++) {
1278 if (msg->data[i - 1] != '\r' && msg->data[i] == '\n')
1279 lfnum++;
1282 new = xmalloc(msg->len + lfnum);
1283 if (msg->data[0] == '\n') {
1284 new[0] = '\r';
1285 new[1] = '\n';
1286 i = 1;
1287 j = 2;
1288 } else {
1289 new[0] = msg->data[0];
1290 i = 1;
1291 j = 1;
1293 for ( ; i < msg->len; i++) {
1294 if (msg->data[i] != '\n') {
1295 new[j++] = msg->data[i];
1296 continue;
1298 if (msg->data[i - 1] != '\r')
1299 new[j++] = '\r';
1300 /* otherwise it already had CR before */
1301 new[j++] = '\n';
1303 msg->len += lfnum;
1304 free(msg->data);
1305 msg->data = new;
1308 static int imap_store_msg(struct store *gctx, struct msg_data *data)
1310 struct imap_store *ctx = (struct imap_store *)gctx;
1311 struct imap *imap = ctx->imap;
1312 struct imap_cmd_cb cb;
1313 const char *prefix, *box;
1314 int ret, d;
1315 char flagstr[128];
1317 lf_to_crlf(data);
1318 memset(&cb, 0, sizeof(cb));
1320 cb.dlen = data->len;
1321 cb.data = xmalloc(cb.dlen);
1322 memcpy(cb.data, data->data, data->len);
1324 d = 0;
1325 if (data->flags) {
1326 d = imap_make_flags(data->flags, flagstr);
1327 flagstr[d++] = ' ';
1329 flagstr[d] = 0;
1331 box = gctx->name;
1332 prefix = !strcmp(box, "INBOX") ? "" : ctx->prefix;
1333 cb.create = 0;
1334 ret = imap_exec_m(ctx, &cb, "APPEND \"%s%s\" %s", prefix, box, flagstr);
1335 imap->caps = imap->rcaps;
1336 if (ret != DRV_OK)
1337 return ret;
1338 gctx->count++;
1340 return DRV_OK;
1343 static void encode_html_chars(struct strbuf *p)
1345 int i;
1346 for (i = 0; i < p->len; i++) {
1347 if (p->buf[i] == '&')
1348 strbuf_splice(p, i, 1, "&amp;", 5);
1349 if (p->buf[i] == '<')
1350 strbuf_splice(p, i, 1, "&lt;", 4);
1351 if (p->buf[i] == '>')
1352 strbuf_splice(p, i, 1, "&gt;", 4);
1353 if (p->buf[i] == '"')
1354 strbuf_splice(p, i, 1, "&quot;", 6);
1357 static void wrap_in_html(struct msg_data *msg)
1359 struct strbuf buf = STRBUF_INIT;
1360 struct strbuf **lines;
1361 struct strbuf **p;
1362 static char *content_type = "Content-Type: text/html;\n";
1363 static char *pre_open = "<pre>\n";
1364 static char *pre_close = "</pre>\n";
1365 int added_header = 0;
1367 strbuf_attach(&buf, msg->data, msg->len, msg->len);
1368 lines = strbuf_split(&buf, '\n');
1369 strbuf_release(&buf);
1370 for (p = lines; *p; p++) {
1371 if (! added_header) {
1372 if ((*p)->len == 1 && *((*p)->buf) == '\n') {
1373 strbuf_addstr(&buf, content_type);
1374 strbuf_addbuf(&buf, *p);
1375 strbuf_addstr(&buf, pre_open);
1376 added_header = 1;
1377 continue;
1380 else
1381 encode_html_chars(*p);
1382 strbuf_addbuf(&buf, *p);
1384 strbuf_addstr(&buf, pre_close);
1385 strbuf_list_free(lines);
1386 msg->len = buf.len;
1387 msg->data = strbuf_detach(&buf, NULL);
1390 #define CHUNKSIZE 0x1000
1392 static int read_message(FILE *f, struct msg_data *msg)
1394 struct strbuf buf = STRBUF_INIT;
1396 memset(msg, 0, sizeof(*msg));
1398 do {
1399 if (strbuf_fread(&buf, CHUNKSIZE, f) <= 0)
1400 break;
1401 } while (!feof(f));
1403 msg->len = buf.len;
1404 msg->data = strbuf_detach(&buf, NULL);
1405 return msg->len;
1408 static int count_messages(struct msg_data *msg)
1410 int count = 0;
1411 char *p = msg->data;
1413 while (1) {
1414 if (!prefixcmp(p, "From ")) {
1415 p = strstr(p+5, "\nFrom: ");
1416 if (!p) break;
1417 p = strstr(p+7, "\nDate: ");
1418 if (!p) break;
1419 p = strstr(p+7, "\nSubject: ");
1420 if (!p) break;
1421 p += 10;
1422 count++;
1424 p = strstr(p+5, "\nFrom ");
1425 if (!p)
1426 break;
1427 p++;
1429 return count;
1432 static int split_msg(struct msg_data *all_msgs, struct msg_data *msg, int *ofs)
1434 char *p, *data;
1436 memset(msg, 0, sizeof *msg);
1437 if (*ofs >= all_msgs->len)
1438 return 0;
1440 data = &all_msgs->data[*ofs];
1441 msg->len = all_msgs->len - *ofs;
1443 if (msg->len < 5 || prefixcmp(data, "From "))
1444 return 0;
1446 p = strchr(data, '\n');
1447 if (p) {
1448 p = &p[1];
1449 msg->len -= p-data;
1450 *ofs += p-data;
1451 data = p;
1454 p = strstr(data, "\nFrom ");
1455 if (p)
1456 msg->len = &p[1] - data;
1458 msg->data = xmemdupz(data, msg->len);
1459 *ofs += msg->len;
1460 return 1;
1463 static char *imap_folder;
1465 static int git_imap_config(const char *key, const char *val, void *cb)
1467 char imap_key[] = "imap.";
1469 if (strncmp(key, imap_key, sizeof imap_key - 1))
1470 return 0;
1472 key += sizeof imap_key - 1;
1474 /* check booleans first, and barf on others */
1475 if (!strcmp("sslverify", key))
1476 server.ssl_verify = git_config_bool(key, val);
1477 else if (!strcmp("preformattedhtml", key))
1478 server.use_html = git_config_bool(key, val);
1479 else if (!val)
1480 return config_error_nonbool(key);
1482 if (!strcmp("folder", key)) {
1483 imap_folder = xstrdup(val);
1484 } else if (!strcmp("host", key)) {
1485 if (!prefixcmp(val, "imap:"))
1486 val += 5;
1487 else if (!prefixcmp(val, "imaps:")) {
1488 val += 6;
1489 server.use_ssl = 1;
1491 if (!prefixcmp(val, "//"))
1492 val += 2;
1493 server.host = xstrdup(val);
1494 } else if (!strcmp("user", key))
1495 server.user = xstrdup(val);
1496 else if (!strcmp("pass", key))
1497 server.pass = xstrdup(val);
1498 else if (!strcmp("port", key))
1499 server.port = git_config_int(key, val);
1500 else if (!strcmp("tunnel", key))
1501 server.tunnel = xstrdup(val);
1502 else if (!strcmp("authmethod", key))
1503 server.auth_method = xstrdup(val);
1505 return 0;
1508 int main(int argc, char **argv)
1510 struct msg_data all_msgs, msg;
1511 struct store *ctx = NULL;
1512 int ofs = 0;
1513 int r;
1514 int total, n = 0;
1515 int nongit_ok;
1517 git_extract_argv0_path(argv[0]);
1519 if (argc != 1)
1520 usage(imap_send_usage);
1522 setup_git_directory_gently(&nongit_ok);
1523 git_config(git_imap_config, NULL);
1525 if (!server.port)
1526 server.port = server.use_ssl ? 993 : 143;
1528 if (!imap_folder) {
1529 fprintf(stderr, "no imap store specified\n");
1530 return 1;
1532 if (!server.host) {
1533 if (!server.tunnel) {
1534 fprintf(stderr, "no imap host specified\n");
1535 return 1;
1537 server.host = "tunnel";
1540 /* read the messages */
1541 if (!read_message(stdin, &all_msgs)) {
1542 fprintf(stderr, "nothing to send\n");
1543 return 1;
1546 total = count_messages(&all_msgs);
1547 if (!total) {
1548 fprintf(stderr, "no messages to send\n");
1549 return 1;
1552 /* write it to the imap server */
1553 ctx = imap_open_store(&server);
1554 if (!ctx) {
1555 fprintf(stderr, "failed to open store\n");
1556 return 1;
1559 fprintf(stderr, "sending %d message%s\n", total, (total != 1) ? "s" : "");
1560 ctx->name = imap_folder;
1561 while (1) {
1562 unsigned percent = n * 100 / total;
1563 fprintf(stderr, "%4u%% (%d/%d) done\r", percent, n, total);
1564 if (!split_msg(&all_msgs, &msg, &ofs))
1565 break;
1566 if (server.use_html)
1567 wrap_in_html(&msg);
1568 r = imap_store_msg(ctx, &msg);
1569 if (r != DRV_OK)
1570 break;
1571 n++;
1573 fprintf(stderr, "\n");
1575 imap_close_store(ctx);
1577 return 0;