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 */
130 unsigned /*currentnc:1,*/ trashnc:1;
134 int (*cont)(struct imap_store *ctx, struct imap_cmd *cmd, const char *prompt);
135 void (*done)(struct imap_store *ctx, struct imap_cmd *cmd, int response);
140 unsigned create:1, trycreate:1;
144 struct imap_cmd *next;
145 struct imap_cmd_cb cb;
150 #define CAP(cap) (imap->caps & (1 << (cap)))
161 static const char *cap_list[] = {
174 static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd);
178 static void ssl_socket_perror(const char *func)
180 fprintf(stderr, "%s: %s\n", func, ERR_error_string(ERR_get_error(), NULL));
184 static void socket_perror(const char *func, struct imap_socket *sock, int ret)
188 int sslerr = SSL_get_error(sock->ssl, ret);
192 case SSL_ERROR_SYSCALL:
193 perror("SSL_connect");
196 ssl_socket_perror("SSL_connect");
205 fprintf(stderr, "%s: unexpected EOF\n", func);
209 static int ssl_socket_connect(struct imap_socket *sock, int use_tls_only, int verify)
212 fprintf(stderr, "SSL requested but SSL support not compiled in\n");
215 #if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
216 const SSL_METHOD *meth;
224 SSL_load_error_strings();
227 meth = TLSv1_method();
229 meth = SSLv23_method();
232 ssl_socket_perror("SSLv23_method");
236 ctx = SSL_CTX_new(meth);
239 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
241 if (!SSL_CTX_set_default_verify_paths(ctx)) {
242 ssl_socket_perror("SSL_CTX_set_default_verify_paths");
245 sock->ssl = SSL_new(ctx);
247 ssl_socket_perror("SSL_new");
250 if (!SSL_set_rfd(sock->ssl, sock->fd[0])) {
251 ssl_socket_perror("SSL_set_rfd");
254 if (!SSL_set_wfd(sock->ssl, sock->fd[1])) {
255 ssl_socket_perror("SSL_set_wfd");
259 ret = SSL_connect(sock->ssl);
261 socket_perror("SSL_connect", sock, ret);
269 static int socket_read(struct imap_socket *sock, char *buf, int len)
274 n = SSL_read(sock->ssl, buf, len);
277 n = xread(sock->fd[0], buf, len);
279 socket_perror("read", sock, n);
282 sock->fd[0] = sock->fd[1] = -1;
287 static int socket_write(struct imap_socket *sock, const char *buf, int len)
292 n = SSL_write(sock->ssl, buf, len);
295 n = write_in_full(sock->fd[1], buf, len);
297 socket_perror("write", sock, n);
300 sock->fd[0] = sock->fd[1] = -1;
305 static void socket_shutdown(struct imap_socket *sock)
309 SSL_shutdown(sock->ssl);
317 /* simple line buffering */
318 static int buffer_gets(struct imap_buffer *b, char **s)
321 int start = b->offset;
326 /* make sure we have enough data to read the \r\n sequence */
327 if (b->offset + 1 >= b->bytes) {
329 /* shift down used bytes */
332 assert(start <= b->bytes);
333 n = b->bytes - start;
336 memmove(b->buf, b->buf + start, n);
342 n = socket_read(&b->sock, b->buf + b->bytes,
343 sizeof(b->buf) - b->bytes);
351 if (b->buf[b->offset] == '\r') {
352 assert(b->offset + 1 < b->bytes);
353 if (b->buf[b->offset + 1] == '\n') {
354 b->buf[b->offset] = 0; /* terminate the string */
355 b->offset += 2; /* next line */
367 static void imap_info(const char *msg, ...)
379 static void imap_warn(const char *msg, ...)
385 vfprintf(stderr, msg, va);
390 static char *next_arg(char **s)
396 while (isspace((unsigned char) **s))
405 *s = strchr(*s, '"');
408 while (**s && !isspace((unsigned char) **s))
420 static int nfsnprintf(char *buf, int blen, const char *fmt, ...)
426 if (blen <= 0 || (unsigned)(ret = vsnprintf(buf, blen, fmt, va)) >= (unsigned)blen)
427 die("Fatal: buffer too small. Please report a bug.");
432 static struct imap_cmd *v_issue_imap_cmd(struct imap_store *ctx,
433 struct imap_cmd_cb *cb,
434 const char *fmt, va_list ap)
436 struct imap *imap = ctx->imap;
437 struct imap_cmd *cmd;
441 cmd = xmalloc(sizeof(struct imap_cmd));
442 nfvasprintf(&cmd->cmd, fmt, ap);
443 cmd->tag = ++imap->nexttag;
448 memset(&cmd->cb, 0, sizeof(cmd->cb));
450 while (imap->literal_pending)
451 get_cmd_result(ctx, NULL);
454 bufl = nfsnprintf(buf, sizeof(buf), "%d %s\r\n", cmd->tag, cmd->cmd);
456 bufl = nfsnprintf(buf, sizeof(buf), "%d %s{%d%s}\r\n",
457 cmd->tag, cmd->cmd, cmd->cb.dlen,
458 CAP(LITERALPLUS) ? "+" : "");
461 if (imap->num_in_progress)
462 printf("(%d in progress) ", imap->num_in_progress);
463 if (memcmp(cmd->cmd, "LOGIN", 5))
464 printf(">>> %s", buf);
466 printf(">>> %d LOGIN <user> <pass>\n", cmd->tag);
468 if (socket_write(&imap->buf.sock, buf, bufl) != bufl) {
476 if (CAP(LITERALPLUS)) {
477 n = socket_write(&imap->buf.sock, cmd->cb.data, cmd->cb.dlen);
479 if (n != cmd->cb.dlen ||
480 socket_write(&imap->buf.sock, "\r\n", 2) != 2) {
487 imap->literal_pending = 1;
488 } else if (cmd->cb.cont)
489 imap->literal_pending = 1;
491 *imap->in_progress_append = cmd;
492 imap->in_progress_append = &cmd->next;
493 imap->num_in_progress++;
497 __attribute__((format (printf, 3, 4)))
498 static struct imap_cmd *issue_imap_cmd(struct imap_store *ctx,
499 struct imap_cmd_cb *cb,
500 const char *fmt, ...)
502 struct imap_cmd *ret;
506 ret = v_issue_imap_cmd(ctx, cb, fmt, ap);
511 __attribute__((format (printf, 3, 4)))
512 static int imap_exec(struct imap_store *ctx, struct imap_cmd_cb *cb,
513 const char *fmt, ...)
516 struct imap_cmd *cmdp;
519 cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
524 return get_cmd_result(ctx, cmdp);
527 __attribute__((format (printf, 3, 4)))
528 static int imap_exec_m(struct imap_store *ctx, struct imap_cmd_cb *cb,
529 const char *fmt, ...)
532 struct imap_cmd *cmdp;
535 cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
538 return DRV_STORE_BAD;
540 switch (get_cmd_result(ctx, cmdp)) {
541 case RESP_BAD: return DRV_STORE_BAD;
542 case RESP_NO: return DRV_MSG_BAD;
543 default: return DRV_OK;
547 static int skip_imap_list_l(char **sp, int level)
552 while (isspace((unsigned char)*s))
554 if (level && *s == ')') {
561 if (skip_imap_list_l(&s, level + 1))
563 } else if (*s == '"') {
566 for (; *s != '"'; s++)
572 for (; *s && !isspace((unsigned char)*s); s++)
573 if (level && *s == ')')
589 static void skip_list(char **sp)
591 skip_imap_list_l(sp, 0);
594 static void parse_capability(struct imap *imap, char *cmd)
599 imap->caps = 0x80000000;
600 while ((arg = next_arg(&cmd)))
601 for (i = 0; i < ARRAY_SIZE(cap_list); i++)
602 if (!strcmp(cap_list[i], arg))
603 imap->caps |= 1 << i;
604 imap->rcaps = imap->caps;
607 static int parse_response_code(struct imap_store *ctx, struct imap_cmd_cb *cb,
610 struct imap *imap = ctx->imap;
614 return RESP_OK; /* no response code */
616 if (!(p = strchr(s, ']'))) {
617 fprintf(stderr, "IMAP error: malformed response code\n");
622 if (!strcmp("UIDVALIDITY", arg)) {
623 if (!(arg = next_arg(&s)) || !(ctx->gen.uidvalidity = atoi(arg))) {
624 fprintf(stderr, "IMAP error: malformed UIDVALIDITY status\n");
627 } else if (!strcmp("UIDNEXT", arg)) {
628 if (!(arg = next_arg(&s)) || !(imap->uidnext = atoi(arg))) {
629 fprintf(stderr, "IMAP error: malformed NEXTUID status\n");
632 } else if (!strcmp("CAPABILITY", arg)) {
633 parse_capability(imap, s);
634 } else if (!strcmp("ALERT", arg)) {
635 /* RFC2060 says that these messages MUST be displayed
638 for (; isspace((unsigned char)*p); p++);
639 fprintf(stderr, "*** IMAP ALERT *** %s\n", p);
640 } else if (cb && cb->ctx && !strcmp("APPENDUID", arg)) {
641 if (!(arg = next_arg(&s)) || !(ctx->gen.uidvalidity = atoi(arg)) ||
642 !(arg = next_arg(&s)) || !(*(int *)cb->ctx = atoi(arg))) {
643 fprintf(stderr, "IMAP error: malformed APPENDUID status\n");
650 static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd)
652 struct imap *imap = ctx->imap;
653 struct imap_cmd *cmdp, **pcmdp, *ncmdp;
654 char *cmd, *arg, *arg1, *p;
655 int n, resp, resp2, tag;
658 if (buffer_gets(&imap->buf, &cmd))
661 arg = next_arg(&cmd);
663 arg = next_arg(&cmd);
665 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
669 if (!strcmp("NAMESPACE", arg)) {
670 /* rfc2342 NAMESPACE response. */
671 skip_list(&cmd); /* Personal mailboxes */
672 skip_list(&cmd); /* Others' mailboxes */
673 skip_list(&cmd); /* Shared mailboxes */
674 } else if (!strcmp("OK", arg) || !strcmp("BAD", arg) ||
675 !strcmp("NO", arg) || !strcmp("BYE", arg)) {
676 if ((resp = parse_response_code(ctx, NULL, cmd)) != RESP_OK)
678 } else if (!strcmp("CAPABILITY", arg)) {
679 parse_capability(imap, cmd);
680 } else if ((arg1 = next_arg(&cmd))) {
682 * Unhandled response-data with at least two words.
685 * NEEDSWORK: Previously this case handled '<num> EXISTS'
686 * and '<num> RECENT' but as a probably-unintended side
687 * effect it ignores other unrecognized two-word
688 * responses. imap-send doesn't ever try to read
689 * messages or mailboxes these days, so consider
690 * eliminating this case.
693 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
696 } else if (!imap->in_progress) {
697 fprintf(stderr, "IMAP error: unexpected reply: %s %s\n", arg, cmd ? cmd : "");
699 } else if (*arg == '+') {
700 /* This can happen only with the last command underway, as
701 it enforces a round-trip. */
702 cmdp = (struct imap_cmd *)((char *)imap->in_progress_append -
703 offsetof(struct imap_cmd, next));
705 n = socket_write(&imap->buf.sock, cmdp->cb.data, cmdp->cb.dlen);
707 cmdp->cb.data = NULL;
708 if (n != (int)cmdp->cb.dlen)
710 } else if (cmdp->cb.cont) {
711 if (cmdp->cb.cont(ctx, cmdp, cmd))
714 fprintf(stderr, "IMAP error: unexpected command continuation request\n");
717 if (socket_write(&imap->buf.sock, "\r\n", 2) != 2)
720 imap->literal_pending = 0;
725 for (pcmdp = &imap->in_progress; (cmdp = *pcmdp); pcmdp = &cmdp->next)
726 if (cmdp->tag == tag)
728 fprintf(stderr, "IMAP error: unexpected tag %s\n", arg);
731 if (!(*pcmdp = cmdp->next))
732 imap->in_progress_append = pcmdp;
733 imap->num_in_progress--;
734 if (cmdp->cb.cont || cmdp->cb.data)
735 imap->literal_pending = 0;
736 arg = next_arg(&cmd);
737 if (!strcmp("OK", arg))
740 if (!strcmp("NO", arg)) {
741 if (cmdp->cb.create && cmd && (cmdp->cb.trycreate || !memcmp(cmd, "[TRYCREATE]", 11))) { /* SELECT, APPEND or UID COPY */
742 p = strchr(cmdp->cmd, '"');
743 if (!issue_imap_cmd(ctx, NULL, "CREATE \"%.*s\"", (int)(strchr(p + 1, '"') - p + 1), p)) {
747 /* not waiting here violates the spec, but a server that does not
748 grok this nonetheless violates it too. */
750 if (!(ncmdp = issue_imap_cmd(ctx, &cmdp->cb, "%s", cmdp->cmd))) {
757 return 0; /* ignored */
763 } else /*if (!strcmp("BAD", arg))*/
765 fprintf(stderr, "IMAP command '%s' returned response (%s) - %s\n",
766 memcmp(cmdp->cmd, "LOGIN", 5) ?
767 cmdp->cmd : "LOGIN <user> <pass>",
768 arg, cmd ? cmd : "");
770 if ((resp2 = parse_response_code(ctx, &cmdp->cb, cmd)) > resp)
774 cmdp->cb.done(ctx, cmdp, resp);
778 if (!tcmd || tcmd == cmdp)
785 static void imap_close_server(struct imap_store *ictx)
787 struct imap *imap = ictx->imap;
789 if (imap->buf.sock.fd[0] != -1) {
790 imap_exec(ictx, NULL, "LOGOUT");
791 socket_shutdown(&imap->buf.sock);
796 static void imap_close_store(struct store *ctx)
798 imap_close_server((struct imap_store *)ctx);
805 * hexchar() and cram() functions are based on the code from the isync
806 * project (http://isync.sf.net/).
808 static char hexchar(unsigned int b)
810 return b < 10 ? '0' + b : 'a' + (b - 10);
813 #define ENCODED_SIZE(n) (4*((n+2)/3))
814 static char *cram(const char *challenge_64, const char *user, const char *pass)
816 int i, resp_len, encoded_len, decoded_len;
818 unsigned char hash[16];
820 char *response, *response_64, *challenge;
823 * length of challenge_64 (i.e. base-64 encoded string) is a good
824 * enough upper bound for challenge (decoded result).
826 encoded_len = strlen(challenge_64);
827 challenge = xmalloc(encoded_len);
828 decoded_len = EVP_DecodeBlock((unsigned char *)challenge,
829 (unsigned char *)challenge_64, encoded_len);
831 die("invalid challenge %s", challenge_64);
832 HMAC_Init(&hmac, (unsigned char *)pass, strlen(pass), EVP_md5());
833 HMAC_Update(&hmac, (unsigned char *)challenge, decoded_len);
834 HMAC_Final(&hmac, hash, NULL);
835 HMAC_CTX_cleanup(&hmac);
838 for (i = 0; i < 16; i++) {
839 hex[2 * i] = hexchar((hash[i] >> 4) & 0xf);
840 hex[2 * i + 1] = hexchar(hash[i] & 0xf);
843 /* response: "<user> <digest in hex>" */
844 resp_len = strlen(user) + 1 + strlen(hex) + 1;
845 response = xmalloc(resp_len);
846 sprintf(response, "%s %s", user, hex);
848 response_64 = xmalloc(ENCODED_SIZE(resp_len) + 1);
849 encoded_len = EVP_EncodeBlock((unsigned char *)response_64,
850 (unsigned char *)response, resp_len);
852 die("EVP_EncodeBlock error");
853 response_64[encoded_len] = '\0';
854 return (char *)response_64;
859 static char *cram(const char *challenge_64, const char *user, const char *pass)
861 die("If you want to use CRAM-MD5 authenticate method, "
862 "you have to build git-imap-send with OpenSSL library.");
867 static int auth_cram_md5(struct imap_store *ctx, struct imap_cmd *cmd, const char *prompt)
872 response = cram(prompt, server.user, server.pass);
874 ret = socket_write(&ctx->imap->buf.sock, response, strlen(response));
875 if (ret != strlen(response))
876 return error("IMAP error: sending response failed");
883 static struct store *imap_open_store(struct imap_server_conf *srvc)
885 struct imap_store *ctx;
890 ctx = xcalloc(sizeof(*ctx), 1);
892 ctx->imap = imap = xcalloc(sizeof(*imap), 1);
893 imap->buf.sock.fd[0] = imap->buf.sock.fd[1] = -1;
894 imap->in_progress_append = &imap->in_progress;
896 /* open connection to IMAP server */
899 const char *argv[] = { srvc->tunnel, NULL };
900 struct child_process tunnel = {NULL};
902 imap_info("Starting tunnel '%s'... ", srvc->tunnel);
905 tunnel.use_shell = 1;
908 if (start_command(&tunnel))
909 die("cannot start proxy %s", argv[0]);
911 imap->buf.sock.fd[0] = tunnel.out;
912 imap->buf.sock.fd[1] = tunnel.in;
917 struct addrinfo hints, *ai0, *ai;
921 snprintf(portstr, sizeof(portstr), "%d", srvc->port);
923 memset(&hints, 0, sizeof(hints));
924 hints.ai_socktype = SOCK_STREAM;
925 hints.ai_protocol = IPPROTO_TCP;
927 imap_info("Resolving %s... ", srvc->host);
928 gai = getaddrinfo(srvc->host, portstr, &hints, &ai);
930 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai));
935 for (ai0 = ai; ai; ai = ai->ai_next) {
936 char addr[NI_MAXHOST];
938 s = socket(ai->ai_family, ai->ai_socktype,
943 getnameinfo(ai->ai_addr, ai->ai_addrlen, addr,
944 sizeof(addr), NULL, 0, NI_NUMERICHOST);
945 imap_info("Connecting to [%s]:%s... ", addr, portstr);
947 if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0) {
959 struct sockaddr_in addr;
961 memset(&addr, 0, sizeof(addr));
962 addr.sin_port = htons(srvc->port);
963 addr.sin_family = AF_INET;
965 imap_info("Resolving %s... ", srvc->host);
966 he = gethostbyname(srvc->host);
968 perror("gethostbyname");
973 addr.sin_addr.s_addr = *((int *) he->h_addr_list[0]);
975 s = socket(PF_INET, SOCK_STREAM, 0);
977 imap_info("Connecting to %s:%hu... ", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
978 if (connect(s, (struct sockaddr *)&addr, sizeof(addr))) {
985 fputs("Error: unable to connect to server.\n", stderr);
989 imap->buf.sock.fd[0] = s;
990 imap->buf.sock.fd[1] = dup(s);
993 ssl_socket_connect(&imap->buf.sock, 0, srvc->ssl_verify)) {
1000 /* read the greeting string */
1001 if (buffer_gets(&imap->buf, &rsp)) {
1002 fprintf(stderr, "IMAP error: no greeting response\n");
1005 arg = next_arg(&rsp);
1006 if (!arg || *arg != '*' || (arg = next_arg(&rsp)) == NULL) {
1007 fprintf(stderr, "IMAP error: invalid greeting response\n");
1011 if (!strcmp("PREAUTH", arg))
1013 else if (strcmp("OK", arg) != 0) {
1014 fprintf(stderr, "IMAP error: unknown greeting response\n");
1017 parse_response_code(ctx, NULL, rsp);
1018 if (!imap->caps && imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1023 if (!srvc->use_ssl && CAP(STARTTLS)) {
1024 if (imap_exec(ctx, NULL, "STARTTLS") != RESP_OK)
1026 if (ssl_socket_connect(&imap->buf.sock, 1,
1029 /* capabilities may have changed, so get the new capabilities */
1030 if (imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1034 imap_info("Logging in...\n");
1036 fprintf(stderr, "Skipping server %s, no user\n", srvc->host);
1040 struct strbuf prompt = STRBUF_INIT;
1041 strbuf_addf(&prompt, "Password (%s@%s): ", srvc->user, srvc->host);
1042 arg = git_getpass(prompt.buf);
1043 strbuf_release(&prompt);
1045 fprintf(stderr, "Skipping account %s@%s, no password\n", srvc->user, srvc->host);
1049 * getpass() returns a pointer to a static buffer. make a copy
1050 * for long term storage.
1052 srvc->pass = xstrdup(arg);
1055 fprintf(stderr, "Skipping account %s@%s, server forbids LOGIN\n", srvc->user, srvc->host);
1059 if (srvc->auth_method) {
1060 struct imap_cmd_cb cb;
1062 if (!strcmp(srvc->auth_method, "CRAM-MD5")) {
1063 if (!CAP(AUTH_CRAM_MD5)) {
1064 fprintf(stderr, "You specified"
1065 "CRAM-MD5 as authentication method, "
1066 "but %s doesn't support it.\n", srvc->host);
1071 memset(&cb, 0, sizeof(cb));
1072 cb.cont = auth_cram_md5;
1073 if (imap_exec(ctx, &cb, "AUTHENTICATE CRAM-MD5") != RESP_OK) {
1074 fprintf(stderr, "IMAP error: AUTHENTICATE CRAM-MD5 failed\n");
1078 fprintf(stderr, "Unknown authentication method:%s\n", srvc->host);
1082 if (!imap->buf.sock.ssl)
1083 imap_warn("*** IMAP Warning *** Password is being "
1084 "sent in the clear\n");
1085 if (imap_exec(ctx, NULL, "LOGIN \"%s\" \"%s\"", srvc->user, srvc->pass) != RESP_OK) {
1086 fprintf(stderr, "IMAP error: LOGIN failed\n");
1094 return (struct store *)ctx;
1097 imap_close_store(&ctx->gen);
1101 static void lf_to_crlf(struct strbuf *msg)
1105 int i, j, lfnum = 0;
1107 if (msg->buf[0] == '\n')
1109 for (i = 1; i < msg->len; i++) {
1110 if (msg->buf[i - 1] != '\r' && msg->buf[i] == '\n')
1114 new_len = msg->len + lfnum;
1115 new = xmalloc(new_len + 1);
1116 if (msg->buf[0] == '\n') {
1122 new[0] = msg->buf[0];
1126 for ( ; i < msg->len; i++) {
1127 if (msg->buf[i] != '\n') {
1128 new[j++] = msg->buf[i];
1131 if (msg->buf[i - 1] != '\r')
1133 /* otherwise it already had CR before */
1136 strbuf_attach(msg, new, new_len, new_len + 1);
1140 * Store msg to IMAP. Also detach and free the data from msg->data,
1141 * leaving msg->data empty.
1143 static int imap_store_msg(struct store *gctx, struct strbuf *msg)
1145 struct imap_store *ctx = (struct imap_store *)gctx;
1146 struct imap *imap = ctx->imap;
1147 struct imap_cmd_cb cb;
1148 const char *prefix, *box;
1152 memset(&cb, 0, sizeof(cb));
1155 cb.data = strbuf_detach(msg, NULL);
1158 prefix = !strcmp(box, "INBOX") ? "" : ctx->prefix;
1160 ret = imap_exec_m(ctx, &cb, "APPEND \"%s%s\" ", prefix, box);
1161 imap->caps = imap->rcaps;
1168 static void wrap_in_html(struct strbuf *msg)
1170 struct strbuf buf = STRBUF_INIT;
1171 static char *content_type = "Content-Type: text/html;\n";
1172 static char *pre_open = "<pre>\n";
1173 static char *pre_close = "</pre>\n";
1174 const char *body = strstr(msg->buf, "\n\n");
1177 return; /* Headers but no body; no wrapping needed */
1181 strbuf_add(&buf, msg->buf, body - msg->buf - 1);
1182 strbuf_addstr(&buf, content_type);
1183 strbuf_addch(&buf, '\n');
1184 strbuf_addstr(&buf, pre_open);
1185 strbuf_addstr_xml_quoted(&buf, body);
1186 strbuf_addstr(&buf, pre_close);
1188 strbuf_release(msg);
1192 #define CHUNKSIZE 0x1000
1194 static int read_message(FILE *f, struct strbuf *all_msgs)
1197 if (strbuf_fread(all_msgs, CHUNKSIZE, f) <= 0)
1201 return ferror(f) ? -1 : 0;
1204 static int count_messages(struct strbuf *all_msgs)
1207 char *p = all_msgs->buf;
1210 if (!prefixcmp(p, "From ")) {
1211 p = strstr(p+5, "\nFrom: ");
1213 p = strstr(p+7, "\nDate: ");
1215 p = strstr(p+7, "\nSubject: ");
1220 p = strstr(p+5, "\nFrom ");
1229 * Copy the next message from all_msgs, starting at offset *ofs, to
1230 * msg. Update *ofs to the start of the following message. Return
1231 * true iff a message was successfully copied.
1233 static int split_msg(struct strbuf *all_msgs, struct strbuf *msg, int *ofs)
1238 if (*ofs >= all_msgs->len)
1241 data = &all_msgs->buf[*ofs];
1242 len = all_msgs->len - *ofs;
1244 if (len < 5 || prefixcmp(data, "From "))
1247 p = strchr(data, '\n');
1255 p = strstr(data, "\nFrom ");
1259 strbuf_add(msg, data, len);
1264 static char *imap_folder;
1266 static int git_imap_config(const char *key, const char *val, void *cb)
1268 char imap_key[] = "imap.";
1270 if (strncmp(key, imap_key, sizeof imap_key - 1))
1273 key += sizeof imap_key - 1;
1275 /* check booleans first, and barf on others */
1276 if (!strcmp("sslverify", key))
1277 server.ssl_verify = git_config_bool(key, val);
1278 else if (!strcmp("preformattedhtml", key))
1279 server.use_html = git_config_bool(key, val);
1281 return config_error_nonbool(key);
1283 if (!strcmp("folder", key)) {
1284 imap_folder = xstrdup(val);
1285 } else if (!strcmp("host", key)) {
1286 if (!prefixcmp(val, "imap:"))
1288 else if (!prefixcmp(val, "imaps:")) {
1292 if (!prefixcmp(val, "//"))
1294 server.host = xstrdup(val);
1295 } else if (!strcmp("user", key))
1296 server.user = xstrdup(val);
1297 else if (!strcmp("pass", key))
1298 server.pass = xstrdup(val);
1299 else if (!strcmp("port", key))
1300 server.port = git_config_int(key, val);
1301 else if (!strcmp("tunnel", key))
1302 server.tunnel = xstrdup(val);
1303 else if (!strcmp("authmethod", key))
1304 server.auth_method = xstrdup(val);
1309 int main(int argc, char **argv)
1311 struct strbuf all_msgs = STRBUF_INIT;
1312 struct strbuf msg = STRBUF_INIT;
1313 struct store *ctx = NULL;
1319 git_extract_argv0_path(argv[0]);
1321 git_setup_gettext();
1324 usage(imap_send_usage);
1326 setup_git_directory_gently(&nongit_ok);
1327 git_config(git_imap_config, NULL);
1330 server.port = server.use_ssl ? 993 : 143;
1333 fprintf(stderr, "no imap store specified\n");
1337 if (!server.tunnel) {
1338 fprintf(stderr, "no imap host specified\n");
1341 server.host = "tunnel";
1344 /* read the messages */
1345 if (read_message(stdin, &all_msgs)) {
1346 fprintf(stderr, "error reading input\n");
1350 if (all_msgs.len == 0) {
1351 fprintf(stderr, "nothing to send\n");
1355 total = count_messages(&all_msgs);
1357 fprintf(stderr, "no messages to send\n");
1361 /* write it to the imap server */
1362 ctx = imap_open_store(&server);
1364 fprintf(stderr, "failed to open store\n");
1368 fprintf(stderr, "sending %d message%s\n", total, (total != 1) ? "s" : "");
1369 ctx->name = imap_folder;
1371 unsigned percent = n * 100 / total;
1373 fprintf(stderr, "%4u%% (%d/%d) done\r", percent, n, total);
1374 if (!split_msg(&all_msgs, &msg, &ofs))
1376 if (server.use_html)
1378 r = imap_store_msg(ctx, &msg);
1383 fprintf(stderr, "\n");
1385 imap_close_store(ctx);