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>
38 const char *path; /* should this be here? its interpretation is driver-specific */
41 unsigned max_size; /* off_t is overkill */
42 unsigned trash_remote_new:1, trash_only_new:1;
45 /* For message->status */
46 #define M_RECENT (1<<0) /* unsyncable flag; maildir_* depend on this being 1<<0 */
47 #define M_DEAD (1<<1) /* expunged */
48 #define M_FLAGS (1<<2) /* flags fetched */
52 size_t size; /* zero implies "not fetched" */
54 unsigned char flags, status;
58 struct store_conf *conf; /* foreign */
60 /* currently open mailbox */
61 const char *name; /* foreign! maybe preset? */
63 struct message *msgs; /* own */
65 unsigned char opts; /* maybe preset? */
66 /* note that the following do _not_ reflect stats from msgs, but mailbox totals */
67 int count; /* # of messages */
68 int recent; /* # of recent messages - don't trust this beyond the initial read */
72 /* NUL-terminated data: */
75 /* length of data (not including NUL): */
81 static const char imap_send_usage[] = "git imap-send < <mbox>";
85 #define DRV_MSG_BAD -1
86 #define DRV_BOX_BAD -2
87 #define DRV_STORE_BAD -3
89 static int Verbose, Quiet;
91 __attribute__((format (printf, 1, 2)))
92 static void imap_info(const char *, ...);
93 __attribute__((format (printf, 1, 2)))
94 static void imap_warn(const char *, ...);
96 static char *next_arg(char **);
98 static void free_generic_messages(struct message *);
100 __attribute__((format (printf, 3, 4)))
101 static int nfsnprintf(char *buf, int blen, const char *fmt, ...);
103 static int nfvasprintf(char **strp, const char *fmt, va_list ap)
108 len = vsnprintf(tmp, sizeof(tmp), fmt, ap);
110 die("Fatal: Out of memory");
111 if (len >= sizeof(tmp))
112 die("imap command overflow!");
113 *strp = xmemdupz(tmp, len);
117 struct imap_server_conf {
130 static struct imap_server_conf server = {
140 NULL, /* auth_method */
143 struct imap_store_conf {
144 struct store_conf gen;
145 struct imap_server_conf *server;
148 #define NIL (void *)0x1
149 #define LIST (void *)0x2
152 struct imap_list *next, *child;
163 struct imap_socket sock;
172 int uidnext; /* from SELECT responses */
173 struct imap_list *ns_personal, *ns_other, *ns_shared; /* NAMESPACE info */
174 unsigned caps, rcaps; /* CAPABILITY results */
176 int nexttag, num_in_progress, literal_pending;
177 struct imap_cmd *in_progress, **in_progress_append;
178 struct imap_buffer buf; /* this is BIG, so put it last */
186 unsigned /*currentnc:1,*/ trashnc:1;
190 int (*cont)(struct imap_store *ctx, struct imap_cmd *cmd, const char *prompt);
191 void (*done)(struct imap_store *ctx, struct imap_cmd *cmd, int response);
196 unsigned create:1, trycreate:1;
200 struct imap_cmd *next;
201 struct imap_cmd_cb cb;
206 #define CAP(cap) (imap->caps & (1 << (cap)))
217 static const char *cap_list[] = {
230 static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd);
233 static const char *Flags[] = {
242 static void ssl_socket_perror(const char *func)
244 fprintf(stderr, "%s: %s\n", func, ERR_error_string(ERR_get_error(), NULL));
248 static void socket_perror(const char *func, struct imap_socket *sock, int ret)
252 int sslerr = SSL_get_error(sock->ssl, ret);
256 case SSL_ERROR_SYSCALL:
257 perror("SSL_connect");
260 ssl_socket_perror("SSL_connect");
269 fprintf(stderr, "%s: unexpected EOF\n", func);
273 static int ssl_socket_connect(struct imap_socket *sock, int use_tls_only, int verify)
276 fprintf(stderr, "SSL requested but SSL support not compiled in\n");
279 #if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
280 const SSL_METHOD *meth;
288 SSL_load_error_strings();
291 meth = TLSv1_method();
293 meth = SSLv23_method();
296 ssl_socket_perror("SSLv23_method");
300 ctx = SSL_CTX_new(meth);
303 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
305 if (!SSL_CTX_set_default_verify_paths(ctx)) {
306 ssl_socket_perror("SSL_CTX_set_default_verify_paths");
309 sock->ssl = SSL_new(ctx);
311 ssl_socket_perror("SSL_new");
314 if (!SSL_set_rfd(sock->ssl, sock->fd[0])) {
315 ssl_socket_perror("SSL_set_rfd");
318 if (!SSL_set_wfd(sock->ssl, sock->fd[1])) {
319 ssl_socket_perror("SSL_set_wfd");
323 ret = SSL_connect(sock->ssl);
325 socket_perror("SSL_connect", sock, ret);
333 static int socket_read(struct imap_socket *sock, char *buf, int len)
338 n = SSL_read(sock->ssl, buf, len);
341 n = xread(sock->fd[0], buf, len);
343 socket_perror("read", sock, n);
346 sock->fd[0] = sock->fd[1] = -1;
351 static int socket_write(struct imap_socket *sock, const char *buf, int len)
356 n = SSL_write(sock->ssl, buf, len);
359 n = write_in_full(sock->fd[1], buf, len);
361 socket_perror("write", sock, n);
364 sock->fd[0] = sock->fd[1] = -1;
369 static void socket_shutdown(struct imap_socket *sock)
373 SSL_shutdown(sock->ssl);
381 /* simple line buffering */
382 static int buffer_gets(struct imap_buffer *b, char **s)
385 int start = b->offset;
390 /* make sure we have enough data to read the \r\n sequence */
391 if (b->offset + 1 >= b->bytes) {
393 /* shift down used bytes */
396 assert(start <= b->bytes);
397 n = b->bytes - start;
400 memmove(b->buf, b->buf + start, n);
406 n = socket_read(&b->sock, b->buf + b->bytes,
407 sizeof(b->buf) - b->bytes);
415 if (b->buf[b->offset] == '\r') {
416 assert(b->offset + 1 < b->bytes);
417 if (b->buf[b->offset + 1] == '\n') {
418 b->buf[b->offset] = 0; /* terminate the string */
419 b->offset += 2; /* next line */
431 static void imap_info(const char *msg, ...)
443 static void imap_warn(const char *msg, ...)
449 vfprintf(stderr, msg, va);
454 static char *next_arg(char **s)
460 while (isspace((unsigned char) **s))
469 *s = strchr(*s, '"');
472 while (**s && !isspace((unsigned char) **s))
484 static void free_generic_messages(struct message *msgs)
486 struct message *tmsg;
488 for (; msgs; msgs = tmsg) {
494 static int nfsnprintf(char *buf, int blen, const char *fmt, ...)
500 if (blen <= 0 || (unsigned)(ret = vsnprintf(buf, blen, fmt, va)) >= (unsigned)blen)
501 die("Fatal: buffer too small. Please report a bug.");
506 static struct imap_cmd *v_issue_imap_cmd(struct imap_store *ctx,
507 struct imap_cmd_cb *cb,
508 const char *fmt, va_list ap)
510 struct imap *imap = ctx->imap;
511 struct imap_cmd *cmd;
515 cmd = xmalloc(sizeof(struct imap_cmd));
516 nfvasprintf(&cmd->cmd, fmt, ap);
517 cmd->tag = ++imap->nexttag;
522 memset(&cmd->cb, 0, sizeof(cmd->cb));
524 while (imap->literal_pending)
525 get_cmd_result(ctx, NULL);
528 bufl = nfsnprintf(buf, sizeof(buf), "%d %s\r\n", cmd->tag, cmd->cmd);
530 bufl = nfsnprintf(buf, sizeof(buf), "%d %s{%d%s}\r\n",
531 cmd->tag, cmd->cmd, cmd->cb.dlen,
532 CAP(LITERALPLUS) ? "+" : "");
535 if (imap->num_in_progress)
536 printf("(%d in progress) ", imap->num_in_progress);
537 if (memcmp(cmd->cmd, "LOGIN", 5))
538 printf(">>> %s", buf);
540 printf(">>> %d LOGIN <user> <pass>\n", cmd->tag);
542 if (socket_write(&imap->buf.sock, buf, bufl) != bufl) {
550 if (CAP(LITERALPLUS)) {
551 n = socket_write(&imap->buf.sock, cmd->cb.data, cmd->cb.dlen);
553 if (n != cmd->cb.dlen ||
554 socket_write(&imap->buf.sock, "\r\n", 2) != 2) {
561 imap->literal_pending = 1;
562 } else if (cmd->cb.cont)
563 imap->literal_pending = 1;
565 *imap->in_progress_append = cmd;
566 imap->in_progress_append = &cmd->next;
567 imap->num_in_progress++;
571 __attribute__((format (printf, 3, 4)))
572 static struct imap_cmd *issue_imap_cmd(struct imap_store *ctx,
573 struct imap_cmd_cb *cb,
574 const char *fmt, ...)
576 struct imap_cmd *ret;
580 ret = v_issue_imap_cmd(ctx, cb, fmt, ap);
585 __attribute__((format (printf, 3, 4)))
586 static int imap_exec(struct imap_store *ctx, struct imap_cmd_cb *cb,
587 const char *fmt, ...)
590 struct imap_cmd *cmdp;
593 cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
598 return get_cmd_result(ctx, cmdp);
601 __attribute__((format (printf, 3, 4)))
602 static int imap_exec_m(struct imap_store *ctx, struct imap_cmd_cb *cb,
603 const char *fmt, ...)
606 struct imap_cmd *cmdp;
609 cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
612 return DRV_STORE_BAD;
614 switch (get_cmd_result(ctx, cmdp)) {
615 case RESP_BAD: return DRV_STORE_BAD;
616 case RESP_NO: return DRV_MSG_BAD;
617 default: return DRV_OK;
621 static int is_atom(struct imap_list *list)
623 return list && list->val && list->val != NIL && list->val != LIST;
626 static int is_list(struct imap_list *list)
628 return list && list->val == LIST;
631 static void free_list(struct imap_list *list)
633 struct imap_list *tmp;
635 for (; list; list = tmp) {
638 free_list(list->child);
639 else if (is_atom(list))
645 static int parse_imap_list_l(struct imap *imap, char **sp, struct imap_list **curp, int level)
647 struct imap_list *cur;
652 while (isspace((unsigned char)*s))
654 if (level && *s == ')') {
658 *curp = cur = xmalloc(sizeof(*cur));
660 cur->val = NULL; /* for clean bail */
665 if (parse_imap_list_l(imap, &s, &cur->child, level + 1))
667 } else if (imap && *s == '{') {
669 bytes = cur->len = strtol(s + 1, &s, 10);
673 s = cur->val = xmalloc(cur->len);
675 /* dump whats left over in the input buffer */
676 n = imap->buf.bytes - imap->buf.offset;
679 /* the entire message fit in the buffer */
682 memcpy(s, imap->buf.buf + imap->buf.offset, n);
686 /* mark that we used part of the buffer */
687 imap->buf.offset += n;
689 /* now read the rest of the message */
691 if ((n = socket_read(&imap->buf.sock, s, bytes)) <= 0)
697 if (buffer_gets(&imap->buf, &s))
699 } else if (*s == '"') {
703 for (; *s != '"'; s++)
708 cur->val = xmemdupz(p, cur->len);
712 for (; *s && !isspace((unsigned char)*s); s++)
713 if (level && *s == ')')
716 if (cur->len == 3 && !memcmp("NIL", p, 3))
719 cur->val = xmemdupz(p, cur->len);
736 static struct imap_list *parse_imap_list(struct imap *imap, char **sp)
738 struct imap_list *head;
740 if (!parse_imap_list_l(imap, sp, &head, 0))
746 static struct imap_list *parse_list(char **sp)
748 return parse_imap_list(NULL, sp);
751 static void parse_capability(struct imap *imap, char *cmd)
756 imap->caps = 0x80000000;
757 while ((arg = next_arg(&cmd)))
758 for (i = 0; i < ARRAY_SIZE(cap_list); i++)
759 if (!strcmp(cap_list[i], arg))
760 imap->caps |= 1 << i;
761 imap->rcaps = imap->caps;
764 static int parse_response_code(struct imap_store *ctx, struct imap_cmd_cb *cb,
767 struct imap *imap = ctx->imap;
771 return RESP_OK; /* no response code */
773 if (!(p = strchr(s, ']'))) {
774 fprintf(stderr, "IMAP error: malformed response code\n");
779 if (!strcmp("UIDVALIDITY", arg)) {
780 if (!(arg = next_arg(&s)) || !(ctx->gen.uidvalidity = atoi(arg))) {
781 fprintf(stderr, "IMAP error: malformed UIDVALIDITY status\n");
784 } else if (!strcmp("UIDNEXT", arg)) {
785 if (!(arg = next_arg(&s)) || !(imap->uidnext = atoi(arg))) {
786 fprintf(stderr, "IMAP error: malformed NEXTUID status\n");
789 } else if (!strcmp("CAPABILITY", arg)) {
790 parse_capability(imap, s);
791 } else if (!strcmp("ALERT", arg)) {
792 /* RFC2060 says that these messages MUST be displayed
795 for (; isspace((unsigned char)*p); p++);
796 fprintf(stderr, "*** IMAP ALERT *** %s\n", p);
797 } else if (cb && cb->ctx && !strcmp("APPENDUID", arg)) {
798 if (!(arg = next_arg(&s)) || !(ctx->gen.uidvalidity = atoi(arg)) ||
799 !(arg = next_arg(&s)) || !(*(int *)cb->ctx = atoi(arg))) {
800 fprintf(stderr, "IMAP error: malformed APPENDUID status\n");
807 static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd)
809 struct imap *imap = ctx->imap;
810 struct imap_cmd *cmdp, **pcmdp, *ncmdp;
811 char *cmd, *arg, *arg1, *p;
812 int n, resp, resp2, tag;
815 if (buffer_gets(&imap->buf, &cmd))
818 arg = next_arg(&cmd);
820 arg = next_arg(&cmd);
822 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
826 if (!strcmp("NAMESPACE", arg)) {
827 imap->ns_personal = parse_list(&cmd);
828 imap->ns_other = parse_list(&cmd);
829 imap->ns_shared = parse_list(&cmd);
830 } else if (!strcmp("OK", arg) || !strcmp("BAD", arg) ||
831 !strcmp("NO", arg) || !strcmp("BYE", arg)) {
832 if ((resp = parse_response_code(ctx, NULL, cmd)) != RESP_OK)
834 } else if (!strcmp("CAPABILITY", arg))
835 parse_capability(imap, cmd);
836 else if ((arg1 = next_arg(&cmd))) {
837 if (!strcmp("EXISTS", arg1))
838 ctx->gen.count = atoi(arg);
839 else if (!strcmp("RECENT", arg1))
840 ctx->gen.recent = atoi(arg);
842 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
845 } else if (!imap->in_progress) {
846 fprintf(stderr, "IMAP error: unexpected reply: %s %s\n", arg, cmd ? cmd : "");
848 } else if (*arg == '+') {
849 /* This can happen only with the last command underway, as
850 it enforces a round-trip. */
851 cmdp = (struct imap_cmd *)((char *)imap->in_progress_append -
852 offsetof(struct imap_cmd, next));
854 n = socket_write(&imap->buf.sock, cmdp->cb.data, cmdp->cb.dlen);
856 cmdp->cb.data = NULL;
857 if (n != (int)cmdp->cb.dlen)
859 } else if (cmdp->cb.cont) {
860 if (cmdp->cb.cont(ctx, cmdp, cmd))
863 fprintf(stderr, "IMAP error: unexpected command continuation request\n");
866 if (socket_write(&imap->buf.sock, "\r\n", 2) != 2)
869 imap->literal_pending = 0;
874 for (pcmdp = &imap->in_progress; (cmdp = *pcmdp); pcmdp = &cmdp->next)
875 if (cmdp->tag == tag)
877 fprintf(stderr, "IMAP error: unexpected tag %s\n", arg);
880 if (!(*pcmdp = cmdp->next))
881 imap->in_progress_append = pcmdp;
882 imap->num_in_progress--;
883 if (cmdp->cb.cont || cmdp->cb.data)
884 imap->literal_pending = 0;
885 arg = next_arg(&cmd);
886 if (!strcmp("OK", arg))
889 if (!strcmp("NO", arg)) {
890 if (cmdp->cb.create && cmd && (cmdp->cb.trycreate || !memcmp(cmd, "[TRYCREATE]", 11))) { /* SELECT, APPEND or UID COPY */
891 p = strchr(cmdp->cmd, '"');
892 if (!issue_imap_cmd(ctx, NULL, "CREATE \"%.*s\"", (int)(strchr(p + 1, '"') - p + 1), p)) {
896 /* not waiting here violates the spec, but a server that does not
897 grok this nonetheless violates it too. */
899 if (!(ncmdp = issue_imap_cmd(ctx, &cmdp->cb, "%s", cmdp->cmd))) {
906 return 0; /* ignored */
912 } else /*if (!strcmp("BAD", arg))*/
914 fprintf(stderr, "IMAP command '%s' returned response (%s) - %s\n",
915 memcmp(cmdp->cmd, "LOGIN", 5) ?
916 cmdp->cmd : "LOGIN <user> <pass>",
917 arg, cmd ? cmd : "");
919 if ((resp2 = parse_response_code(ctx, &cmdp->cb, cmd)) > resp)
923 cmdp->cb.done(ctx, cmdp, resp);
927 if (!tcmd || tcmd == cmdp)
934 static void imap_close_server(struct imap_store *ictx)
936 struct imap *imap = ictx->imap;
938 if (imap->buf.sock.fd[0] != -1) {
939 imap_exec(ictx, NULL, "LOGOUT");
940 socket_shutdown(&imap->buf.sock);
942 free_list(imap->ns_personal);
943 free_list(imap->ns_other);
944 free_list(imap->ns_shared);
948 static void imap_close_store(struct store *ctx)
950 imap_close_server((struct imap_store *)ctx);
951 free_generic_messages(ctx->msgs);
958 * hexchar() and cram() functions are based on the code from the isync
959 * project (http://isync.sf.net/).
961 static char hexchar(unsigned int b)
963 return b < 10 ? '0' + b : 'a' + (b - 10);
966 #define ENCODED_SIZE(n) (4*((n+2)/3))
967 static char *cram(const char *challenge_64, const char *user, const char *pass)
969 int i, resp_len, encoded_len, decoded_len;
971 unsigned char hash[16];
973 char *response, *response_64, *challenge;
976 * length of challenge_64 (i.e. base-64 encoded string) is a good
977 * enough upper bound for challenge (decoded result).
979 encoded_len = strlen(challenge_64);
980 challenge = xmalloc(encoded_len);
981 decoded_len = EVP_DecodeBlock((unsigned char *)challenge,
982 (unsigned char *)challenge_64, encoded_len);
984 die("invalid challenge %s", challenge_64);
985 HMAC_Init(&hmac, (unsigned char *)pass, strlen(pass), EVP_md5());
986 HMAC_Update(&hmac, (unsigned char *)challenge, decoded_len);
987 HMAC_Final(&hmac, hash, NULL);
988 HMAC_CTX_cleanup(&hmac);
991 for (i = 0; i < 16; i++) {
992 hex[2 * i] = hexchar((hash[i] >> 4) & 0xf);
993 hex[2 * i + 1] = hexchar(hash[i] & 0xf);
996 /* response: "<user> <digest in hex>" */
997 resp_len = strlen(user) + 1 + strlen(hex) + 1;
998 response = xmalloc(resp_len);
999 sprintf(response, "%s %s", user, hex);
1001 response_64 = xmalloc(ENCODED_SIZE(resp_len) + 1);
1002 encoded_len = EVP_EncodeBlock((unsigned char *)response_64,
1003 (unsigned char *)response, resp_len);
1004 if (encoded_len < 0)
1005 die("EVP_EncodeBlock error");
1006 response_64[encoded_len] = '\0';
1007 return (char *)response_64;
1012 static char *cram(const char *challenge_64, const char *user, const char *pass)
1014 die("If you want to use CRAM-MD5 authenticate method, "
1015 "you have to build git-imap-send with OpenSSL library.");
1020 static int auth_cram_md5(struct imap_store *ctx, struct imap_cmd *cmd, const char *prompt)
1025 response = cram(prompt, server.user, server.pass);
1027 ret = socket_write(&ctx->imap->buf.sock, response, strlen(response));
1028 if (ret != strlen(response))
1029 return error("IMAP error: sending response failed");
1036 static struct store *imap_open_store(struct imap_server_conf *srvc)
1038 struct imap_store *ctx;
1041 int s = -1, preauth;
1043 ctx = xcalloc(sizeof(*ctx), 1);
1045 ctx->imap = imap = xcalloc(sizeof(*imap), 1);
1046 imap->buf.sock.fd[0] = imap->buf.sock.fd[1] = -1;
1047 imap->in_progress_append = &imap->in_progress;
1049 /* open connection to IMAP server */
1052 const char *argv[] = { srvc->tunnel, NULL };
1053 struct child_process tunnel = {NULL};
1055 imap_info("Starting tunnel '%s'... ", srvc->tunnel);
1058 tunnel.use_shell = 1;
1061 if (start_command(&tunnel))
1062 die("cannot start proxy %s", argv[0]);
1064 imap->buf.sock.fd[0] = tunnel.out;
1065 imap->buf.sock.fd[1] = tunnel.in;
1070 struct addrinfo hints, *ai0, *ai;
1074 snprintf(portstr, sizeof(portstr), "%d", srvc->port);
1076 memset(&hints, 0, sizeof(hints));
1077 hints.ai_socktype = SOCK_STREAM;
1078 hints.ai_protocol = IPPROTO_TCP;
1080 imap_info("Resolving %s... ", srvc->host);
1081 gai = getaddrinfo(srvc->host, portstr, &hints, &ai);
1083 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai));
1088 for (ai0 = ai; ai; ai = ai->ai_next) {
1089 char addr[NI_MAXHOST];
1091 s = socket(ai->ai_family, ai->ai_socktype,
1096 getnameinfo(ai->ai_addr, ai->ai_addrlen, addr,
1097 sizeof(addr), NULL, 0, NI_NUMERICHOST);
1098 imap_info("Connecting to [%s]:%s... ", addr, portstr);
1100 if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0) {
1112 struct sockaddr_in addr;
1114 memset(&addr, 0, sizeof(addr));
1115 addr.sin_port = htons(srvc->port);
1116 addr.sin_family = AF_INET;
1118 imap_info("Resolving %s... ", srvc->host);
1119 he = gethostbyname(srvc->host);
1121 perror("gethostbyname");
1126 addr.sin_addr.s_addr = *((int *) he->h_addr_list[0]);
1128 s = socket(PF_INET, SOCK_STREAM, 0);
1130 imap_info("Connecting to %s:%hu... ", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
1131 if (connect(s, (struct sockaddr *)&addr, sizeof(addr))) {
1138 fputs("Error: unable to connect to server.\n", stderr);
1142 imap->buf.sock.fd[0] = s;
1143 imap->buf.sock.fd[1] = dup(s);
1145 if (srvc->use_ssl &&
1146 ssl_socket_connect(&imap->buf.sock, 0, srvc->ssl_verify)) {
1153 /* read the greeting string */
1154 if (buffer_gets(&imap->buf, &rsp)) {
1155 fprintf(stderr, "IMAP error: no greeting response\n");
1158 arg = next_arg(&rsp);
1159 if (!arg || *arg != '*' || (arg = next_arg(&rsp)) == NULL) {
1160 fprintf(stderr, "IMAP error: invalid greeting response\n");
1164 if (!strcmp("PREAUTH", arg))
1166 else if (strcmp("OK", arg) != 0) {
1167 fprintf(stderr, "IMAP error: unknown greeting response\n");
1170 parse_response_code(ctx, NULL, rsp);
1171 if (!imap->caps && imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1176 if (!srvc->use_ssl && CAP(STARTTLS)) {
1177 if (imap_exec(ctx, NULL, "STARTTLS") != RESP_OK)
1179 if (ssl_socket_connect(&imap->buf.sock, 1,
1182 /* capabilities may have changed, so get the new capabilities */
1183 if (imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1187 imap_info("Logging in...\n");
1189 fprintf(stderr, "Skipping server %s, no user\n", srvc->host);
1193 struct strbuf prompt = STRBUF_INIT;
1194 strbuf_addf(&prompt, "Password (%s@%s): ", srvc->user, srvc->host);
1195 arg = git_getpass(prompt.buf);
1196 strbuf_release(&prompt);
1198 fprintf(stderr, "Skipping account %s@%s, no password\n", srvc->user, srvc->host);
1202 * getpass() returns a pointer to a static buffer. make a copy
1203 * for long term storage.
1205 srvc->pass = xstrdup(arg);
1208 fprintf(stderr, "Skipping account %s@%s, server forbids LOGIN\n", srvc->user, srvc->host);
1212 if (srvc->auth_method) {
1213 struct imap_cmd_cb cb;
1215 if (!strcmp(srvc->auth_method, "CRAM-MD5")) {
1216 if (!CAP(AUTH_CRAM_MD5)) {
1217 fprintf(stderr, "You specified"
1218 "CRAM-MD5 as authentication method, "
1219 "but %s doesn't support it.\n", srvc->host);
1224 memset(&cb, 0, sizeof(cb));
1225 cb.cont = auth_cram_md5;
1226 if (imap_exec(ctx, &cb, "AUTHENTICATE CRAM-MD5") != RESP_OK) {
1227 fprintf(stderr, "IMAP error: AUTHENTICATE CRAM-MD5 failed\n");
1231 fprintf(stderr, "Unknown authentication method:%s\n", srvc->host);
1235 if (!imap->buf.sock.ssl)
1236 imap_warn("*** IMAP Warning *** Password is being "
1237 "sent in the clear\n");
1238 if (imap_exec(ctx, NULL, "LOGIN \"%s\" \"%s\"", srvc->user, srvc->pass) != RESP_OK) {
1239 fprintf(stderr, "IMAP error: LOGIN failed\n");
1247 return (struct store *)ctx;
1250 imap_close_store(&ctx->gen);
1254 static int imap_make_flags(int flags, char *buf)
1259 for (i = d = 0; i < ARRAY_SIZE(Flags); i++)
1260 if (flags & (1 << i)) {
1263 for (s = Flags[i]; *s; s++)
1271 static void lf_to_crlf(struct msg_data *msg)
1274 int i, j, lfnum = 0;
1276 if (msg->data[0] == '\n')
1278 for (i = 1; i < msg->len; i++) {
1279 if (msg->data[i - 1] != '\r' && msg->data[i] == '\n')
1283 new = xmalloc(msg->len + lfnum + 1);
1284 if (msg->data[0] == '\n') {
1290 new[0] = msg->data[0];
1294 for ( ; i < msg->len; i++) {
1295 if (msg->data[i] != '\n') {
1296 new[j++] = msg->data[i];
1299 if (msg->data[i - 1] != '\r')
1301 /* otherwise it already had CR before */
1310 static int imap_store_msg(struct store *gctx, struct msg_data *data)
1312 struct imap_store *ctx = (struct imap_store *)gctx;
1313 struct imap *imap = ctx->imap;
1314 struct imap_cmd_cb cb;
1315 const char *prefix, *box;
1320 memset(&cb, 0, sizeof(cb));
1322 cb.dlen = data->len;
1323 cb.data = xmalloc(cb.dlen);
1324 memcpy(cb.data, data->data, data->len);
1328 d = imap_make_flags(data->flags, flagstr);
1334 prefix = !strcmp(box, "INBOX") ? "" : ctx->prefix;
1336 ret = imap_exec_m(ctx, &cb, "APPEND \"%s%s\" %s", prefix, box, flagstr);
1337 imap->caps = imap->rcaps;
1345 static void encode_html_chars(struct strbuf *p)
1348 for (i = 0; i < p->len; i++) {
1349 if (p->buf[i] == '&')
1350 strbuf_splice(p, i, 1, "&", 5);
1351 if (p->buf[i] == '<')
1352 strbuf_splice(p, i, 1, "<", 4);
1353 if (p->buf[i] == '>')
1354 strbuf_splice(p, i, 1, ">", 4);
1355 if (p->buf[i] == '"')
1356 strbuf_splice(p, i, 1, """, 6);
1359 static void wrap_in_html(struct msg_data *msg)
1361 struct strbuf buf = STRBUF_INIT;
1362 struct strbuf **lines;
1364 static char *content_type = "Content-Type: text/html;\n";
1365 static char *pre_open = "<pre>\n";
1366 static char *pre_close = "</pre>\n";
1367 int added_header = 0;
1369 strbuf_attach(&buf, msg->data, msg->len, msg->len);
1370 lines = strbuf_split(&buf, '\n');
1371 strbuf_release(&buf);
1372 for (p = lines; *p; p++) {
1373 if (! added_header) {
1374 if ((*p)->len == 1 && *((*p)->buf) == '\n') {
1375 strbuf_addstr(&buf, content_type);
1376 strbuf_addbuf(&buf, *p);
1377 strbuf_addstr(&buf, pre_open);
1383 encode_html_chars(*p);
1384 strbuf_addbuf(&buf, *p);
1386 strbuf_addstr(&buf, pre_close);
1387 strbuf_list_free(lines);
1389 msg->data = strbuf_detach(&buf, NULL);
1392 #define CHUNKSIZE 0x1000
1394 static int read_message(FILE *f, struct strbuf *all_msgs)
1397 if (strbuf_fread(all_msgs, CHUNKSIZE, f) <= 0)
1401 return all_msgs->len;
1404 static int count_messages(struct strbuf *all_msgs)
1407 char *p = all_msgs->buf;
1410 if (!prefixcmp(p, "From ")) {
1411 p = strstr(p+5, "\nFrom: ");
1413 p = strstr(p+7, "\nDate: ");
1415 p = strstr(p+7, "\nSubject: ");
1420 p = strstr(p+5, "\nFrom ");
1428 static int split_msg(struct strbuf *all_msgs, struct msg_data *msg, int *ofs)
1432 memset(msg, 0, sizeof *msg);
1433 if (*ofs >= all_msgs->len)
1436 data = &all_msgs->buf[*ofs];
1437 msg->len = all_msgs->len - *ofs;
1439 if (msg->len < 5 || prefixcmp(data, "From "))
1442 p = strchr(data, '\n');
1450 p = strstr(data, "\nFrom ");
1452 msg->len = &p[1] - data;
1454 msg->data = xmemdupz(data, msg->len);
1459 static char *imap_folder;
1461 static int git_imap_config(const char *key, const char *val, void *cb)
1463 char imap_key[] = "imap.";
1465 if (strncmp(key, imap_key, sizeof imap_key - 1))
1468 key += sizeof imap_key - 1;
1470 /* check booleans first, and barf on others */
1471 if (!strcmp("sslverify", key))
1472 server.ssl_verify = git_config_bool(key, val);
1473 else if (!strcmp("preformattedhtml", key))
1474 server.use_html = git_config_bool(key, val);
1476 return config_error_nonbool(key);
1478 if (!strcmp("folder", key)) {
1479 imap_folder = xstrdup(val);
1480 } else if (!strcmp("host", key)) {
1481 if (!prefixcmp(val, "imap:"))
1483 else if (!prefixcmp(val, "imaps:")) {
1487 if (!prefixcmp(val, "//"))
1489 server.host = xstrdup(val);
1490 } else if (!strcmp("user", key))
1491 server.user = xstrdup(val);
1492 else if (!strcmp("pass", key))
1493 server.pass = xstrdup(val);
1494 else if (!strcmp("port", key))
1495 server.port = git_config_int(key, val);
1496 else if (!strcmp("tunnel", key))
1497 server.tunnel = xstrdup(val);
1498 else if (!strcmp("authmethod", key))
1499 server.auth_method = xstrdup(val);
1504 int main(int argc, char **argv)
1506 struct strbuf all_msgs = STRBUF_INIT;
1507 struct msg_data msg;
1508 struct store *ctx = NULL;
1514 git_extract_argv0_path(argv[0]);
1516 git_setup_gettext();
1519 usage(imap_send_usage);
1521 setup_git_directory_gently(&nongit_ok);
1522 git_config(git_imap_config, NULL);
1525 server.port = server.use_ssl ? 993 : 143;
1528 fprintf(stderr, "no imap store specified\n");
1532 if (!server.tunnel) {
1533 fprintf(stderr, "no imap host specified\n");
1536 server.host = "tunnel";
1539 /* read the messages */
1540 if (!read_message(stdin, &all_msgs)) {
1541 fprintf(stderr, "nothing to send\n");
1545 total = count_messages(&all_msgs);
1547 fprintf(stderr, "no messages to send\n");
1551 /* write it to the imap server */
1552 ctx = imap_open_store(&server);
1554 fprintf(stderr, "failed to open store\n");
1558 fprintf(stderr, "sending %d message%s\n", total, (total != 1) ? "s" : "");
1559 ctx->name = imap_folder;
1561 unsigned percent = n * 100 / total;
1562 fprintf(stderr, "%4u%% (%d/%d) done\r", percent, n, total);
1563 if (!split_msg(&all_msgs, &msg, &ofs))
1565 if (server.use_html)
1567 r = imap_store_msg(ctx, &msg);
1572 fprintf(stderr, "\n");
1574 imap_close_store(ctx);