Merge branch 'rs/clarify-entry-cmp-sslice'
[git.git] / imap-send.c
blob21dc20b57d392c5789043968d28a3b958b2b50c7
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 #include "prompt.h"
29 #ifdef NO_OPENSSL
30 typedef void *SSL;
31 #else
32 #include <openssl/evp.h>
33 #include <openssl/hmac.h>
34 #endif
36 static const char imap_send_usage[] = "git imap-send < <mbox>";
38 #undef DRV_OK
39 #define DRV_OK 0
40 #define DRV_MSG_BAD -1
41 #define DRV_BOX_BAD -2
42 #define DRV_STORE_BAD -3
44 static int Verbose, Quiet;
46 __attribute__((format (printf, 1, 2)))
47 static void imap_info(const char *, ...);
48 __attribute__((format (printf, 1, 2)))
49 static void imap_warn(const char *, ...);
51 static char *next_arg(char **);
53 __attribute__((format (printf, 3, 4)))
54 static int nfsnprintf(char *buf, int blen, const char *fmt, ...);
56 static int nfvasprintf(char **strp, const char *fmt, va_list ap)
58 int len;
59 char tmp[8192];
61 len = vsnprintf(tmp, sizeof(tmp), fmt, ap);
62 if (len < 0)
63 die("Fatal: Out of memory");
64 if (len >= sizeof(tmp))
65 die("imap command overflow!");
66 *strp = xmemdupz(tmp, len);
67 return len;
70 struct imap_server_conf {
71 char *name;
72 char *tunnel;
73 char *host;
74 int port;
75 char *user;
76 char *pass;
77 int use_ssl;
78 int ssl_verify;
79 int use_html;
80 char *auth_method;
83 static struct imap_server_conf server = {
84 NULL, /* name */
85 NULL, /* tunnel */
86 NULL, /* host */
87 0, /* port */
88 NULL, /* user */
89 NULL, /* pass */
90 0, /* use_ssl */
91 1, /* ssl_verify */
92 0, /* use_html */
93 NULL, /* auth_method */
96 struct imap_socket {
97 int fd[2];
98 SSL *ssl;
101 struct imap_buffer {
102 struct imap_socket sock;
103 int bytes;
104 int offset;
105 char buf[1024];
108 struct imap_cmd;
110 struct imap {
111 int uidnext; /* from SELECT responses */
112 unsigned caps, rcaps; /* CAPABILITY results */
113 /* command queue */
114 int nexttag, num_in_progress, literal_pending;
115 struct imap_cmd *in_progress, **in_progress_append;
116 struct imap_buffer buf; /* this is BIG, so put it last */
119 struct imap_store {
120 /* currently open mailbox */
121 const char *name; /* foreign! maybe preset? */
122 int uidvalidity;
123 struct imap *imap;
124 const char *prefix;
127 struct imap_cmd_cb {
128 int (*cont)(struct imap_store *ctx, struct imap_cmd *cmd, const char *prompt);
129 void (*done)(struct imap_store *ctx, struct imap_cmd *cmd, int response);
130 void *ctx;
131 char *data;
132 int dlen;
133 int uid;
134 unsigned create:1, trycreate:1;
137 struct imap_cmd {
138 struct imap_cmd *next;
139 struct imap_cmd_cb cb;
140 char *cmd;
141 int tag;
144 #define CAP(cap) (imap->caps & (1 << (cap)))
146 enum CAPABILITY {
147 NOLOGIN = 0,
148 UIDPLUS,
149 LITERALPLUS,
150 NAMESPACE,
151 STARTTLS,
152 AUTH_CRAM_MD5
155 static const char *cap_list[] = {
156 "LOGINDISABLED",
157 "UIDPLUS",
158 "LITERAL+",
159 "NAMESPACE",
160 "STARTTLS",
161 "AUTH=CRAM-MD5",
164 #define RESP_OK 0
165 #define RESP_NO 1
166 #define RESP_BAD 2
168 static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd);
171 #ifndef NO_OPENSSL
172 static void ssl_socket_perror(const char *func)
174 fprintf(stderr, "%s: %s\n", func, ERR_error_string(ERR_get_error(), NULL));
176 #endif
178 static void socket_perror(const char *func, struct imap_socket *sock, int ret)
180 #ifndef NO_OPENSSL
181 if (sock->ssl) {
182 int sslerr = SSL_get_error(sock->ssl, ret);
183 switch (sslerr) {
184 case SSL_ERROR_NONE:
185 break;
186 case SSL_ERROR_SYSCALL:
187 perror("SSL_connect");
188 break;
189 default:
190 ssl_socket_perror("SSL_connect");
191 break;
193 } else
194 #endif
196 if (ret < 0)
197 perror(func);
198 else
199 fprintf(stderr, "%s: unexpected EOF\n", func);
203 static int ssl_socket_connect(struct imap_socket *sock, int use_tls_only, int verify)
205 #ifdef NO_OPENSSL
206 fprintf(stderr, "SSL requested but SSL support not compiled in\n");
207 return -1;
208 #else
209 #if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
210 const SSL_METHOD *meth;
211 #else
212 SSL_METHOD *meth;
213 #endif
214 SSL_CTX *ctx;
215 int ret;
217 SSL_library_init();
218 SSL_load_error_strings();
220 if (use_tls_only)
221 meth = TLSv1_method();
222 else
223 meth = SSLv23_method();
225 if (!meth) {
226 ssl_socket_perror("SSLv23_method");
227 return -1;
230 ctx = SSL_CTX_new(meth);
232 if (verify)
233 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
235 if (!SSL_CTX_set_default_verify_paths(ctx)) {
236 ssl_socket_perror("SSL_CTX_set_default_verify_paths");
237 return -1;
239 sock->ssl = SSL_new(ctx);
240 if (!sock->ssl) {
241 ssl_socket_perror("SSL_new");
242 return -1;
244 if (!SSL_set_rfd(sock->ssl, sock->fd[0])) {
245 ssl_socket_perror("SSL_set_rfd");
246 return -1;
248 if (!SSL_set_wfd(sock->ssl, sock->fd[1])) {
249 ssl_socket_perror("SSL_set_wfd");
250 return -1;
253 ret = SSL_connect(sock->ssl);
254 if (ret <= 0) {
255 socket_perror("SSL_connect", sock, ret);
256 return -1;
259 return 0;
260 #endif
263 static int socket_read(struct imap_socket *sock, char *buf, int len)
265 ssize_t n;
266 #ifndef NO_OPENSSL
267 if (sock->ssl)
268 n = SSL_read(sock->ssl, buf, len);
269 else
270 #endif
271 n = xread(sock->fd[0], buf, len);
272 if (n <= 0) {
273 socket_perror("read", sock, n);
274 close(sock->fd[0]);
275 close(sock->fd[1]);
276 sock->fd[0] = sock->fd[1] = -1;
278 return n;
281 static int socket_write(struct imap_socket *sock, const char *buf, int len)
283 int n;
284 #ifndef NO_OPENSSL
285 if (sock->ssl)
286 n = SSL_write(sock->ssl, buf, len);
287 else
288 #endif
289 n = write_in_full(sock->fd[1], buf, len);
290 if (n != len) {
291 socket_perror("write", sock, n);
292 close(sock->fd[0]);
293 close(sock->fd[1]);
294 sock->fd[0] = sock->fd[1] = -1;
296 return n;
299 static void socket_shutdown(struct imap_socket *sock)
301 #ifndef NO_OPENSSL
302 if (sock->ssl) {
303 SSL_shutdown(sock->ssl);
304 SSL_free(sock->ssl);
306 #endif
307 close(sock->fd[0]);
308 close(sock->fd[1]);
311 /* simple line buffering */
312 static int buffer_gets(struct imap_buffer *b, char **s)
314 int n;
315 int start = b->offset;
317 *s = b->buf + start;
319 for (;;) {
320 /* make sure we have enough data to read the \r\n sequence */
321 if (b->offset + 1 >= b->bytes) {
322 if (start) {
323 /* shift down used bytes */
324 *s = b->buf;
326 assert(start <= b->bytes);
327 n = b->bytes - start;
329 if (n)
330 memmove(b->buf, b->buf + start, n);
331 b->offset -= start;
332 b->bytes = n;
333 start = 0;
336 n = socket_read(&b->sock, b->buf + b->bytes,
337 sizeof(b->buf) - b->bytes);
339 if (n <= 0)
340 return -1;
342 b->bytes += n;
345 if (b->buf[b->offset] == '\r') {
346 assert(b->offset + 1 < b->bytes);
347 if (b->buf[b->offset + 1] == '\n') {
348 b->buf[b->offset] = 0; /* terminate the string */
349 b->offset += 2; /* next line */
350 if (Verbose)
351 puts(*s);
352 return 0;
356 b->offset++;
358 /* not reached */
361 static void imap_info(const char *msg, ...)
363 va_list va;
365 if (!Quiet) {
366 va_start(va, msg);
367 vprintf(msg, va);
368 va_end(va);
369 fflush(stdout);
373 static void imap_warn(const char *msg, ...)
375 va_list va;
377 if (Quiet < 2) {
378 va_start(va, msg);
379 vfprintf(stderr, msg, va);
380 va_end(va);
384 static char *next_arg(char **s)
386 char *ret;
388 if (!s || !*s)
389 return NULL;
390 while (isspace((unsigned char) **s))
391 (*s)++;
392 if (!**s) {
393 *s = NULL;
394 return NULL;
396 if (**s == '"') {
397 ++*s;
398 ret = *s;
399 *s = strchr(*s, '"');
400 } else {
401 ret = *s;
402 while (**s && !isspace((unsigned char) **s))
403 (*s)++;
405 if (*s) {
406 if (**s)
407 *(*s)++ = 0;
408 if (!**s)
409 *s = NULL;
411 return ret;
414 static int nfsnprintf(char *buf, int blen, const char *fmt, ...)
416 int ret;
417 va_list va;
419 va_start(va, fmt);
420 if (blen <= 0 || (unsigned)(ret = vsnprintf(buf, blen, fmt, va)) >= (unsigned)blen)
421 die("Fatal: buffer too small. Please report a bug.");
422 va_end(va);
423 return ret;
426 static struct imap_cmd *v_issue_imap_cmd(struct imap_store *ctx,
427 struct imap_cmd_cb *cb,
428 const char *fmt, va_list ap)
430 struct imap *imap = ctx->imap;
431 struct imap_cmd *cmd;
432 int n, bufl;
433 char buf[1024];
435 cmd = xmalloc(sizeof(struct imap_cmd));
436 nfvasprintf(&cmd->cmd, fmt, ap);
437 cmd->tag = ++imap->nexttag;
439 if (cb)
440 cmd->cb = *cb;
441 else
442 memset(&cmd->cb, 0, sizeof(cmd->cb));
444 while (imap->literal_pending)
445 get_cmd_result(ctx, NULL);
447 if (!cmd->cb.data)
448 bufl = nfsnprintf(buf, sizeof(buf), "%d %s\r\n", cmd->tag, cmd->cmd);
449 else
450 bufl = nfsnprintf(buf, sizeof(buf), "%d %s{%d%s}\r\n",
451 cmd->tag, cmd->cmd, cmd->cb.dlen,
452 CAP(LITERALPLUS) ? "+" : "");
454 if (Verbose) {
455 if (imap->num_in_progress)
456 printf("(%d in progress) ", imap->num_in_progress);
457 if (memcmp(cmd->cmd, "LOGIN", 5))
458 printf(">>> %s", buf);
459 else
460 printf(">>> %d LOGIN <user> <pass>\n", cmd->tag);
462 if (socket_write(&imap->buf.sock, buf, bufl) != bufl) {
463 free(cmd->cmd);
464 free(cmd);
465 if (cb)
466 free(cb->data);
467 return NULL;
469 if (cmd->cb.data) {
470 if (CAP(LITERALPLUS)) {
471 n = socket_write(&imap->buf.sock, cmd->cb.data, cmd->cb.dlen);
472 free(cmd->cb.data);
473 if (n != cmd->cb.dlen ||
474 socket_write(&imap->buf.sock, "\r\n", 2) != 2) {
475 free(cmd->cmd);
476 free(cmd);
477 return NULL;
479 cmd->cb.data = NULL;
480 } else
481 imap->literal_pending = 1;
482 } else if (cmd->cb.cont)
483 imap->literal_pending = 1;
484 cmd->next = NULL;
485 *imap->in_progress_append = cmd;
486 imap->in_progress_append = &cmd->next;
487 imap->num_in_progress++;
488 return cmd;
491 __attribute__((format (printf, 3, 4)))
492 static struct imap_cmd *issue_imap_cmd(struct imap_store *ctx,
493 struct imap_cmd_cb *cb,
494 const char *fmt, ...)
496 struct imap_cmd *ret;
497 va_list ap;
499 va_start(ap, fmt);
500 ret = v_issue_imap_cmd(ctx, cb, fmt, ap);
501 va_end(ap);
502 return ret;
505 __attribute__((format (printf, 3, 4)))
506 static int imap_exec(struct imap_store *ctx, struct imap_cmd_cb *cb,
507 const char *fmt, ...)
509 va_list ap;
510 struct imap_cmd *cmdp;
512 va_start(ap, fmt);
513 cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
514 va_end(ap);
515 if (!cmdp)
516 return RESP_BAD;
518 return get_cmd_result(ctx, cmdp);
521 __attribute__((format (printf, 3, 4)))
522 static int imap_exec_m(struct imap_store *ctx, struct imap_cmd_cb *cb,
523 const char *fmt, ...)
525 va_list ap;
526 struct imap_cmd *cmdp;
528 va_start(ap, fmt);
529 cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
530 va_end(ap);
531 if (!cmdp)
532 return DRV_STORE_BAD;
534 switch (get_cmd_result(ctx, cmdp)) {
535 case RESP_BAD: return DRV_STORE_BAD;
536 case RESP_NO: return DRV_MSG_BAD;
537 default: return DRV_OK;
541 static int skip_imap_list_l(char **sp, int level)
543 char *s = *sp;
545 for (;;) {
546 while (isspace((unsigned char)*s))
547 s++;
548 if (level && *s == ')') {
549 s++;
550 break;
552 if (*s == '(') {
553 /* sublist */
554 s++;
555 if (skip_imap_list_l(&s, level + 1))
556 goto bail;
557 } else if (*s == '"') {
558 /* quoted string */
559 s++;
560 for (; *s != '"'; s++)
561 if (!*s)
562 goto bail;
563 s++;
564 } else {
565 /* atom */
566 for (; *s && !isspace((unsigned char)*s); s++)
567 if (level && *s == ')')
568 break;
571 if (!level)
572 break;
573 if (!*s)
574 goto bail;
576 *sp = s;
577 return 0;
579 bail:
580 return -1;
583 static void skip_list(char **sp)
585 skip_imap_list_l(sp, 0);
588 static void parse_capability(struct imap *imap, char *cmd)
590 char *arg;
591 unsigned i;
593 imap->caps = 0x80000000;
594 while ((arg = next_arg(&cmd)))
595 for (i = 0; i < ARRAY_SIZE(cap_list); i++)
596 if (!strcmp(cap_list[i], arg))
597 imap->caps |= 1 << i;
598 imap->rcaps = imap->caps;
601 static int parse_response_code(struct imap_store *ctx, struct imap_cmd_cb *cb,
602 char *s)
604 struct imap *imap = ctx->imap;
605 char *arg, *p;
607 if (*s != '[')
608 return RESP_OK; /* no response code */
609 s++;
610 if (!(p = strchr(s, ']'))) {
611 fprintf(stderr, "IMAP error: malformed response code\n");
612 return RESP_BAD;
614 *p++ = 0;
615 arg = next_arg(&s);
616 if (!strcmp("UIDVALIDITY", arg)) {
617 if (!(arg = next_arg(&s)) || !(ctx->uidvalidity = atoi(arg))) {
618 fprintf(stderr, "IMAP error: malformed UIDVALIDITY status\n");
619 return RESP_BAD;
621 } else if (!strcmp("UIDNEXT", arg)) {
622 if (!(arg = next_arg(&s)) || !(imap->uidnext = atoi(arg))) {
623 fprintf(stderr, "IMAP error: malformed NEXTUID status\n");
624 return RESP_BAD;
626 } else if (!strcmp("CAPABILITY", arg)) {
627 parse_capability(imap, s);
628 } else if (!strcmp("ALERT", arg)) {
629 /* RFC2060 says that these messages MUST be displayed
630 * to the user
632 for (; isspace((unsigned char)*p); p++);
633 fprintf(stderr, "*** IMAP ALERT *** %s\n", p);
634 } else if (cb && cb->ctx && !strcmp("APPENDUID", arg)) {
635 if (!(arg = next_arg(&s)) || !(ctx->uidvalidity = atoi(arg)) ||
636 !(arg = next_arg(&s)) || !(*(int *)cb->ctx = atoi(arg))) {
637 fprintf(stderr, "IMAP error: malformed APPENDUID status\n");
638 return RESP_BAD;
641 return RESP_OK;
644 static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd)
646 struct imap *imap = ctx->imap;
647 struct imap_cmd *cmdp, **pcmdp, *ncmdp;
648 char *cmd, *arg, *arg1, *p;
649 int n, resp, resp2, tag;
651 for (;;) {
652 if (buffer_gets(&imap->buf, &cmd))
653 return RESP_BAD;
655 arg = next_arg(&cmd);
656 if (*arg == '*') {
657 arg = next_arg(&cmd);
658 if (!arg) {
659 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
660 return RESP_BAD;
663 if (!strcmp("NAMESPACE", arg)) {
664 /* rfc2342 NAMESPACE response. */
665 skip_list(&cmd); /* Personal mailboxes */
666 skip_list(&cmd); /* Others' mailboxes */
667 skip_list(&cmd); /* Shared mailboxes */
668 } else if (!strcmp("OK", arg) || !strcmp("BAD", arg) ||
669 !strcmp("NO", arg) || !strcmp("BYE", arg)) {
670 if ((resp = parse_response_code(ctx, NULL, cmd)) != RESP_OK)
671 return resp;
672 } else if (!strcmp("CAPABILITY", arg)) {
673 parse_capability(imap, cmd);
674 } else if ((arg1 = next_arg(&cmd))) {
675 ; /*
676 * Unhandled response-data with at least two words.
677 * Ignore it.
679 * NEEDSWORK: Previously this case handled '<num> EXISTS'
680 * and '<num> RECENT' but as a probably-unintended side
681 * effect it ignores other unrecognized two-word
682 * responses. imap-send doesn't ever try to read
683 * messages or mailboxes these days, so consider
684 * eliminating this case.
686 } else {
687 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
688 return RESP_BAD;
690 } else if (!imap->in_progress) {
691 fprintf(stderr, "IMAP error: unexpected reply: %s %s\n", arg, cmd ? cmd : "");
692 return RESP_BAD;
693 } else if (*arg == '+') {
694 /* This can happen only with the last command underway, as
695 it enforces a round-trip. */
696 cmdp = (struct imap_cmd *)((char *)imap->in_progress_append -
697 offsetof(struct imap_cmd, next));
698 if (cmdp->cb.data) {
699 n = socket_write(&imap->buf.sock, cmdp->cb.data, cmdp->cb.dlen);
700 free(cmdp->cb.data);
701 cmdp->cb.data = NULL;
702 if (n != (int)cmdp->cb.dlen)
703 return RESP_BAD;
704 } else if (cmdp->cb.cont) {
705 if (cmdp->cb.cont(ctx, cmdp, cmd))
706 return RESP_BAD;
707 } else {
708 fprintf(stderr, "IMAP error: unexpected command continuation request\n");
709 return RESP_BAD;
711 if (socket_write(&imap->buf.sock, "\r\n", 2) != 2)
712 return RESP_BAD;
713 if (!cmdp->cb.cont)
714 imap->literal_pending = 0;
715 if (!tcmd)
716 return DRV_OK;
717 } else {
718 tag = atoi(arg);
719 for (pcmdp = &imap->in_progress; (cmdp = *pcmdp); pcmdp = &cmdp->next)
720 if (cmdp->tag == tag)
721 goto gottag;
722 fprintf(stderr, "IMAP error: unexpected tag %s\n", arg);
723 return RESP_BAD;
724 gottag:
725 if (!(*pcmdp = cmdp->next))
726 imap->in_progress_append = pcmdp;
727 imap->num_in_progress--;
728 if (cmdp->cb.cont || cmdp->cb.data)
729 imap->literal_pending = 0;
730 arg = next_arg(&cmd);
731 if (!strcmp("OK", arg))
732 resp = DRV_OK;
733 else {
734 if (!strcmp("NO", arg)) {
735 if (cmdp->cb.create && cmd && (cmdp->cb.trycreate || !memcmp(cmd, "[TRYCREATE]", 11))) { /* SELECT, APPEND or UID COPY */
736 p = strchr(cmdp->cmd, '"');
737 if (!issue_imap_cmd(ctx, NULL, "CREATE \"%.*s\"", (int)(strchr(p + 1, '"') - p + 1), p)) {
738 resp = RESP_BAD;
739 goto normal;
741 /* not waiting here violates the spec, but a server that does not
742 grok this nonetheless violates it too. */
743 cmdp->cb.create = 0;
744 if (!(ncmdp = issue_imap_cmd(ctx, &cmdp->cb, "%s", cmdp->cmd))) {
745 resp = RESP_BAD;
746 goto normal;
748 free(cmdp->cmd);
749 free(cmdp);
750 if (!tcmd)
751 return 0; /* ignored */
752 if (cmdp == tcmd)
753 tcmd = ncmdp;
754 continue;
756 resp = RESP_NO;
757 } else /*if (!strcmp("BAD", arg))*/
758 resp = RESP_BAD;
759 fprintf(stderr, "IMAP command '%s' returned response (%s) - %s\n",
760 memcmp(cmdp->cmd, "LOGIN", 5) ?
761 cmdp->cmd : "LOGIN <user> <pass>",
762 arg, cmd ? cmd : "");
764 if ((resp2 = parse_response_code(ctx, &cmdp->cb, cmd)) > resp)
765 resp = resp2;
766 normal:
767 if (cmdp->cb.done)
768 cmdp->cb.done(ctx, cmdp, resp);
769 free(cmdp->cb.data);
770 free(cmdp->cmd);
771 free(cmdp);
772 if (!tcmd || tcmd == cmdp)
773 return resp;
776 /* not reached */
779 static void imap_close_server(struct imap_store *ictx)
781 struct imap *imap = ictx->imap;
783 if (imap->buf.sock.fd[0] != -1) {
784 imap_exec(ictx, NULL, "LOGOUT");
785 socket_shutdown(&imap->buf.sock);
787 free(imap);
790 static void imap_close_store(struct imap_store *ctx)
792 imap_close_server(ctx);
793 free(ctx);
796 #ifndef NO_OPENSSL
799 * hexchar() and cram() functions are based on the code from the isync
800 * project (http://isync.sf.net/).
802 static char hexchar(unsigned int b)
804 return b < 10 ? '0' + b : 'a' + (b - 10);
807 #define ENCODED_SIZE(n) (4*((n+2)/3))
808 static char *cram(const char *challenge_64, const char *user, const char *pass)
810 int i, resp_len, encoded_len, decoded_len;
811 HMAC_CTX hmac;
812 unsigned char hash[16];
813 char hex[33];
814 char *response, *response_64, *challenge;
817 * length of challenge_64 (i.e. base-64 encoded string) is a good
818 * enough upper bound for challenge (decoded result).
820 encoded_len = strlen(challenge_64);
821 challenge = xmalloc(encoded_len);
822 decoded_len = EVP_DecodeBlock((unsigned char *)challenge,
823 (unsigned char *)challenge_64, encoded_len);
824 if (decoded_len < 0)
825 die("invalid challenge %s", challenge_64);
826 HMAC_Init(&hmac, (unsigned char *)pass, strlen(pass), EVP_md5());
827 HMAC_Update(&hmac, (unsigned char *)challenge, decoded_len);
828 HMAC_Final(&hmac, hash, NULL);
829 HMAC_CTX_cleanup(&hmac);
831 hex[32] = 0;
832 for (i = 0; i < 16; i++) {
833 hex[2 * i] = hexchar((hash[i] >> 4) & 0xf);
834 hex[2 * i + 1] = hexchar(hash[i] & 0xf);
837 /* response: "<user> <digest in hex>" */
838 resp_len = strlen(user) + 1 + strlen(hex) + 1;
839 response = xmalloc(resp_len);
840 sprintf(response, "%s %s", user, hex);
842 response_64 = xmalloc(ENCODED_SIZE(resp_len) + 1);
843 encoded_len = EVP_EncodeBlock((unsigned char *)response_64,
844 (unsigned char *)response, resp_len);
845 if (encoded_len < 0)
846 die("EVP_EncodeBlock error");
847 response_64[encoded_len] = '\0';
848 return (char *)response_64;
851 #else
853 static char *cram(const char *challenge_64, const char *user, const char *pass)
855 die("If you want to use CRAM-MD5 authenticate method, "
856 "you have to build git-imap-send with OpenSSL library.");
859 #endif
861 static int auth_cram_md5(struct imap_store *ctx, struct imap_cmd *cmd, const char *prompt)
863 int ret;
864 char *response;
866 response = cram(prompt, server.user, server.pass);
868 ret = socket_write(&ctx->imap->buf.sock, response, strlen(response));
869 if (ret != strlen(response))
870 return error("IMAP error: sending response failed");
872 free(response);
874 return 0;
877 static struct imap_store *imap_open_store(struct imap_server_conf *srvc)
879 struct imap_store *ctx;
880 struct imap *imap;
881 char *arg, *rsp;
882 int s = -1, preauth;
884 ctx = xcalloc(sizeof(*ctx), 1);
886 ctx->imap = imap = xcalloc(sizeof(*imap), 1);
887 imap->buf.sock.fd[0] = imap->buf.sock.fd[1] = -1;
888 imap->in_progress_append = &imap->in_progress;
890 /* open connection to IMAP server */
892 if (srvc->tunnel) {
893 const char *argv[] = { srvc->tunnel, NULL };
894 struct child_process tunnel = {NULL};
896 imap_info("Starting tunnel '%s'... ", srvc->tunnel);
898 tunnel.argv = argv;
899 tunnel.use_shell = 1;
900 tunnel.in = -1;
901 tunnel.out = -1;
902 if (start_command(&tunnel))
903 die("cannot start proxy %s", argv[0]);
905 imap->buf.sock.fd[0] = tunnel.out;
906 imap->buf.sock.fd[1] = tunnel.in;
908 imap_info("ok\n");
909 } else {
910 #ifndef NO_IPV6
911 struct addrinfo hints, *ai0, *ai;
912 int gai;
913 char portstr[6];
915 snprintf(portstr, sizeof(portstr), "%d", srvc->port);
917 memset(&hints, 0, sizeof(hints));
918 hints.ai_socktype = SOCK_STREAM;
919 hints.ai_protocol = IPPROTO_TCP;
921 imap_info("Resolving %s... ", srvc->host);
922 gai = getaddrinfo(srvc->host, portstr, &hints, &ai);
923 if (gai) {
924 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai));
925 goto bail;
927 imap_info("ok\n");
929 for (ai0 = ai; ai; ai = ai->ai_next) {
930 char addr[NI_MAXHOST];
932 s = socket(ai->ai_family, ai->ai_socktype,
933 ai->ai_protocol);
934 if (s < 0)
935 continue;
937 getnameinfo(ai->ai_addr, ai->ai_addrlen, addr,
938 sizeof(addr), NULL, 0, NI_NUMERICHOST);
939 imap_info("Connecting to [%s]:%s... ", addr, portstr);
941 if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0) {
942 close(s);
943 s = -1;
944 perror("connect");
945 continue;
948 break;
950 freeaddrinfo(ai0);
951 #else /* NO_IPV6 */
952 struct hostent *he;
953 struct sockaddr_in addr;
955 memset(&addr, 0, sizeof(addr));
956 addr.sin_port = htons(srvc->port);
957 addr.sin_family = AF_INET;
959 imap_info("Resolving %s... ", srvc->host);
960 he = gethostbyname(srvc->host);
961 if (!he) {
962 perror("gethostbyname");
963 goto bail;
965 imap_info("ok\n");
967 addr.sin_addr.s_addr = *((int *) he->h_addr_list[0]);
969 s = socket(PF_INET, SOCK_STREAM, 0);
971 imap_info("Connecting to %s:%hu... ", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
972 if (connect(s, (struct sockaddr *)&addr, sizeof(addr))) {
973 close(s);
974 s = -1;
975 perror("connect");
977 #endif
978 if (s < 0) {
979 fputs("Error: unable to connect to server.\n", stderr);
980 goto bail;
983 imap->buf.sock.fd[0] = s;
984 imap->buf.sock.fd[1] = dup(s);
986 if (srvc->use_ssl &&
987 ssl_socket_connect(&imap->buf.sock, 0, srvc->ssl_verify)) {
988 close(s);
989 goto bail;
991 imap_info("ok\n");
994 /* read the greeting string */
995 if (buffer_gets(&imap->buf, &rsp)) {
996 fprintf(stderr, "IMAP error: no greeting response\n");
997 goto bail;
999 arg = next_arg(&rsp);
1000 if (!arg || *arg != '*' || (arg = next_arg(&rsp)) == NULL) {
1001 fprintf(stderr, "IMAP error: invalid greeting response\n");
1002 goto bail;
1004 preauth = 0;
1005 if (!strcmp("PREAUTH", arg))
1006 preauth = 1;
1007 else if (strcmp("OK", arg) != 0) {
1008 fprintf(stderr, "IMAP error: unknown greeting response\n");
1009 goto bail;
1011 parse_response_code(ctx, NULL, rsp);
1012 if (!imap->caps && imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1013 goto bail;
1015 if (!preauth) {
1016 #ifndef NO_OPENSSL
1017 if (!srvc->use_ssl && CAP(STARTTLS)) {
1018 if (imap_exec(ctx, NULL, "STARTTLS") != RESP_OK)
1019 goto bail;
1020 if (ssl_socket_connect(&imap->buf.sock, 1,
1021 srvc->ssl_verify))
1022 goto bail;
1023 /* capabilities may have changed, so get the new capabilities */
1024 if (imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1025 goto bail;
1027 #endif
1028 imap_info("Logging in...\n");
1029 if (!srvc->user) {
1030 fprintf(stderr, "Skipping server %s, no user\n", srvc->host);
1031 goto bail;
1033 if (!srvc->pass) {
1034 struct strbuf prompt = STRBUF_INIT;
1035 strbuf_addf(&prompt, "Password (%s@%s): ", srvc->user, srvc->host);
1036 arg = git_getpass(prompt.buf);
1037 strbuf_release(&prompt);
1038 if (!*arg) {
1039 fprintf(stderr, "Skipping account %s@%s, no password\n", srvc->user, srvc->host);
1040 goto bail;
1043 * getpass() returns a pointer to a static buffer. make a copy
1044 * for long term storage.
1046 srvc->pass = xstrdup(arg);
1048 if (CAP(NOLOGIN)) {
1049 fprintf(stderr, "Skipping account %s@%s, server forbids LOGIN\n", srvc->user, srvc->host);
1050 goto bail;
1053 if (srvc->auth_method) {
1054 struct imap_cmd_cb cb;
1056 if (!strcmp(srvc->auth_method, "CRAM-MD5")) {
1057 if (!CAP(AUTH_CRAM_MD5)) {
1058 fprintf(stderr, "You specified"
1059 "CRAM-MD5 as authentication method, "
1060 "but %s doesn't support it.\n", srvc->host);
1061 goto bail;
1063 /* CRAM-MD5 */
1065 memset(&cb, 0, sizeof(cb));
1066 cb.cont = auth_cram_md5;
1067 if (imap_exec(ctx, &cb, "AUTHENTICATE CRAM-MD5") != RESP_OK) {
1068 fprintf(stderr, "IMAP error: AUTHENTICATE CRAM-MD5 failed\n");
1069 goto bail;
1071 } else {
1072 fprintf(stderr, "Unknown authentication method:%s\n", srvc->host);
1073 goto bail;
1075 } else {
1076 if (!imap->buf.sock.ssl)
1077 imap_warn("*** IMAP Warning *** Password is being "
1078 "sent in the clear\n");
1079 if (imap_exec(ctx, NULL, "LOGIN \"%s\" \"%s\"", srvc->user, srvc->pass) != RESP_OK) {
1080 fprintf(stderr, "IMAP error: LOGIN failed\n");
1081 goto bail;
1084 } /* !preauth */
1086 ctx->prefix = "";
1087 return ctx;
1089 bail:
1090 imap_close_store(ctx);
1091 return NULL;
1095 * Insert CR characters as necessary in *msg to ensure that every LF
1096 * character in *msg is preceded by a CR.
1098 static void lf_to_crlf(struct strbuf *msg)
1100 char *new;
1101 size_t i, j;
1102 char lastc;
1104 /* First pass: tally, in j, the size of the new string: */
1105 for (i = j = 0, lastc = '\0'; i < msg->len; i++) {
1106 if (msg->buf[i] == '\n' && lastc != '\r')
1107 j++; /* a CR will need to be added here */
1108 lastc = msg->buf[i];
1109 j++;
1112 new = xmalloc(j + 1);
1115 * Second pass: write the new string. Note that this loop is
1116 * otherwise identical to the first pass.
1118 for (i = j = 0, lastc = '\0'; i < msg->len; i++) {
1119 if (msg->buf[i] == '\n' && lastc != '\r')
1120 new[j++] = '\r';
1121 lastc = new[j++] = msg->buf[i];
1123 strbuf_attach(msg, new, j, j + 1);
1127 * Store msg to IMAP. Also detach and free the data from msg->data,
1128 * leaving msg->data empty.
1130 static int imap_store_msg(struct imap_store *ctx, struct strbuf *msg)
1132 struct imap *imap = ctx->imap;
1133 struct imap_cmd_cb cb;
1134 const char *prefix, *box;
1135 int ret;
1137 lf_to_crlf(msg);
1138 memset(&cb, 0, sizeof(cb));
1140 cb.dlen = msg->len;
1141 cb.data = strbuf_detach(msg, NULL);
1143 box = ctx->name;
1144 prefix = !strcmp(box, "INBOX") ? "" : ctx->prefix;
1145 cb.create = 0;
1146 ret = imap_exec_m(ctx, &cb, "APPEND \"%s%s\" ", prefix, box);
1147 imap->caps = imap->rcaps;
1148 if (ret != DRV_OK)
1149 return ret;
1151 return DRV_OK;
1154 static void wrap_in_html(struct strbuf *msg)
1156 struct strbuf buf = STRBUF_INIT;
1157 static char *content_type = "Content-Type: text/html;\n";
1158 static char *pre_open = "<pre>\n";
1159 static char *pre_close = "</pre>\n";
1160 const char *body = strstr(msg->buf, "\n\n");
1162 if (!body)
1163 return; /* Headers but no body; no wrapping needed */
1165 body += 2;
1167 strbuf_add(&buf, msg->buf, body - msg->buf - 1);
1168 strbuf_addstr(&buf, content_type);
1169 strbuf_addch(&buf, '\n');
1170 strbuf_addstr(&buf, pre_open);
1171 strbuf_addstr_xml_quoted(&buf, body);
1172 strbuf_addstr(&buf, pre_close);
1174 strbuf_release(msg);
1175 *msg = buf;
1178 #define CHUNKSIZE 0x1000
1180 static int read_message(FILE *f, struct strbuf *all_msgs)
1182 do {
1183 if (strbuf_fread(all_msgs, CHUNKSIZE, f) <= 0)
1184 break;
1185 } while (!feof(f));
1187 return ferror(f) ? -1 : 0;
1190 static int count_messages(struct strbuf *all_msgs)
1192 int count = 0;
1193 char *p = all_msgs->buf;
1195 while (1) {
1196 if (!prefixcmp(p, "From ")) {
1197 p = strstr(p+5, "\nFrom: ");
1198 if (!p) break;
1199 p = strstr(p+7, "\nDate: ");
1200 if (!p) break;
1201 p = strstr(p+7, "\nSubject: ");
1202 if (!p) break;
1203 p += 10;
1204 count++;
1206 p = strstr(p+5, "\nFrom ");
1207 if (!p)
1208 break;
1209 p++;
1211 return count;
1215 * Copy the next message from all_msgs, starting at offset *ofs, to
1216 * msg. Update *ofs to the start of the following message. Return
1217 * true iff a message was successfully copied.
1219 static int split_msg(struct strbuf *all_msgs, struct strbuf *msg, int *ofs)
1221 char *p, *data;
1222 size_t len;
1224 if (*ofs >= all_msgs->len)
1225 return 0;
1227 data = &all_msgs->buf[*ofs];
1228 len = all_msgs->len - *ofs;
1230 if (len < 5 || prefixcmp(data, "From "))
1231 return 0;
1233 p = strchr(data, '\n');
1234 if (p) {
1235 p++;
1236 len -= p - data;
1237 *ofs += p - data;
1238 data = p;
1241 p = strstr(data, "\nFrom ");
1242 if (p)
1243 len = &p[1] - data;
1245 strbuf_add(msg, data, len);
1246 *ofs += len;
1247 return 1;
1250 static char *imap_folder;
1252 static int git_imap_config(const char *key, const char *val, void *cb)
1254 char imap_key[] = "imap.";
1256 if (strncmp(key, imap_key, sizeof imap_key - 1))
1257 return 0;
1259 key += sizeof imap_key - 1;
1261 /* check booleans first, and barf on others */
1262 if (!strcmp("sslverify", key))
1263 server.ssl_verify = git_config_bool(key, val);
1264 else if (!strcmp("preformattedhtml", key))
1265 server.use_html = git_config_bool(key, val);
1266 else if (!val)
1267 return config_error_nonbool(key);
1269 if (!strcmp("folder", key)) {
1270 imap_folder = xstrdup(val);
1271 } else if (!strcmp("host", key)) {
1272 if (!prefixcmp(val, "imap:"))
1273 val += 5;
1274 else if (!prefixcmp(val, "imaps:")) {
1275 val += 6;
1276 server.use_ssl = 1;
1278 if (!prefixcmp(val, "//"))
1279 val += 2;
1280 server.host = xstrdup(val);
1281 } else if (!strcmp("user", key))
1282 server.user = xstrdup(val);
1283 else if (!strcmp("pass", key))
1284 server.pass = xstrdup(val);
1285 else if (!strcmp("port", key))
1286 server.port = git_config_int(key, val);
1287 else if (!strcmp("tunnel", key))
1288 server.tunnel = xstrdup(val);
1289 else if (!strcmp("authmethod", key))
1290 server.auth_method = xstrdup(val);
1292 return 0;
1295 int main(int argc, char **argv)
1297 struct strbuf all_msgs = STRBUF_INIT;
1298 struct strbuf msg = STRBUF_INIT;
1299 struct imap_store *ctx = NULL;
1300 int ofs = 0;
1301 int r;
1302 int total, n = 0;
1303 int nongit_ok;
1305 git_extract_argv0_path(argv[0]);
1307 git_setup_gettext();
1309 if (argc != 1)
1310 usage(imap_send_usage);
1312 setup_git_directory_gently(&nongit_ok);
1313 git_config(git_imap_config, NULL);
1315 if (!server.port)
1316 server.port = server.use_ssl ? 993 : 143;
1318 if (!imap_folder) {
1319 fprintf(stderr, "no imap store specified\n");
1320 return 1;
1322 if (!server.host) {
1323 if (!server.tunnel) {
1324 fprintf(stderr, "no imap host specified\n");
1325 return 1;
1327 server.host = "tunnel";
1330 /* read the messages */
1331 if (read_message(stdin, &all_msgs)) {
1332 fprintf(stderr, "error reading input\n");
1333 return 1;
1336 if (all_msgs.len == 0) {
1337 fprintf(stderr, "nothing to send\n");
1338 return 1;
1341 total = count_messages(&all_msgs);
1342 if (!total) {
1343 fprintf(stderr, "no messages to send\n");
1344 return 1;
1347 /* write it to the imap server */
1348 ctx = imap_open_store(&server);
1349 if (!ctx) {
1350 fprintf(stderr, "failed to open store\n");
1351 return 1;
1354 fprintf(stderr, "sending %d message%s\n", total, (total != 1) ? "s" : "");
1355 ctx->name = imap_folder;
1356 while (1) {
1357 unsigned percent = n * 100 / total;
1359 fprintf(stderr, "%4u%% (%d/%d) done\r", percent, n, total);
1360 if (!split_msg(&all_msgs, &msg, &ofs))
1361 break;
1362 if (server.use_html)
1363 wrap_in_html(&msg);
1364 r = imap_store_msg(ctx, &msg);
1365 if (r != DRV_OK)
1366 break;
1367 n++;
1369 fprintf(stderr, "\n");
1371 imap_close_store(ctx);
1373 return 0;