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>
36 static const char imap_send_usage[] = "git imap-send < <mbox>";
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)
61 len = vsnprintf(tmp, sizeof(tmp), fmt, ap);
63 die("Fatal: Out of memory");
64 if (len >= sizeof(tmp))
65 die("imap command overflow!");
66 *strp = xmemdupz(tmp, len);
70 struct imap_server_conf {
83 static struct imap_server_conf server = {
93 NULL, /* auth_method */
102 struct imap_socket sock;
111 int uidnext; /* from SELECT responses */
112 unsigned caps, rcaps; /* CAPABILITY results */
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 */
120 /* currently open mailbox */
121 const char *name; /* foreign! maybe preset? */
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);
134 unsigned create:1, trycreate:1;
138 struct imap_cmd *next;
139 struct imap_cmd_cb cb;
144 #define CAP(cap) (imap->caps & (1 << (cap)))
155 static const char *cap_list[] = {
168 static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd);
172 static void ssl_socket_perror(const char *func)
174 fprintf(stderr, "%s: %s\n", func, ERR_error_string(ERR_get_error(), NULL));
178 static void socket_perror(const char *func, struct imap_socket *sock, int ret)
182 int sslerr = SSL_get_error(sock->ssl, ret);
186 case SSL_ERROR_SYSCALL:
187 perror("SSL_connect");
190 ssl_socket_perror("SSL_connect");
199 fprintf(stderr, "%s: unexpected EOF\n", func);
203 static int ssl_socket_connect(struct imap_socket *sock, int use_tls_only, int verify)
206 fprintf(stderr, "SSL requested but SSL support not compiled in\n");
209 #if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
210 const SSL_METHOD *meth;
218 SSL_load_error_strings();
221 meth = TLSv1_method();
223 meth = SSLv23_method();
226 ssl_socket_perror("SSLv23_method");
230 ctx = SSL_CTX_new(meth);
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");
239 sock->ssl = SSL_new(ctx);
241 ssl_socket_perror("SSL_new");
244 if (!SSL_set_rfd(sock->ssl, sock->fd[0])) {
245 ssl_socket_perror("SSL_set_rfd");
248 if (!SSL_set_wfd(sock->ssl, sock->fd[1])) {
249 ssl_socket_perror("SSL_set_wfd");
253 ret = SSL_connect(sock->ssl);
255 socket_perror("SSL_connect", sock, ret);
263 static int socket_read(struct imap_socket *sock, char *buf, int len)
268 n = SSL_read(sock->ssl, buf, len);
271 n = xread(sock->fd[0], buf, len);
273 socket_perror("read", sock, n);
276 sock->fd[0] = sock->fd[1] = -1;
281 static int socket_write(struct imap_socket *sock, const char *buf, int len)
286 n = SSL_write(sock->ssl, buf, len);
289 n = write_in_full(sock->fd[1], buf, len);
291 socket_perror("write", sock, n);
294 sock->fd[0] = sock->fd[1] = -1;
299 static void socket_shutdown(struct imap_socket *sock)
303 SSL_shutdown(sock->ssl);
311 /* simple line buffering */
312 static int buffer_gets(struct imap_buffer *b, char **s)
315 int start = b->offset;
320 /* make sure we have enough data to read the \r\n sequence */
321 if (b->offset + 1 >= b->bytes) {
323 /* shift down used bytes */
326 assert(start <= b->bytes);
327 n = b->bytes - start;
330 memmove(b->buf, b->buf + start, n);
336 n = socket_read(&b->sock, b->buf + b->bytes,
337 sizeof(b->buf) - b->bytes);
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 */
361 static void imap_info(const char *msg, ...)
373 static void imap_warn(const char *msg, ...)
379 vfprintf(stderr, msg, va);
384 static char *next_arg(char **s)
390 while (isspace((unsigned char) **s))
399 *s = strchr(*s, '"');
402 while (**s && !isspace((unsigned char) **s))
414 static int nfsnprintf(char *buf, int blen, const char *fmt, ...)
420 if (blen <= 0 || (unsigned)(ret = vsnprintf(buf, blen, fmt, va)) >= (unsigned)blen)
421 die("Fatal: buffer too small. Please report a bug.");
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;
435 cmd = xmalloc(sizeof(struct imap_cmd));
436 nfvasprintf(&cmd->cmd, fmt, ap);
437 cmd->tag = ++imap->nexttag;
442 memset(&cmd->cb, 0, sizeof(cmd->cb));
444 while (imap->literal_pending)
445 get_cmd_result(ctx, NULL);
448 bufl = nfsnprintf(buf, sizeof(buf), "%d %s\r\n", cmd->tag, cmd->cmd);
450 bufl = nfsnprintf(buf, sizeof(buf), "%d %s{%d%s}\r\n",
451 cmd->tag, cmd->cmd, cmd->cb.dlen,
452 CAP(LITERALPLUS) ? "+" : "");
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);
460 printf(">>> %d LOGIN <user> <pass>\n", cmd->tag);
462 if (socket_write(&imap->buf.sock, buf, bufl) != bufl) {
470 if (CAP(LITERALPLUS)) {
471 n = socket_write(&imap->buf.sock, cmd->cb.data, cmd->cb.dlen);
473 if (n != cmd->cb.dlen ||
474 socket_write(&imap->buf.sock, "\r\n", 2) != 2) {
481 imap->literal_pending = 1;
482 } else if (cmd->cb.cont)
483 imap->literal_pending = 1;
485 *imap->in_progress_append = cmd;
486 imap->in_progress_append = &cmd->next;
487 imap->num_in_progress++;
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;
500 ret = v_issue_imap_cmd(ctx, cb, fmt, ap);
505 __attribute__((format (printf, 3, 4)))
506 static int imap_exec(struct imap_store *ctx, struct imap_cmd_cb *cb,
507 const char *fmt, ...)
510 struct imap_cmd *cmdp;
513 cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
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, ...)
526 struct imap_cmd *cmdp;
529 cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
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)
546 while (isspace((unsigned char)*s))
548 if (level && *s == ')') {
555 if (skip_imap_list_l(&s, level + 1))
557 } else if (*s == '"') {
560 for (; *s != '"'; s++)
566 for (; *s && !isspace((unsigned char)*s); s++)
567 if (level && *s == ')')
583 static void skip_list(char **sp)
585 skip_imap_list_l(sp, 0);
588 static void parse_capability(struct imap *imap, char *cmd)
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,
604 struct imap *imap = ctx->imap;
608 return RESP_OK; /* no response code */
610 if (!(p = strchr(s, ']'))) {
611 fprintf(stderr, "IMAP error: malformed response code\n");
616 if (!strcmp("UIDVALIDITY", arg)) {
617 if (!(arg = next_arg(&s)) || !(ctx->uidvalidity = atoi(arg))) {
618 fprintf(stderr, "IMAP error: malformed UIDVALIDITY status\n");
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");
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
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");
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;
652 if (buffer_gets(&imap->buf, &cmd))
655 arg = next_arg(&cmd);
657 arg = next_arg(&cmd);
659 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
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)
672 } else if (!strcmp("CAPABILITY", arg)) {
673 parse_capability(imap, cmd);
674 } else if ((arg1 = next_arg(&cmd))) {
676 * Unhandled response-data with at least two words.
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.
687 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
690 } else if (!imap->in_progress) {
691 fprintf(stderr, "IMAP error: unexpected reply: %s %s\n", arg, cmd ? cmd : "");
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));
699 n = socket_write(&imap->buf.sock, cmdp->cb.data, cmdp->cb.dlen);
701 cmdp->cb.data = NULL;
702 if (n != (int)cmdp->cb.dlen)
704 } else if (cmdp->cb.cont) {
705 if (cmdp->cb.cont(ctx, cmdp, cmd))
708 fprintf(stderr, "IMAP error: unexpected command continuation request\n");
711 if (socket_write(&imap->buf.sock, "\r\n", 2) != 2)
714 imap->literal_pending = 0;
719 for (pcmdp = &imap->in_progress; (cmdp = *pcmdp); pcmdp = &cmdp->next)
720 if (cmdp->tag == tag)
722 fprintf(stderr, "IMAP error: unexpected tag %s\n", arg);
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))
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)) {
741 /* not waiting here violates the spec, but a server that does not
742 grok this nonetheless violates it too. */
744 if (!(ncmdp = issue_imap_cmd(ctx, &cmdp->cb, "%s", cmdp->cmd))) {
751 return 0; /* ignored */
757 } else /*if (!strcmp("BAD", arg))*/
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)
768 cmdp->cb.done(ctx, cmdp, resp);
772 if (!tcmd || tcmd == cmdp)
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);
790 static void imap_close_store(struct imap_store *ctx)
792 imap_close_server(ctx);
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;
812 unsigned char hash[16];
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);
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);
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);
846 die("EVP_EncodeBlock error");
847 response_64[encoded_len] = '\0';
848 return (char *)response_64;
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.");
861 static int auth_cram_md5(struct imap_store *ctx, struct imap_cmd *cmd, const char *prompt)
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");
877 static struct imap_store *imap_open_store(struct imap_server_conf *srvc)
879 struct imap_store *ctx;
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 */
893 const char *argv[] = { srvc->tunnel, NULL };
894 struct child_process tunnel = {NULL};
896 imap_info("Starting tunnel '%s'... ", srvc->tunnel);
899 tunnel.use_shell = 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;
911 struct addrinfo hints, *ai0, *ai;
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);
924 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai));
929 for (ai0 = ai; ai; ai = ai->ai_next) {
930 char addr[NI_MAXHOST];
932 s = socket(ai->ai_family, ai->ai_socktype,
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) {
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);
962 perror("gethostbyname");
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))) {
979 fputs("Error: unable to connect to server.\n", stderr);
983 imap->buf.sock.fd[0] = s;
984 imap->buf.sock.fd[1] = dup(s);
987 ssl_socket_connect(&imap->buf.sock, 0, srvc->ssl_verify)) {
994 /* read the greeting string */
995 if (buffer_gets(&imap->buf, &rsp)) {
996 fprintf(stderr, "IMAP error: no greeting response\n");
999 arg = next_arg(&rsp);
1000 if (!arg || *arg != '*' || (arg = next_arg(&rsp)) == NULL) {
1001 fprintf(stderr, "IMAP error: invalid greeting response\n");
1005 if (!strcmp("PREAUTH", arg))
1007 else if (strcmp("OK", arg) != 0) {
1008 fprintf(stderr, "IMAP error: unknown greeting response\n");
1011 parse_response_code(ctx, NULL, rsp);
1012 if (!imap->caps && imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1017 if (!srvc->use_ssl && CAP(STARTTLS)) {
1018 if (imap_exec(ctx, NULL, "STARTTLS") != RESP_OK)
1020 if (ssl_socket_connect(&imap->buf.sock, 1,
1023 /* capabilities may have changed, so get the new capabilities */
1024 if (imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1028 imap_info("Logging in...\n");
1030 fprintf(stderr, "Skipping server %s, no user\n", srvc->host);
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);
1039 fprintf(stderr, "Skipping account %s@%s, no password\n", srvc->user, srvc->host);
1043 * getpass() returns a pointer to a static buffer. make a copy
1044 * for long term storage.
1046 srvc->pass = xstrdup(arg);
1049 fprintf(stderr, "Skipping account %s@%s, server forbids LOGIN\n", srvc->user, srvc->host);
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);
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");
1072 fprintf(stderr, "Unknown authentication method:%s\n", srvc->host);
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");
1090 imap_close_store(ctx);
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)
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];
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')
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;
1138 memset(&cb, 0, sizeof(cb));
1141 cb.data = strbuf_detach(msg, NULL);
1144 prefix = !strcmp(box, "INBOX") ? "" : ctx->prefix;
1146 ret = imap_exec_m(ctx, &cb, "APPEND \"%s%s\" ", prefix, box);
1147 imap->caps = imap->rcaps;
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");
1163 return; /* Headers but no body; no wrapping needed */
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);
1178 #define CHUNKSIZE 0x1000
1180 static int read_message(FILE *f, struct strbuf *all_msgs)
1183 if (strbuf_fread(all_msgs, CHUNKSIZE, f) <= 0)
1187 return ferror(f) ? -1 : 0;
1190 static int count_messages(struct strbuf *all_msgs)
1193 char *p = all_msgs->buf;
1196 if (!prefixcmp(p, "From ")) {
1197 p = strstr(p+5, "\nFrom: ");
1199 p = strstr(p+7, "\nDate: ");
1201 p = strstr(p+7, "\nSubject: ");
1206 p = strstr(p+5, "\nFrom ");
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)
1224 if (*ofs >= all_msgs->len)
1227 data = &all_msgs->buf[*ofs];
1228 len = all_msgs->len - *ofs;
1230 if (len < 5 || prefixcmp(data, "From "))
1233 p = strchr(data, '\n');
1241 p = strstr(data, "\nFrom ");
1245 strbuf_add(msg, data, len);
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))
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);
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:"))
1274 else if (!prefixcmp(val, "imaps:")) {
1278 if (!prefixcmp(val, "//"))
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);
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;
1305 git_extract_argv0_path(argv[0]);
1307 git_setup_gettext();
1310 usage(imap_send_usage);
1312 setup_git_directory_gently(&nongit_ok);
1313 git_config(git_imap_config, NULL);
1316 server.port = server.use_ssl ? 993 : 143;
1319 fprintf(stderr, "no imap store specified\n");
1323 if (!server.tunnel) {
1324 fprintf(stderr, "no imap host specified\n");
1327 server.host = "tunnel";
1330 /* read the messages */
1331 if (read_message(stdin, &all_msgs)) {
1332 fprintf(stderr, "error reading input\n");
1336 if (all_msgs.len == 0) {
1337 fprintf(stderr, "nothing to send\n");
1341 total = count_messages(&all_msgs);
1343 fprintf(stderr, "no messages to send\n");
1347 /* write it to the imap server */
1348 ctx = imap_open_store(&server);
1350 fprintf(stderr, "failed to open store\n");
1354 fprintf(stderr, "sending %d message%s\n", total, (total != 1) ? "s" : "");
1355 ctx->name = imap_folder;
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))
1362 if (server.use_html)
1364 r = imap_store_msg(ctx, &msg);
1369 fprintf(stderr, "\n");
1371 imap_close_store(ctx);