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"
31 #include <openssl/evp.h>
32 #include <openssl/hmac.h>
37 const char *path; /* should this be here? its interpretation is driver-specific */
40 unsigned max_size; /* off_t is overkill */
41 unsigned trash_remote_new:1, trash_only_new:1;
44 /* For message->status */
45 #define M_RECENT (1<<0) /* unsyncable flag; maildir_* depend on this being 1<<0 */
46 #define M_DEAD (1<<1) /* expunged */
47 #define M_FLAGS (1<<2) /* flags fetched */
51 size_t size; /* zero implies "not fetched" */
53 unsigned char flags, status;
57 struct store_conf *conf; /* foreign */
59 /* currently open mailbox */
60 const char *name; /* foreign! maybe preset? */
62 struct message *msgs; /* own */
64 unsigned char opts; /* maybe preset? */
65 /* note that the following do _not_ reflect stats from msgs, but mailbox totals */
66 int count; /* # of messages */
67 int recent; /* # of recent messages - don't trust this beyond the initial read */
76 static const char imap_send_usage[] = "git imap-send < <mbox>";
80 #define DRV_MSG_BAD -1
81 #define DRV_BOX_BAD -2
82 #define DRV_STORE_BAD -3
84 static int Verbose, Quiet;
86 __attribute__((format (printf, 1, 2)))
87 static void imap_info(const char *, ...);
88 __attribute__((format (printf, 1, 2)))
89 static void imap_warn(const char *, ...);
91 static char *next_arg(char **);
93 static void free_generic_messages(struct message *);
95 __attribute__((format (printf, 3, 4)))
96 static int nfsnprintf(char *buf, int blen, const char *fmt, ...);
98 static int nfvasprintf(char **strp, const char *fmt, va_list ap)
103 len = vsnprintf(tmp, sizeof(tmp), fmt, ap);
105 die("Fatal: Out of memory");
106 if (len >= sizeof(tmp))
107 die("imap command overflow!");
108 *strp = xmemdupz(tmp, len);
112 struct imap_server_conf {
125 static struct imap_server_conf server = {
135 NULL, /* auth_method */
138 struct imap_store_conf {
139 struct store_conf gen;
140 struct imap_server_conf *server;
141 unsigned use_namespace:1;
144 #define NIL (void *)0x1
145 #define LIST (void *)0x2
148 struct imap_list *next, *child;
159 struct imap_socket sock;
168 int uidnext; /* from SELECT responses */
169 struct imap_list *ns_personal, *ns_other, *ns_shared; /* NAMESPACE info */
170 unsigned caps, rcaps; /* CAPABILITY results */
172 int nexttag, num_in_progress, literal_pending;
173 struct imap_cmd *in_progress, **in_progress_append;
174 struct imap_buffer buf; /* this is BIG, so put it last */
182 unsigned /*currentnc:1,*/ trashnc:1;
186 int (*cont)(struct imap_store *ctx, struct imap_cmd *cmd, const char *prompt);
187 void (*done)(struct imap_store *ctx, struct imap_cmd *cmd, int response);
192 unsigned create:1, trycreate:1;
196 struct imap_cmd *next;
197 struct imap_cmd_cb cb;
202 #define CAP(cap) (imap->caps & (1 << (cap)))
213 static const char *cap_list[] = {
226 static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd);
229 static const char *Flags[] = {
238 static void ssl_socket_perror(const char *func)
240 fprintf(stderr, "%s: %s\n", func, ERR_error_string(ERR_get_error(), NULL));
244 static void socket_perror(const char *func, struct imap_socket *sock, int ret)
248 int sslerr = SSL_get_error(sock->ssl, ret);
252 case SSL_ERROR_SYSCALL:
253 perror("SSL_connect");
256 ssl_socket_perror("SSL_connect");
265 fprintf(stderr, "%s: unexpected EOF\n", func);
270 static int ssl_socket_connect(struct imap_socket *sock, int use_tls_only, int verify)
272 fprintf(stderr, "SSL requested but SSL support not compiled in\n");
278 static int ssl_socket_connect(struct imap_socket *sock, int use_tls_only, int verify)
280 #if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
281 const SSL_METHOD *meth;
289 SSL_load_error_strings();
292 meth = TLSv1_method();
294 meth = SSLv23_method();
297 ssl_socket_perror("SSLv23_method");
301 ctx = SSL_CTX_new(meth);
304 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
306 if (!SSL_CTX_set_default_verify_paths(ctx)) {
307 ssl_socket_perror("SSL_CTX_set_default_verify_paths");
310 sock->ssl = SSL_new(ctx);
312 ssl_socket_perror("SSL_new");
315 if (!SSL_set_rfd(sock->ssl, sock->fd[0])) {
316 ssl_socket_perror("SSL_set_rfd");
319 if (!SSL_set_wfd(sock->ssl, sock->fd[1])) {
320 ssl_socket_perror("SSL_set_wfd");
324 ret = SSL_connect(sock->ssl);
326 socket_perror("SSL_connect", sock, ret);
334 static int socket_read(struct imap_socket *sock, char *buf, int len)
339 n = SSL_read(sock->ssl, buf, len);
342 n = xread(sock->fd[0], buf, len);
344 socket_perror("read", sock, n);
347 sock->fd[0] = sock->fd[1] = -1;
352 static int socket_write(struct imap_socket *sock, const char *buf, int len)
357 n = SSL_write(sock->ssl, buf, len);
360 n = write_in_full(sock->fd[1], buf, len);
362 socket_perror("write", sock, n);
365 sock->fd[0] = sock->fd[1] = -1;
370 static void socket_shutdown(struct imap_socket *sock)
374 SSL_shutdown(sock->ssl);
382 /* simple line buffering */
383 static int buffer_gets(struct imap_buffer *b, char **s)
386 int start = b->offset;
391 /* make sure we have enough data to read the \r\n sequence */
392 if (b->offset + 1 >= b->bytes) {
394 /* shift down used bytes */
397 assert(start <= b->bytes);
398 n = b->bytes - start;
401 memmove(b->buf, b->buf + start, n);
407 n = socket_read(&b->sock, b->buf + b->bytes,
408 sizeof(b->buf) - b->bytes);
416 if (b->buf[b->offset] == '\r') {
417 assert(b->offset + 1 < b->bytes);
418 if (b->buf[b->offset + 1] == '\n') {
419 b->buf[b->offset] = 0; /* terminate the string */
420 b->offset += 2; /* next line */
432 static void imap_info(const char *msg, ...)
444 static void imap_warn(const char *msg, ...)
450 vfprintf(stderr, msg, va);
455 static char *next_arg(char **s)
461 while (isspace((unsigned char) **s))
470 *s = strchr(*s, '"');
473 while (**s && !isspace((unsigned char) **s))
485 static void free_generic_messages(struct message *msgs)
487 struct message *tmsg;
489 for (; msgs; msgs = tmsg) {
495 static int nfsnprintf(char *buf, int blen, const char *fmt, ...)
501 if (blen <= 0 || (unsigned)(ret = vsnprintf(buf, blen, fmt, va)) >= (unsigned)blen)
502 die("Fatal: buffer too small. Please report a bug.");
507 static struct imap_cmd *v_issue_imap_cmd(struct imap_store *ctx,
508 struct imap_cmd_cb *cb,
509 const char *fmt, va_list ap)
511 struct imap *imap = ctx->imap;
512 struct imap_cmd *cmd;
516 cmd = xmalloc(sizeof(struct imap_cmd));
517 nfvasprintf(&cmd->cmd, fmt, ap);
518 cmd->tag = ++imap->nexttag;
523 memset(&cmd->cb, 0, sizeof(cmd->cb));
525 while (imap->literal_pending)
526 get_cmd_result(ctx, NULL);
529 bufl = nfsnprintf(buf, sizeof(buf), "%d %s\r\n", cmd->tag, cmd->cmd);
531 bufl = nfsnprintf(buf, sizeof(buf), "%d %s{%d%s}\r\n",
532 cmd->tag, cmd->cmd, cmd->cb.dlen,
533 CAP(LITERALPLUS) ? "+" : "");
536 if (imap->num_in_progress)
537 printf("(%d in progress) ", imap->num_in_progress);
538 if (memcmp(cmd->cmd, "LOGIN", 5))
539 printf(">>> %s", buf);
541 printf(">>> %d LOGIN <user> <pass>\n", cmd->tag);
543 if (socket_write(&imap->buf.sock, buf, bufl) != bufl) {
551 if (CAP(LITERALPLUS)) {
552 n = socket_write(&imap->buf.sock, cmd->cb.data, cmd->cb.dlen);
554 if (n != cmd->cb.dlen ||
555 socket_write(&imap->buf.sock, "\r\n", 2) != 2) {
562 imap->literal_pending = 1;
563 } else if (cmd->cb.cont)
564 imap->literal_pending = 1;
566 *imap->in_progress_append = cmd;
567 imap->in_progress_append = &cmd->next;
568 imap->num_in_progress++;
572 __attribute__((format (printf, 3, 4)))
573 static struct imap_cmd *issue_imap_cmd(struct imap_store *ctx,
574 struct imap_cmd_cb *cb,
575 const char *fmt, ...)
577 struct imap_cmd *ret;
581 ret = v_issue_imap_cmd(ctx, cb, fmt, ap);
586 __attribute__((format (printf, 3, 4)))
587 static int imap_exec(struct imap_store *ctx, struct imap_cmd_cb *cb,
588 const char *fmt, ...)
591 struct imap_cmd *cmdp;
594 cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
599 return get_cmd_result(ctx, cmdp);
602 __attribute__((format (printf, 3, 4)))
603 static int imap_exec_m(struct imap_store *ctx, struct imap_cmd_cb *cb,
604 const char *fmt, ...)
607 struct imap_cmd *cmdp;
610 cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
613 return DRV_STORE_BAD;
615 switch (get_cmd_result(ctx, cmdp)) {
616 case RESP_BAD: return DRV_STORE_BAD;
617 case RESP_NO: return DRV_MSG_BAD;
618 default: return DRV_OK;
622 static int is_atom(struct imap_list *list)
624 return list && list->val && list->val != NIL && list->val != LIST;
627 static int is_list(struct imap_list *list)
629 return list && list->val == LIST;
632 static void free_list(struct imap_list *list)
634 struct imap_list *tmp;
636 for (; list; list = tmp) {
639 free_list(list->child);
640 else if (is_atom(list))
646 static int parse_imap_list_l(struct imap *imap, char **sp, struct imap_list **curp, int level)
648 struct imap_list *cur;
653 while (isspace((unsigned char)*s))
655 if (level && *s == ')') {
659 *curp = cur = xmalloc(sizeof(*cur));
661 cur->val = NULL; /* for clean bail */
666 if (parse_imap_list_l(imap, &s, &cur->child, level + 1))
668 } else if (imap && *s == '{') {
670 bytes = cur->len = strtol(s + 1, &s, 10);
674 s = cur->val = xmalloc(cur->len);
676 /* dump whats left over in the input buffer */
677 n = imap->buf.bytes - imap->buf.offset;
680 /* the entire message fit in the buffer */
683 memcpy(s, imap->buf.buf + imap->buf.offset, n);
687 /* mark that we used part of the buffer */
688 imap->buf.offset += n;
690 /* now read the rest of the message */
692 if ((n = socket_read(&imap->buf.sock, s, bytes)) <= 0)
698 if (buffer_gets(&imap->buf, &s))
700 } else if (*s == '"') {
704 for (; *s != '"'; s++)
709 cur->val = xmemdupz(p, cur->len);
713 for (; *s && !isspace((unsigned char)*s); s++)
714 if (level && *s == ')')
717 if (cur->len == 3 && !memcmp("NIL", p, 3))
720 cur->val = xmemdupz(p, cur->len);
737 static struct imap_list *parse_imap_list(struct imap *imap, char **sp)
739 struct imap_list *head;
741 if (!parse_imap_list_l(imap, sp, &head, 0))
747 static struct imap_list *parse_list(char **sp)
749 return parse_imap_list(NULL, sp);
752 static void parse_capability(struct imap *imap, char *cmd)
757 imap->caps = 0x80000000;
758 while ((arg = next_arg(&cmd)))
759 for (i = 0; i < ARRAY_SIZE(cap_list); i++)
760 if (!strcmp(cap_list[i], arg))
761 imap->caps |= 1 << i;
762 imap->rcaps = imap->caps;
765 static int parse_response_code(struct imap_store *ctx, struct imap_cmd_cb *cb,
768 struct imap *imap = ctx->imap;
772 return RESP_OK; /* no response code */
774 if (!(p = strchr(s, ']'))) {
775 fprintf(stderr, "IMAP error: malformed response code\n");
780 if (!strcmp("UIDVALIDITY", arg)) {
781 if (!(arg = next_arg(&s)) || !(ctx->gen.uidvalidity = atoi(arg))) {
782 fprintf(stderr, "IMAP error: malformed UIDVALIDITY status\n");
785 } else if (!strcmp("UIDNEXT", arg)) {
786 if (!(arg = next_arg(&s)) || !(imap->uidnext = atoi(arg))) {
787 fprintf(stderr, "IMAP error: malformed NEXTUID status\n");
790 } else if (!strcmp("CAPABILITY", arg)) {
791 parse_capability(imap, s);
792 } else if (!strcmp("ALERT", arg)) {
793 /* RFC2060 says that these messages MUST be displayed
796 for (; isspace((unsigned char)*p); p++);
797 fprintf(stderr, "*** IMAP ALERT *** %s\n", p);
798 } else if (cb && cb->ctx && !strcmp("APPENDUID", arg)) {
799 if (!(arg = next_arg(&s)) || !(ctx->gen.uidvalidity = atoi(arg)) ||
800 !(arg = next_arg(&s)) || !(*(int *)cb->ctx = atoi(arg))) {
801 fprintf(stderr, "IMAP error: malformed APPENDUID status\n");
808 static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd)
810 struct imap *imap = ctx->imap;
811 struct imap_cmd *cmdp, **pcmdp, *ncmdp;
812 char *cmd, *arg, *arg1, *p;
813 int n, resp, resp2, tag;
816 if (buffer_gets(&imap->buf, &cmd))
819 arg = next_arg(&cmd);
821 arg = next_arg(&cmd);
823 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
827 if (!strcmp("NAMESPACE", arg)) {
828 imap->ns_personal = parse_list(&cmd);
829 imap->ns_other = parse_list(&cmd);
830 imap->ns_shared = parse_list(&cmd);
831 } else if (!strcmp("OK", arg) || !strcmp("BAD", arg) ||
832 !strcmp("NO", arg) || !strcmp("BYE", arg)) {
833 if ((resp = parse_response_code(ctx, NULL, cmd)) != RESP_OK)
835 } else if (!strcmp("CAPABILITY", arg))
836 parse_capability(imap, cmd);
837 else if ((arg1 = next_arg(&cmd))) {
838 if (!strcmp("EXISTS", arg1))
839 ctx->gen.count = atoi(arg);
840 else if (!strcmp("RECENT", arg1))
841 ctx->gen.recent = atoi(arg);
843 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
846 } else if (!imap->in_progress) {
847 fprintf(stderr, "IMAP error: unexpected reply: %s %s\n", arg, cmd ? cmd : "");
849 } else if (*arg == '+') {
850 /* This can happen only with the last command underway, as
851 it enforces a round-trip. */
852 cmdp = (struct imap_cmd *)((char *)imap->in_progress_append -
853 offsetof(struct imap_cmd, next));
855 n = socket_write(&imap->buf.sock, cmdp->cb.data, cmdp->cb.dlen);
857 cmdp->cb.data = NULL;
858 if (n != (int)cmdp->cb.dlen)
860 } else if (cmdp->cb.cont) {
861 if (cmdp->cb.cont(ctx, cmdp, cmd))
864 fprintf(stderr, "IMAP error: unexpected command continuation request\n");
867 if (socket_write(&imap->buf.sock, "\r\n", 2) != 2)
870 imap->literal_pending = 0;
875 for (pcmdp = &imap->in_progress; (cmdp = *pcmdp); pcmdp = &cmdp->next)
876 if (cmdp->tag == tag)
878 fprintf(stderr, "IMAP error: unexpected tag %s\n", arg);
881 if (!(*pcmdp = cmdp->next))
882 imap->in_progress_append = pcmdp;
883 imap->num_in_progress--;
884 if (cmdp->cb.cont || cmdp->cb.data)
885 imap->literal_pending = 0;
886 arg = next_arg(&cmd);
887 if (!strcmp("OK", arg))
890 if (!strcmp("NO", arg)) {
891 if (cmdp->cb.create && cmd && (cmdp->cb.trycreate || !memcmp(cmd, "[TRYCREATE]", 11))) { /* SELECT, APPEND or UID COPY */
892 p = strchr(cmdp->cmd, '"');
893 if (!issue_imap_cmd(ctx, NULL, "CREATE \"%.*s\"", (int)(strchr(p + 1, '"') - p + 1), p)) {
897 /* not waiting here violates the spec, but a server that does not
898 grok this nonetheless violates it too. */
900 if (!(ncmdp = issue_imap_cmd(ctx, &cmdp->cb, "%s", cmdp->cmd))) {
907 return 0; /* ignored */
913 } else /*if (!strcmp("BAD", arg))*/
915 fprintf(stderr, "IMAP command '%s' returned response (%s) - %s\n",
916 memcmp(cmdp->cmd, "LOGIN", 5) ?
917 cmdp->cmd : "LOGIN <user> <pass>",
918 arg, cmd ? cmd : "");
920 if ((resp2 = parse_response_code(ctx, &cmdp->cb, cmd)) > resp)
924 cmdp->cb.done(ctx, cmdp, resp);
928 if (!tcmd || tcmd == cmdp)
935 static void imap_close_server(struct imap_store *ictx)
937 struct imap *imap = ictx->imap;
939 if (imap->buf.sock.fd[0] != -1) {
940 imap_exec(ictx, NULL, "LOGOUT");
941 socket_shutdown(&imap->buf.sock);
943 free_list(imap->ns_personal);
944 free_list(imap->ns_other);
945 free_list(imap->ns_shared);
949 static void imap_close_store(struct store *ctx)
951 imap_close_server((struct imap_store *)ctx);
952 free_generic_messages(ctx->msgs);
959 * hexchar() and cram() functions are based on the code from the isync
960 * project (http://isync.sf.net/).
962 static char hexchar(unsigned int b)
964 return b < 10 ? '0' + b : 'a' + (b - 10);
967 #define ENCODED_SIZE(n) (4*((n+2)/3))
968 static char *cram(const char *challenge_64, const char *user, const char *pass)
970 int i, resp_len, encoded_len, decoded_len;
972 unsigned char hash[16];
974 char *response, *response_64, *challenge;
977 * length of challenge_64 (i.e. base-64 encoded string) is a good
978 * enough upper bound for challenge (decoded result).
980 encoded_len = strlen(challenge_64);
981 challenge = xmalloc(encoded_len);
982 decoded_len = EVP_DecodeBlock((unsigned char *)challenge,
983 (unsigned char *)challenge_64, encoded_len);
985 die("invalid challenge %s", challenge_64);
986 HMAC_Init(&hmac, (unsigned char *)pass, strlen(pass), EVP_md5());
987 HMAC_Update(&hmac, (unsigned char *)challenge, decoded_len);
988 HMAC_Final(&hmac, hash, NULL);
989 HMAC_CTX_cleanup(&hmac);
992 for (i = 0; i < 16; i++) {
993 hex[2 * i] = hexchar((hash[i] >> 4) & 0xf);
994 hex[2 * i + 1] = hexchar(hash[i] & 0xf);
997 /* response: "<user> <digest in hex>" */
998 resp_len = strlen(user) + 1 + strlen(hex) + 1;
999 response = xmalloc(resp_len);
1000 sprintf(response, "%s %s", user, hex);
1002 response_64 = xmalloc(ENCODED_SIZE(resp_len) + 1);
1003 encoded_len = EVP_EncodeBlock((unsigned char *)response_64,
1004 (unsigned char *)response, resp_len);
1005 if (encoded_len < 0)
1006 die("EVP_EncodeBlock error");
1007 response_64[encoded_len] = '\0';
1008 return (char *)response_64;
1013 static char *cram(const char *challenge_64, const char *user, const char *pass)
1015 die("If you want to use CRAM-MD5 authenticate method, "
1016 "you have to build git-imap-send with OpenSSL library.");
1021 static int auth_cram_md5(struct imap_store *ctx, struct imap_cmd *cmd, const char *prompt)
1026 response = cram(prompt, server.user, server.pass);
1028 ret = socket_write(&ctx->imap->buf.sock, response, strlen(response));
1029 if (ret != strlen(response))
1030 return error("IMAP error: sending response failed\n");
1037 static struct store *imap_open_store(struct imap_server_conf *srvc)
1039 struct imap_store *ctx;
1042 int s = -1, preauth;
1044 ctx = xcalloc(sizeof(*ctx), 1);
1046 ctx->imap = imap = xcalloc(sizeof(*imap), 1);
1047 imap->buf.sock.fd[0] = imap->buf.sock.fd[1] = -1;
1048 imap->in_progress_append = &imap->in_progress;
1050 /* open connection to IMAP server */
1053 const char *argv[] = { srvc->tunnel, NULL };
1054 struct child_process tunnel = {NULL};
1056 imap_info("Starting tunnel '%s'... ", srvc->tunnel);
1059 tunnel.use_shell = 1;
1062 if (start_command(&tunnel))
1063 die("cannot start proxy %s", argv[0]);
1065 imap->buf.sock.fd[0] = tunnel.out;
1066 imap->buf.sock.fd[1] = tunnel.in;
1071 struct addrinfo hints, *ai0, *ai;
1075 snprintf(portstr, sizeof(portstr), "%d", srvc->port);
1077 memset(&hints, 0, sizeof(hints));
1078 hints.ai_socktype = SOCK_STREAM;
1079 hints.ai_protocol = IPPROTO_TCP;
1081 imap_info("Resolving %s... ", srvc->host);
1082 gai = getaddrinfo(srvc->host, portstr, &hints, &ai);
1084 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai));
1089 for (ai0 = ai; ai; ai = ai->ai_next) {
1090 char addr[NI_MAXHOST];
1092 s = socket(ai->ai_family, ai->ai_socktype,
1097 getnameinfo(ai->ai_addr, ai->ai_addrlen, addr,
1098 sizeof(addr), NULL, 0, NI_NUMERICHOST);
1099 imap_info("Connecting to [%s]:%s... ", addr, portstr);
1101 if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0) {
1113 struct sockaddr_in addr;
1115 memset(&addr, 0, sizeof(addr));
1116 addr.sin_port = htons(srvc->port);
1117 addr.sin_family = AF_INET;
1119 imap_info("Resolving %s... ", srvc->host);
1120 he = gethostbyname(srvc->host);
1122 perror("gethostbyname");
1127 addr.sin_addr.s_addr = *((int *) he->h_addr_list[0]);
1129 s = socket(PF_INET, SOCK_STREAM, 0);
1131 imap_info("Connecting to %s:%hu... ", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
1132 if (connect(s, (struct sockaddr *)&addr, sizeof(addr))) {
1139 fputs("Error: unable to connect to server.\n", stderr);
1143 imap->buf.sock.fd[0] = s;
1144 imap->buf.sock.fd[1] = dup(s);
1146 if (srvc->use_ssl &&
1147 ssl_socket_connect(&imap->buf.sock, 0, srvc->ssl_verify)) {
1154 /* read the greeting string */
1155 if (buffer_gets(&imap->buf, &rsp)) {
1156 fprintf(stderr, "IMAP error: no greeting response\n");
1159 arg = next_arg(&rsp);
1160 if (!arg || *arg != '*' || (arg = next_arg(&rsp)) == NULL) {
1161 fprintf(stderr, "IMAP error: invalid greeting response\n");
1165 if (!strcmp("PREAUTH", arg))
1167 else if (strcmp("OK", arg) != 0) {
1168 fprintf(stderr, "IMAP error: unknown greeting response\n");
1171 parse_response_code(ctx, NULL, rsp);
1172 if (!imap->caps && imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1177 if (!srvc->use_ssl && CAP(STARTTLS)) {
1178 if (imap_exec(ctx, NULL, "STARTTLS") != RESP_OK)
1180 if (ssl_socket_connect(&imap->buf.sock, 1,
1183 /* capabilities may have changed, so get the new capabilities */
1184 if (imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1188 imap_info("Logging in...\n");
1190 fprintf(stderr, "Skipping server %s, no user\n", srvc->host);
1195 sprintf(prompt, "Password (%s@%s): ", srvc->user, srvc->host);
1196 arg = git_getpass(prompt);
1202 fprintf(stderr, "Skipping account %s@%s, no password\n", srvc->user, srvc->host);
1206 * getpass() returns a pointer to a static buffer. make a copy
1207 * for long term storage.
1209 srvc->pass = xstrdup(arg);
1212 fprintf(stderr, "Skipping account %s@%s, server forbids LOGIN\n", srvc->user, srvc->host);
1216 if (srvc->auth_method) {
1217 struct imap_cmd_cb cb;
1219 if (!strcmp(srvc->auth_method, "CRAM-MD5")) {
1220 if (!CAP(AUTH_CRAM_MD5)) {
1221 fprintf(stderr, "You specified"
1222 "CRAM-MD5 as authentication method, "
1223 "but %s doesn't support it.\n", srvc->host);
1228 memset(&cb, 0, sizeof(cb));
1229 cb.cont = auth_cram_md5;
1230 if (imap_exec(ctx, &cb, "AUTHENTICATE CRAM-MD5") != RESP_OK) {
1231 fprintf(stderr, "IMAP error: AUTHENTICATE CRAM-MD5 failed\n");
1235 fprintf(stderr, "Unknown authentication method:%s\n", srvc->host);
1239 if (!imap->buf.sock.ssl)
1240 imap_warn("*** IMAP Warning *** Password is being "
1241 "sent in the clear\n");
1242 if (imap_exec(ctx, NULL, "LOGIN \"%s\" \"%s\"", srvc->user, srvc->pass) != RESP_OK) {
1243 fprintf(stderr, "IMAP error: LOGIN failed\n");
1251 return (struct store *)ctx;
1254 imap_close_store(&ctx->gen);
1258 static int imap_make_flags(int flags, char *buf)
1263 for (i = d = 0; i < ARRAY_SIZE(Flags); i++)
1264 if (flags & (1 << i)) {
1267 for (s = Flags[i]; *s; s++)
1275 static void lf_to_crlf(struct msg_data *msg)
1278 int i, j, lfnum = 0;
1280 if (msg->data[0] == '\n')
1282 for (i = 1; i < msg->len; i++) {
1283 if (msg->data[i - 1] != '\r' && msg->data[i] == '\n')
1287 new = xmalloc(msg->len + lfnum);
1288 if (msg->data[0] == '\n') {
1294 new[0] = msg->data[0];
1298 for ( ; i < msg->len; i++) {
1299 if (msg->data[i] != '\n') {
1300 new[j++] = msg->data[i];
1303 if (msg->data[i - 1] != '\r')
1305 /* otherwise it already had CR before */
1313 static int imap_store_msg(struct store *gctx, struct msg_data *data)
1315 struct imap_store *ctx = (struct imap_store *)gctx;
1316 struct imap *imap = ctx->imap;
1317 struct imap_cmd_cb cb;
1318 const char *prefix, *box;
1323 memset(&cb, 0, sizeof(cb));
1325 cb.dlen = data->len;
1326 cb.data = xmalloc(cb.dlen);
1327 memcpy(cb.data, data->data, data->len);
1331 d = imap_make_flags(data->flags, flagstr);
1337 prefix = !strcmp(box, "INBOX") ? "" : ctx->prefix;
1339 ret = imap_exec_m(ctx, &cb, "APPEND \"%s%s\" %s", prefix, box, flagstr);
1340 imap->caps = imap->rcaps;
1348 static void encode_html_chars(struct strbuf *p)
1351 for (i = 0; i < p->len; i++) {
1352 if (p->buf[i] == '&')
1353 strbuf_splice(p, i, 1, "&", 5);
1354 if (p->buf[i] == '<')
1355 strbuf_splice(p, i, 1, "<", 4);
1356 if (p->buf[i] == '>')
1357 strbuf_splice(p, i, 1, ">", 4);
1358 if (p->buf[i] == '"')
1359 strbuf_splice(p, i, 1, """, 6);
1362 static void wrap_in_html(struct msg_data *msg)
1364 struct strbuf buf = STRBUF_INIT;
1365 struct strbuf **lines;
1367 static char *content_type = "Content-Type: text/html;\n";
1368 static char *pre_open = "<pre>\n";
1369 static char *pre_close = "</pre>\n";
1370 int added_header = 0;
1372 strbuf_attach(&buf, msg->data, msg->len, msg->len);
1373 lines = strbuf_split(&buf, '\n');
1374 strbuf_release(&buf);
1375 for (p = lines; *p; p++) {
1376 if (! added_header) {
1377 if ((*p)->len == 1 && *((*p)->buf) == '\n') {
1378 strbuf_addstr(&buf, content_type);
1379 strbuf_addbuf(&buf, *p);
1380 strbuf_addstr(&buf, pre_open);
1386 encode_html_chars(*p);
1387 strbuf_addbuf(&buf, *p);
1389 strbuf_addstr(&buf, pre_close);
1390 strbuf_list_free(lines);
1392 msg->data = strbuf_detach(&buf, NULL);
1395 #define CHUNKSIZE 0x1000
1397 static int read_message(FILE *f, struct msg_data *msg)
1399 struct strbuf buf = STRBUF_INIT;
1401 memset(msg, 0, sizeof(*msg));
1404 if (strbuf_fread(&buf, CHUNKSIZE, f) <= 0)
1409 msg->data = strbuf_detach(&buf, NULL);
1413 static int count_messages(struct msg_data *msg)
1416 char *p = msg->data;
1419 if (!prefixcmp(p, "From ")) {
1420 p = strstr(p+5, "\nFrom: ");
1422 p = strstr(p+7, "\nDate: ");
1424 p = strstr(p+7, "\nSubject: ");
1429 p = strstr(p+5, "\nFrom ");
1437 static int split_msg(struct msg_data *all_msgs, struct msg_data *msg, int *ofs)
1441 memset(msg, 0, sizeof *msg);
1442 if (*ofs >= all_msgs->len)
1445 data = &all_msgs->data[*ofs];
1446 msg->len = all_msgs->len - *ofs;
1448 if (msg->len < 5 || prefixcmp(data, "From "))
1451 p = strchr(data, '\n');
1459 p = strstr(data, "\nFrom ");
1461 msg->len = &p[1] - data;
1463 msg->data = xmemdupz(data, msg->len);
1468 static char *imap_folder;
1470 static int git_imap_config(const char *key, const char *val, void *cb)
1472 char imap_key[] = "imap.";
1474 if (strncmp(key, imap_key, sizeof imap_key - 1))
1477 key += sizeof imap_key - 1;
1479 /* check booleans first, and barf on others */
1480 if (!strcmp("sslverify", key))
1481 server.ssl_verify = git_config_bool(key, val);
1482 else if (!strcmp("preformattedhtml", key))
1483 server.use_html = git_config_bool(key, val);
1485 return config_error_nonbool(key);
1487 if (!strcmp("folder", key)) {
1488 imap_folder = xstrdup(val);
1489 } else if (!strcmp("host", key)) {
1490 if (!prefixcmp(val, "imap:"))
1492 else if (!prefixcmp(val, "imaps:")) {
1496 if (!prefixcmp(val, "//"))
1498 server.host = xstrdup(val);
1499 } else if (!strcmp("user", key))
1500 server.user = xstrdup(val);
1501 else if (!strcmp("pass", key))
1502 server.pass = xstrdup(val);
1503 else if (!strcmp("port", key))
1504 server.port = git_config_int(key, val);
1505 else if (!strcmp("tunnel", key))
1506 server.tunnel = xstrdup(val);
1507 else if (!strcmp("authmethod", key))
1508 server.auth_method = xstrdup(val);
1513 int main(int argc, char **argv)
1515 struct msg_data all_msgs, msg;
1516 struct store *ctx = NULL;
1522 git_extract_argv0_path(argv[0]);
1525 usage(imap_send_usage);
1527 setup_git_directory_gently(&nongit_ok);
1528 git_config(git_imap_config, NULL);
1531 server.port = server.use_ssl ? 993 : 143;
1534 fprintf(stderr, "no imap store specified\n");
1538 if (!server.tunnel) {
1539 fprintf(stderr, "no imap host specified\n");
1542 server.host = "tunnel";
1545 /* read the messages */
1546 if (!read_message(stdin, &all_msgs)) {
1547 fprintf(stderr, "nothing to send\n");
1551 total = count_messages(&all_msgs);
1553 fprintf(stderr, "no messages to send\n");
1557 /* write it to the imap server */
1558 ctx = imap_open_store(&server);
1560 fprintf(stderr, "failed to open store\n");
1564 fprintf(stderr, "sending %d message%s\n", total, (total != 1) ? "s" : "");
1565 ctx->name = imap_folder;
1567 unsigned percent = n * 100 / total;
1568 fprintf(stderr, "%4u%% (%d/%d) done\r", percent, n, total);
1569 if (!split_msg(&all_msgs, &msg, &ofs))
1571 if (server.use_html)
1573 r = imap_store_msg(ctx, &msg);
1578 fprintf(stderr, "\n");
1580 imap_close_store(ctx);