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
27 #include "run-command.h"
32 #include <openssl/evp.h>
33 #include <openssl/hmac.h>
37 /* currently open mailbox */
38 const char *name; /* foreign! maybe preset? */
42 static const char imap_send_usage[] = "git imap-send < <mbox>";
46 #define DRV_MSG_BAD -1
47 #define DRV_BOX_BAD -2
48 #define DRV_STORE_BAD -3
50 static int Verbose, Quiet;
52 __attribute__((format (printf, 1, 2)))
53 static void imap_info(const char *, ...);
54 __attribute__((format (printf, 1, 2)))
55 static void imap_warn(const char *, ...);
57 static char *next_arg(char **);
59 __attribute__((format (printf, 3, 4)))
60 static int nfsnprintf(char *buf, int blen, const char *fmt, ...);
62 static int nfvasprintf(char **strp, const char *fmt, va_list ap)
67 len = vsnprintf(tmp, sizeof(tmp), fmt, ap);
69 die("Fatal: Out of memory");
70 if (len >= sizeof(tmp))
71 die("imap command overflow!");
72 *strp = xmemdupz(tmp, len);
76 struct imap_server_conf {
89 static struct imap_server_conf server = {
99 NULL, /* auth_method */
108 struct imap_socket sock;
117 int uidnext; /* from SELECT responses */
118 unsigned caps, rcaps; /* CAPABILITY results */
120 int nexttag, num_in_progress, literal_pending;
121 struct imap_cmd *in_progress, **in_progress_append;
122 struct imap_buffer buf; /* this is BIG, so put it last */
133 int (*cont)(struct imap_store *ctx, struct imap_cmd *cmd, const char *prompt);
134 void (*done)(struct imap_store *ctx, struct imap_cmd *cmd, int response);
139 unsigned create:1, trycreate:1;
143 struct imap_cmd *next;
144 struct imap_cmd_cb cb;
149 #define CAP(cap) (imap->caps & (1 << (cap)))
160 static const char *cap_list[] = {
173 static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd);
177 static void ssl_socket_perror(const char *func)
179 fprintf(stderr, "%s: %s\n", func, ERR_error_string(ERR_get_error(), NULL));
183 static void socket_perror(const char *func, struct imap_socket *sock, int ret)
187 int sslerr = SSL_get_error(sock->ssl, ret);
191 case SSL_ERROR_SYSCALL:
192 perror("SSL_connect");
195 ssl_socket_perror("SSL_connect");
204 fprintf(stderr, "%s: unexpected EOF\n", func);
208 static int ssl_socket_connect(struct imap_socket *sock, int use_tls_only, int verify)
211 fprintf(stderr, "SSL requested but SSL support not compiled in\n");
214 #if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
215 const SSL_METHOD *meth;
223 SSL_load_error_strings();
226 meth = TLSv1_method();
228 meth = SSLv23_method();
231 ssl_socket_perror("SSLv23_method");
235 ctx = SSL_CTX_new(meth);
238 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
240 if (!SSL_CTX_set_default_verify_paths(ctx)) {
241 ssl_socket_perror("SSL_CTX_set_default_verify_paths");
244 sock->ssl = SSL_new(ctx);
246 ssl_socket_perror("SSL_new");
249 if (!SSL_set_rfd(sock->ssl, sock->fd[0])) {
250 ssl_socket_perror("SSL_set_rfd");
253 if (!SSL_set_wfd(sock->ssl, sock->fd[1])) {
254 ssl_socket_perror("SSL_set_wfd");
258 ret = SSL_connect(sock->ssl);
260 socket_perror("SSL_connect", sock, ret);
268 static int socket_read(struct imap_socket *sock, char *buf, int len)
273 n = SSL_read(sock->ssl, buf, len);
276 n = xread(sock->fd[0], buf, len);
278 socket_perror("read", sock, n);
281 sock->fd[0] = sock->fd[1] = -1;
286 static int socket_write(struct imap_socket *sock, const char *buf, int len)
291 n = SSL_write(sock->ssl, buf, len);
294 n = write_in_full(sock->fd[1], buf, len);
296 socket_perror("write", sock, n);
299 sock->fd[0] = sock->fd[1] = -1;
304 static void socket_shutdown(struct imap_socket *sock)
308 SSL_shutdown(sock->ssl);
316 /* simple line buffering */
317 static int buffer_gets(struct imap_buffer *b, char **s)
320 int start = b->offset;
325 /* make sure we have enough data to read the \r\n sequence */
326 if (b->offset + 1 >= b->bytes) {
328 /* shift down used bytes */
331 assert(start <= b->bytes);
332 n = b->bytes - start;
335 memmove(b->buf, b->buf + start, n);
341 n = socket_read(&b->sock, b->buf + b->bytes,
342 sizeof(b->buf) - b->bytes);
350 if (b->buf[b->offset] == '\r') {
351 assert(b->offset + 1 < b->bytes);
352 if (b->buf[b->offset + 1] == '\n') {
353 b->buf[b->offset] = 0; /* terminate the string */
354 b->offset += 2; /* next line */
366 static void imap_info(const char *msg, ...)
378 static void imap_warn(const char *msg, ...)
384 vfprintf(stderr, msg, va);
389 static char *next_arg(char **s)
395 while (isspace((unsigned char) **s))
404 *s = strchr(*s, '"');
407 while (**s && !isspace((unsigned char) **s))
419 static int nfsnprintf(char *buf, int blen, const char *fmt, ...)
425 if (blen <= 0 || (unsigned)(ret = vsnprintf(buf, blen, fmt, va)) >= (unsigned)blen)
426 die("Fatal: buffer too small. Please report a bug.");
431 static struct imap_cmd *v_issue_imap_cmd(struct imap_store *ctx,
432 struct imap_cmd_cb *cb,
433 const char *fmt, va_list ap)
435 struct imap *imap = ctx->imap;
436 struct imap_cmd *cmd;
440 cmd = xmalloc(sizeof(struct imap_cmd));
441 nfvasprintf(&cmd->cmd, fmt, ap);
442 cmd->tag = ++imap->nexttag;
447 memset(&cmd->cb, 0, sizeof(cmd->cb));
449 while (imap->literal_pending)
450 get_cmd_result(ctx, NULL);
453 bufl = nfsnprintf(buf, sizeof(buf), "%d %s\r\n", cmd->tag, cmd->cmd);
455 bufl = nfsnprintf(buf, sizeof(buf), "%d %s{%d%s}\r\n",
456 cmd->tag, cmd->cmd, cmd->cb.dlen,
457 CAP(LITERALPLUS) ? "+" : "");
460 if (imap->num_in_progress)
461 printf("(%d in progress) ", imap->num_in_progress);
462 if (memcmp(cmd->cmd, "LOGIN", 5))
463 printf(">>> %s", buf);
465 printf(">>> %d LOGIN <user> <pass>\n", cmd->tag);
467 if (socket_write(&imap->buf.sock, buf, bufl) != bufl) {
475 if (CAP(LITERALPLUS)) {
476 n = socket_write(&imap->buf.sock, cmd->cb.data, cmd->cb.dlen);
478 if (n != cmd->cb.dlen ||
479 socket_write(&imap->buf.sock, "\r\n", 2) != 2) {
486 imap->literal_pending = 1;
487 } else if (cmd->cb.cont)
488 imap->literal_pending = 1;
490 *imap->in_progress_append = cmd;
491 imap->in_progress_append = &cmd->next;
492 imap->num_in_progress++;
496 __attribute__((format (printf, 3, 4)))
497 static struct imap_cmd *issue_imap_cmd(struct imap_store *ctx,
498 struct imap_cmd_cb *cb,
499 const char *fmt, ...)
501 struct imap_cmd *ret;
505 ret = v_issue_imap_cmd(ctx, cb, fmt, ap);
510 __attribute__((format (printf, 3, 4)))
511 static int imap_exec(struct imap_store *ctx, struct imap_cmd_cb *cb,
512 const char *fmt, ...)
515 struct imap_cmd *cmdp;
518 cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
523 return get_cmd_result(ctx, cmdp);
526 __attribute__((format (printf, 3, 4)))
527 static int imap_exec_m(struct imap_store *ctx, struct imap_cmd_cb *cb,
528 const char *fmt, ...)
531 struct imap_cmd *cmdp;
534 cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
537 return DRV_STORE_BAD;
539 switch (get_cmd_result(ctx, cmdp)) {
540 case RESP_BAD: return DRV_STORE_BAD;
541 case RESP_NO: return DRV_MSG_BAD;
542 default: return DRV_OK;
546 static int skip_imap_list_l(char **sp, int level)
551 while (isspace((unsigned char)*s))
553 if (level && *s == ')') {
560 if (skip_imap_list_l(&s, level + 1))
562 } else if (*s == '"') {
565 for (; *s != '"'; s++)
571 for (; *s && !isspace((unsigned char)*s); s++)
572 if (level && *s == ')')
588 static void skip_list(char **sp)
590 skip_imap_list_l(sp, 0);
593 static void parse_capability(struct imap *imap, char *cmd)
598 imap->caps = 0x80000000;
599 while ((arg = next_arg(&cmd)))
600 for (i = 0; i < ARRAY_SIZE(cap_list); i++)
601 if (!strcmp(cap_list[i], arg))
602 imap->caps |= 1 << i;
603 imap->rcaps = imap->caps;
606 static int parse_response_code(struct imap_store *ctx, struct imap_cmd_cb *cb,
609 struct imap *imap = ctx->imap;
613 return RESP_OK; /* no response code */
615 if (!(p = strchr(s, ']'))) {
616 fprintf(stderr, "IMAP error: malformed response code\n");
621 if (!strcmp("UIDVALIDITY", arg)) {
622 if (!(arg = next_arg(&s)) || !(ctx->gen.uidvalidity = atoi(arg))) {
623 fprintf(stderr, "IMAP error: malformed UIDVALIDITY status\n");
626 } else if (!strcmp("UIDNEXT", arg)) {
627 if (!(arg = next_arg(&s)) || !(imap->uidnext = atoi(arg))) {
628 fprintf(stderr, "IMAP error: malformed NEXTUID status\n");
631 } else if (!strcmp("CAPABILITY", arg)) {
632 parse_capability(imap, s);
633 } else if (!strcmp("ALERT", arg)) {
634 /* RFC2060 says that these messages MUST be displayed
637 for (; isspace((unsigned char)*p); p++);
638 fprintf(stderr, "*** IMAP ALERT *** %s\n", p);
639 } else if (cb && cb->ctx && !strcmp("APPENDUID", arg)) {
640 if (!(arg = next_arg(&s)) || !(ctx->gen.uidvalidity = atoi(arg)) ||
641 !(arg = next_arg(&s)) || !(*(int *)cb->ctx = atoi(arg))) {
642 fprintf(stderr, "IMAP error: malformed APPENDUID status\n");
649 static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd)
651 struct imap *imap = ctx->imap;
652 struct imap_cmd *cmdp, **pcmdp, *ncmdp;
653 char *cmd, *arg, *arg1, *p;
654 int n, resp, resp2, tag;
657 if (buffer_gets(&imap->buf, &cmd))
660 arg = next_arg(&cmd);
662 arg = next_arg(&cmd);
664 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
668 if (!strcmp("NAMESPACE", arg)) {
669 /* rfc2342 NAMESPACE response. */
670 skip_list(&cmd); /* Personal mailboxes */
671 skip_list(&cmd); /* Others' mailboxes */
672 skip_list(&cmd); /* Shared mailboxes */
673 } else if (!strcmp("OK", arg) || !strcmp("BAD", arg) ||
674 !strcmp("NO", arg) || !strcmp("BYE", arg)) {
675 if ((resp = parse_response_code(ctx, NULL, cmd)) != RESP_OK)
677 } else if (!strcmp("CAPABILITY", arg)) {
678 parse_capability(imap, cmd);
679 } else if ((arg1 = next_arg(&cmd))) {
681 * Unhandled response-data with at least two words.
684 * NEEDSWORK: Previously this case handled '<num> EXISTS'
685 * and '<num> RECENT' but as a probably-unintended side
686 * effect it ignores other unrecognized two-word
687 * responses. imap-send doesn't ever try to read
688 * messages or mailboxes these days, so consider
689 * eliminating this case.
692 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
695 } else if (!imap->in_progress) {
696 fprintf(stderr, "IMAP error: unexpected reply: %s %s\n", arg, cmd ? cmd : "");
698 } else if (*arg == '+') {
699 /* This can happen only with the last command underway, as
700 it enforces a round-trip. */
701 cmdp = (struct imap_cmd *)((char *)imap->in_progress_append -
702 offsetof(struct imap_cmd, next));
704 n = socket_write(&imap->buf.sock, cmdp->cb.data, cmdp->cb.dlen);
706 cmdp->cb.data = NULL;
707 if (n != (int)cmdp->cb.dlen)
709 } else if (cmdp->cb.cont) {
710 if (cmdp->cb.cont(ctx, cmdp, cmd))
713 fprintf(stderr, "IMAP error: unexpected command continuation request\n");
716 if (socket_write(&imap->buf.sock, "\r\n", 2) != 2)
719 imap->literal_pending = 0;
724 for (pcmdp = &imap->in_progress; (cmdp = *pcmdp); pcmdp = &cmdp->next)
725 if (cmdp->tag == tag)
727 fprintf(stderr, "IMAP error: unexpected tag %s\n", arg);
730 if (!(*pcmdp = cmdp->next))
731 imap->in_progress_append = pcmdp;
732 imap->num_in_progress--;
733 if (cmdp->cb.cont || cmdp->cb.data)
734 imap->literal_pending = 0;
735 arg = next_arg(&cmd);
736 if (!strcmp("OK", arg))
739 if (!strcmp("NO", arg)) {
740 if (cmdp->cb.create && cmd && (cmdp->cb.trycreate || !memcmp(cmd, "[TRYCREATE]", 11))) { /* SELECT, APPEND or UID COPY */
741 p = strchr(cmdp->cmd, '"');
742 if (!issue_imap_cmd(ctx, NULL, "CREATE \"%.*s\"", (int)(strchr(p + 1, '"') - p + 1), p)) {
746 /* not waiting here violates the spec, but a server that does not
747 grok this nonetheless violates it too. */
749 if (!(ncmdp = issue_imap_cmd(ctx, &cmdp->cb, "%s", cmdp->cmd))) {
756 return 0; /* ignored */
762 } else /*if (!strcmp("BAD", arg))*/
764 fprintf(stderr, "IMAP command '%s' returned response (%s) - %s\n",
765 memcmp(cmdp->cmd, "LOGIN", 5) ?
766 cmdp->cmd : "LOGIN <user> <pass>",
767 arg, cmd ? cmd : "");
769 if ((resp2 = parse_response_code(ctx, &cmdp->cb, cmd)) > resp)
773 cmdp->cb.done(ctx, cmdp, resp);
777 if (!tcmd || tcmd == cmdp)
784 static void imap_close_server(struct imap_store *ictx)
786 struct imap *imap = ictx->imap;
788 if (imap->buf.sock.fd[0] != -1) {
789 imap_exec(ictx, NULL, "LOGOUT");
790 socket_shutdown(&imap->buf.sock);
795 static void imap_close_store(struct imap_store *ctx)
797 imap_close_server(ctx);
804 * hexchar() and cram() functions are based on the code from the isync
805 * project (http://isync.sf.net/).
807 static char hexchar(unsigned int b)
809 return b < 10 ? '0' + b : 'a' + (b - 10);
812 #define ENCODED_SIZE(n) (4*((n+2)/3))
813 static char *cram(const char *challenge_64, const char *user, const char *pass)
815 int i, resp_len, encoded_len, decoded_len;
817 unsigned char hash[16];
819 char *response, *response_64, *challenge;
822 * length of challenge_64 (i.e. base-64 encoded string) is a good
823 * enough upper bound for challenge (decoded result).
825 encoded_len = strlen(challenge_64);
826 challenge = xmalloc(encoded_len);
827 decoded_len = EVP_DecodeBlock((unsigned char *)challenge,
828 (unsigned char *)challenge_64, encoded_len);
830 die("invalid challenge %s", challenge_64);
831 HMAC_Init(&hmac, (unsigned char *)pass, strlen(pass), EVP_md5());
832 HMAC_Update(&hmac, (unsigned char *)challenge, decoded_len);
833 HMAC_Final(&hmac, hash, NULL);
834 HMAC_CTX_cleanup(&hmac);
837 for (i = 0; i < 16; i++) {
838 hex[2 * i] = hexchar((hash[i] >> 4) & 0xf);
839 hex[2 * i + 1] = hexchar(hash[i] & 0xf);
842 /* response: "<user> <digest in hex>" */
843 resp_len = strlen(user) + 1 + strlen(hex) + 1;
844 response = xmalloc(resp_len);
845 sprintf(response, "%s %s", user, hex);
847 response_64 = xmalloc(ENCODED_SIZE(resp_len) + 1);
848 encoded_len = EVP_EncodeBlock((unsigned char *)response_64,
849 (unsigned char *)response, resp_len);
851 die("EVP_EncodeBlock error");
852 response_64[encoded_len] = '\0';
853 return (char *)response_64;
858 static char *cram(const char *challenge_64, const char *user, const char *pass)
860 die("If you want to use CRAM-MD5 authenticate method, "
861 "you have to build git-imap-send with OpenSSL library.");
866 static int auth_cram_md5(struct imap_store *ctx, struct imap_cmd *cmd, const char *prompt)
871 response = cram(prompt, server.user, server.pass);
873 ret = socket_write(&ctx->imap->buf.sock, response, strlen(response));
874 if (ret != strlen(response))
875 return error("IMAP error: sending response failed");
882 static struct imap_store *imap_open_store(struct imap_server_conf *srvc)
884 struct imap_store *ctx;
889 ctx = xcalloc(sizeof(*ctx), 1);
891 ctx->imap = imap = xcalloc(sizeof(*imap), 1);
892 imap->buf.sock.fd[0] = imap->buf.sock.fd[1] = -1;
893 imap->in_progress_append = &imap->in_progress;
895 /* open connection to IMAP server */
898 const char *argv[] = { srvc->tunnel, NULL };
899 struct child_process tunnel = {NULL};
901 imap_info("Starting tunnel '%s'... ", srvc->tunnel);
904 tunnel.use_shell = 1;
907 if (start_command(&tunnel))
908 die("cannot start proxy %s", argv[0]);
910 imap->buf.sock.fd[0] = tunnel.out;
911 imap->buf.sock.fd[1] = tunnel.in;
916 struct addrinfo hints, *ai0, *ai;
920 snprintf(portstr, sizeof(portstr), "%d", srvc->port);
922 memset(&hints, 0, sizeof(hints));
923 hints.ai_socktype = SOCK_STREAM;
924 hints.ai_protocol = IPPROTO_TCP;
926 imap_info("Resolving %s... ", srvc->host);
927 gai = getaddrinfo(srvc->host, portstr, &hints, &ai);
929 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai));
934 for (ai0 = ai; ai; ai = ai->ai_next) {
935 char addr[NI_MAXHOST];
937 s = socket(ai->ai_family, ai->ai_socktype,
942 getnameinfo(ai->ai_addr, ai->ai_addrlen, addr,
943 sizeof(addr), NULL, 0, NI_NUMERICHOST);
944 imap_info("Connecting to [%s]:%s... ", addr, portstr);
946 if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0) {
958 struct sockaddr_in addr;
960 memset(&addr, 0, sizeof(addr));
961 addr.sin_port = htons(srvc->port);
962 addr.sin_family = AF_INET;
964 imap_info("Resolving %s... ", srvc->host);
965 he = gethostbyname(srvc->host);
967 perror("gethostbyname");
972 addr.sin_addr.s_addr = *((int *) he->h_addr_list[0]);
974 s = socket(PF_INET, SOCK_STREAM, 0);
976 imap_info("Connecting to %s:%hu... ", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
977 if (connect(s, (struct sockaddr *)&addr, sizeof(addr))) {
984 fputs("Error: unable to connect to server.\n", stderr);
988 imap->buf.sock.fd[0] = s;
989 imap->buf.sock.fd[1] = dup(s);
992 ssl_socket_connect(&imap->buf.sock, 0, srvc->ssl_verify)) {
999 /* read the greeting string */
1000 if (buffer_gets(&imap->buf, &rsp)) {
1001 fprintf(stderr, "IMAP error: no greeting response\n");
1004 arg = next_arg(&rsp);
1005 if (!arg || *arg != '*' || (arg = next_arg(&rsp)) == NULL) {
1006 fprintf(stderr, "IMAP error: invalid greeting response\n");
1010 if (!strcmp("PREAUTH", arg))
1012 else if (strcmp("OK", arg) != 0) {
1013 fprintf(stderr, "IMAP error: unknown greeting response\n");
1016 parse_response_code(ctx, NULL, rsp);
1017 if (!imap->caps && imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1022 if (!srvc->use_ssl && CAP(STARTTLS)) {
1023 if (imap_exec(ctx, NULL, "STARTTLS") != RESP_OK)
1025 if (ssl_socket_connect(&imap->buf.sock, 1,
1028 /* capabilities may have changed, so get the new capabilities */
1029 if (imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1033 imap_info("Logging in...\n");
1035 fprintf(stderr, "Skipping server %s, no user\n", srvc->host);
1039 struct strbuf prompt = STRBUF_INIT;
1040 strbuf_addf(&prompt, "Password (%s@%s): ", srvc->user, srvc->host);
1041 arg = git_getpass(prompt.buf);
1042 strbuf_release(&prompt);
1044 fprintf(stderr, "Skipping account %s@%s, no password\n", srvc->user, srvc->host);
1048 * getpass() returns a pointer to a static buffer. make a copy
1049 * for long term storage.
1051 srvc->pass = xstrdup(arg);
1054 fprintf(stderr, "Skipping account %s@%s, server forbids LOGIN\n", srvc->user, srvc->host);
1058 if (srvc->auth_method) {
1059 struct imap_cmd_cb cb;
1061 if (!strcmp(srvc->auth_method, "CRAM-MD5")) {
1062 if (!CAP(AUTH_CRAM_MD5)) {
1063 fprintf(stderr, "You specified"
1064 "CRAM-MD5 as authentication method, "
1065 "but %s doesn't support it.\n", srvc->host);
1070 memset(&cb, 0, sizeof(cb));
1071 cb.cont = auth_cram_md5;
1072 if (imap_exec(ctx, &cb, "AUTHENTICATE CRAM-MD5") != RESP_OK) {
1073 fprintf(stderr, "IMAP error: AUTHENTICATE CRAM-MD5 failed\n");
1077 fprintf(stderr, "Unknown authentication method:%s\n", srvc->host);
1081 if (!imap->buf.sock.ssl)
1082 imap_warn("*** IMAP Warning *** Password is being "
1083 "sent in the clear\n");
1084 if (imap_exec(ctx, NULL, "LOGIN \"%s\" \"%s\"", srvc->user, srvc->pass) != RESP_OK) {
1085 fprintf(stderr, "IMAP error: LOGIN failed\n");
1095 imap_close_store(ctx);
1099 static void lf_to_crlf(struct strbuf *msg)
1103 int i, j, lfnum = 0;
1105 if (msg->buf[0] == '\n')
1107 for (i = 1; i < msg->len; i++) {
1108 if (msg->buf[i - 1] != '\r' && msg->buf[i] == '\n')
1112 new_len = msg->len + lfnum;
1113 new = xmalloc(new_len + 1);
1114 if (msg->buf[0] == '\n') {
1120 new[0] = msg->buf[0];
1124 for ( ; i < msg->len; i++) {
1125 if (msg->buf[i] != '\n') {
1126 new[j++] = msg->buf[i];
1129 if (msg->buf[i - 1] != '\r')
1131 /* otherwise it already had CR before */
1134 strbuf_attach(msg, new, new_len, new_len + 1);
1138 * Store msg to IMAP. Also detach and free the data from msg->data,
1139 * leaving msg->data empty.
1141 static int imap_store_msg(struct imap_store *ctx, struct strbuf *msg)
1143 struct imap *imap = ctx->imap;
1144 struct imap_cmd_cb cb;
1145 const char *prefix, *box;
1149 memset(&cb, 0, sizeof(cb));
1152 cb.data = strbuf_detach(msg, NULL);
1154 box = ctx->gen.name;
1155 prefix = !strcmp(box, "INBOX") ? "" : ctx->prefix;
1157 ret = imap_exec_m(ctx, &cb, "APPEND \"%s%s\" ", prefix, box);
1158 imap->caps = imap->rcaps;
1165 static void wrap_in_html(struct strbuf *msg)
1167 struct strbuf buf = STRBUF_INIT;
1168 static char *content_type = "Content-Type: text/html;\n";
1169 static char *pre_open = "<pre>\n";
1170 static char *pre_close = "</pre>\n";
1171 const char *body = strstr(msg->buf, "\n\n");
1174 return; /* Headers but no body; no wrapping needed */
1178 strbuf_add(&buf, msg->buf, body - msg->buf - 1);
1179 strbuf_addstr(&buf, content_type);
1180 strbuf_addch(&buf, '\n');
1181 strbuf_addstr(&buf, pre_open);
1182 strbuf_addstr_xml_quoted(&buf, body);
1183 strbuf_addstr(&buf, pre_close);
1185 strbuf_release(msg);
1189 #define CHUNKSIZE 0x1000
1191 static int read_message(FILE *f, struct strbuf *all_msgs)
1194 if (strbuf_fread(all_msgs, CHUNKSIZE, f) <= 0)
1198 return ferror(f) ? -1 : 0;
1201 static int count_messages(struct strbuf *all_msgs)
1204 char *p = all_msgs->buf;
1207 if (!prefixcmp(p, "From ")) {
1208 p = strstr(p+5, "\nFrom: ");
1210 p = strstr(p+7, "\nDate: ");
1212 p = strstr(p+7, "\nSubject: ");
1217 p = strstr(p+5, "\nFrom ");
1226 * Copy the next message from all_msgs, starting at offset *ofs, to
1227 * msg. Update *ofs to the start of the following message. Return
1228 * true iff a message was successfully copied.
1230 static int split_msg(struct strbuf *all_msgs, struct strbuf *msg, int *ofs)
1235 if (*ofs >= all_msgs->len)
1238 data = &all_msgs->buf[*ofs];
1239 len = all_msgs->len - *ofs;
1241 if (len < 5 || prefixcmp(data, "From "))
1244 p = strchr(data, '\n');
1252 p = strstr(data, "\nFrom ");
1256 strbuf_add(msg, data, len);
1261 static char *imap_folder;
1263 static int git_imap_config(const char *key, const char *val, void *cb)
1265 char imap_key[] = "imap.";
1267 if (strncmp(key, imap_key, sizeof imap_key - 1))
1270 key += sizeof imap_key - 1;
1272 /* check booleans first, and barf on others */
1273 if (!strcmp("sslverify", key))
1274 server.ssl_verify = git_config_bool(key, val);
1275 else if (!strcmp("preformattedhtml", key))
1276 server.use_html = git_config_bool(key, val);
1278 return config_error_nonbool(key);
1280 if (!strcmp("folder", key)) {
1281 imap_folder = xstrdup(val);
1282 } else if (!strcmp("host", key)) {
1283 if (!prefixcmp(val, "imap:"))
1285 else if (!prefixcmp(val, "imaps:")) {
1289 if (!prefixcmp(val, "//"))
1291 server.host = xstrdup(val);
1292 } else if (!strcmp("user", key))
1293 server.user = xstrdup(val);
1294 else if (!strcmp("pass", key))
1295 server.pass = xstrdup(val);
1296 else if (!strcmp("port", key))
1297 server.port = git_config_int(key, val);
1298 else if (!strcmp("tunnel", key))
1299 server.tunnel = xstrdup(val);
1300 else if (!strcmp("authmethod", key))
1301 server.auth_method = xstrdup(val);
1306 int main(int argc, char **argv)
1308 struct strbuf all_msgs = STRBUF_INIT;
1309 struct strbuf msg = STRBUF_INIT;
1310 struct imap_store *ctx = NULL;
1316 git_extract_argv0_path(argv[0]);
1318 git_setup_gettext();
1321 usage(imap_send_usage);
1323 setup_git_directory_gently(&nongit_ok);
1324 git_config(git_imap_config, NULL);
1327 server.port = server.use_ssl ? 993 : 143;
1330 fprintf(stderr, "no imap store specified\n");
1334 if (!server.tunnel) {
1335 fprintf(stderr, "no imap host specified\n");
1338 server.host = "tunnel";
1341 /* read the messages */
1342 if (read_message(stdin, &all_msgs)) {
1343 fprintf(stderr, "error reading input\n");
1347 if (all_msgs.len == 0) {
1348 fprintf(stderr, "nothing to send\n");
1352 total = count_messages(&all_msgs);
1354 fprintf(stderr, "no messages to send\n");
1358 /* write it to the imap server */
1359 ctx = imap_open_store(&server);
1361 fprintf(stderr, "failed to open store\n");
1365 fprintf(stderr, "sending %d message%s\n", total, (total != 1) ? "s" : "");
1366 ctx->gen.name = imap_folder;
1368 unsigned percent = n * 100 / total;
1370 fprintf(stderr, "%4u%% (%d/%d) done\r", percent, n, total);
1371 if (!split_msg(&all_msgs, &msg, &ofs))
1373 if (server.use_html)
1375 r = imap_store_msg(ctx, &msg);
1380 fprintf(stderr, "\n");
1382 imap_close_store(ctx);