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;
45 struct string_list *next;
50 struct channel_conf *next;
52 struct store_conf *master, *slave;
53 char *master_name, *slave_name;
55 struct string_list *patterns;
57 unsigned max_messages; /* for slave only */
61 struct group_conf *next;
63 struct string_list *channels;
66 /* For message->status */
67 #define M_RECENT (1<<0) /* unsyncable flag; maildir_* depend on this being 1<<0 */
68 #define M_DEAD (1<<1) /* expunged */
69 #define M_FLAGS (1<<2) /* flags fetched */
73 /* struct string_list *keywords; */
74 size_t size; /* zero implies "not fetched" */
76 unsigned char flags, status;
80 struct store_conf *conf; /* foreign */
82 /* currently open mailbox */
83 const char *name; /* foreign! maybe preset? */
85 struct message *msgs; /* own */
87 unsigned char opts; /* maybe preset? */
88 /* note that the following do _not_ reflect stats from msgs, but mailbox totals */
89 int count; /* # of messages */
90 int recent; /* # of recent messages - don't trust this beyond the initial read */
100 static const char imap_send_usage[] = "git imap-send < <mbox>";
104 #define DRV_MSG_BAD -1
105 #define DRV_BOX_BAD -2
106 #define DRV_STORE_BAD -3
108 static int Verbose, Quiet;
110 __attribute__((format (printf, 1, 2)))
111 static void imap_info(const char *, ...);
112 __attribute__((format (printf, 1, 2)))
113 static void imap_warn(const char *, ...);
115 static char *next_arg(char **);
117 static void free_generic_messages(struct message *);
119 __attribute__((format (printf, 3, 4)))
120 static int nfsnprintf(char *buf, int blen, const char *fmt, ...);
122 static int nfvasprintf(char **strp, const char *fmt, va_list ap)
127 len = vsnprintf(tmp, sizeof(tmp), fmt, ap);
129 die("Fatal: Out of memory");
130 if (len >= sizeof(tmp))
131 die("imap command overflow!");
132 *strp = xmemdupz(tmp, len);
136 struct imap_server_conf {
149 static struct imap_server_conf server = {
159 NULL, /* auth_method */
162 struct imap_store_conf {
163 struct store_conf gen;
164 struct imap_server_conf *server;
165 unsigned use_namespace:1;
168 #define NIL (void *)0x1
169 #define LIST (void *)0x2
172 struct imap_list *next, *child;
183 struct imap_socket sock;
192 int uidnext; /* from SELECT responses */
193 struct imap_list *ns_personal, *ns_other, *ns_shared; /* NAMESPACE info */
194 unsigned caps, rcaps; /* CAPABILITY results */
196 int nexttag, num_in_progress, literal_pending;
197 struct imap_cmd *in_progress, **in_progress_append;
198 struct imap_buffer buf; /* this is BIG, so put it last */
206 unsigned /*currentnc:1,*/ trashnc:1;
210 int (*cont)(struct imap_store *ctx, struct imap_cmd *cmd, const char *prompt);
211 void (*done)(struct imap_store *ctx, struct imap_cmd *cmd, int response);
216 unsigned create:1, trycreate:1;
220 struct imap_cmd *next;
221 struct imap_cmd_cb cb;
226 #define CAP(cap) (imap->caps & (1 << (cap)))
237 static const char *cap_list[] = {
250 static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd);
253 static const char *Flags[] = {
262 static void ssl_socket_perror(const char *func)
264 fprintf(stderr, "%s: %s\n", func, ERR_error_string(ERR_get_error(), NULL));
268 static void socket_perror(const char *func, struct imap_socket *sock, int ret)
272 int sslerr = SSL_get_error(sock->ssl, ret);
276 case SSL_ERROR_SYSCALL:
277 perror("SSL_connect");
280 ssl_socket_perror("SSL_connect");
289 fprintf(stderr, "%s: unexpected EOF\n", func);
293 static int ssl_socket_connect(struct imap_socket *sock, int use_tls_only, int verify)
296 fprintf(stderr, "SSL requested but SSL support not compiled in\n");
299 #if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
300 const SSL_METHOD *meth;
308 SSL_load_error_strings();
311 meth = TLSv1_method();
313 meth = SSLv23_method();
316 ssl_socket_perror("SSLv23_method");
320 ctx = SSL_CTX_new(meth);
323 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
325 if (!SSL_CTX_set_default_verify_paths(ctx)) {
326 ssl_socket_perror("SSL_CTX_set_default_verify_paths");
329 sock->ssl = SSL_new(ctx);
331 ssl_socket_perror("SSL_new");
334 if (!SSL_set_rfd(sock->ssl, sock->fd[0])) {
335 ssl_socket_perror("SSL_set_rfd");
338 if (!SSL_set_wfd(sock->ssl, sock->fd[1])) {
339 ssl_socket_perror("SSL_set_wfd");
343 ret = SSL_connect(sock->ssl);
345 socket_perror("SSL_connect", sock, ret);
353 static int socket_read(struct imap_socket *sock, char *buf, int len)
358 n = SSL_read(sock->ssl, buf, len);
361 n = xread(sock->fd[0], buf, len);
363 socket_perror("read", sock, n);
366 sock->fd[0] = sock->fd[1] = -1;
371 static int socket_write(struct imap_socket *sock, const char *buf, int len)
376 n = SSL_write(sock->ssl, buf, len);
379 n = write_in_full(sock->fd[1], buf, len);
381 socket_perror("write", sock, n);
384 sock->fd[0] = sock->fd[1] = -1;
389 static void socket_shutdown(struct imap_socket *sock)
393 SSL_shutdown(sock->ssl);
401 /* simple line buffering */
402 static int buffer_gets(struct imap_buffer *b, char **s)
405 int start = b->offset;
410 /* make sure we have enough data to read the \r\n sequence */
411 if (b->offset + 1 >= b->bytes) {
413 /* shift down used bytes */
416 assert(start <= b->bytes);
417 n = b->bytes - start;
420 memmove(b->buf, b->buf + start, n);
426 n = socket_read(&b->sock, b->buf + b->bytes,
427 sizeof(b->buf) - b->bytes);
435 if (b->buf[b->offset] == '\r') {
436 assert(b->offset + 1 < b->bytes);
437 if (b->buf[b->offset + 1] == '\n') {
438 b->buf[b->offset] = 0; /* terminate the string */
439 b->offset += 2; /* next line */
451 static void imap_info(const char *msg, ...)
463 static void imap_warn(const char *msg, ...)
469 vfprintf(stderr, msg, va);
474 static char *next_arg(char **s)
480 while (isspace((unsigned char) **s))
489 *s = strchr(*s, '"');
492 while (**s && !isspace((unsigned char) **s))
504 static void free_generic_messages(struct message *msgs)
506 struct message *tmsg;
508 for (; msgs; msgs = tmsg) {
514 static int nfsnprintf(char *buf, int blen, const char *fmt, ...)
520 if (blen <= 0 || (unsigned)(ret = vsnprintf(buf, blen, fmt, va)) >= (unsigned)blen)
521 die("Fatal: buffer too small. Please report a bug.");
526 static struct imap_cmd *v_issue_imap_cmd(struct imap_store *ctx,
527 struct imap_cmd_cb *cb,
528 const char *fmt, va_list ap)
530 struct imap *imap = ctx->imap;
531 struct imap_cmd *cmd;
535 cmd = xmalloc(sizeof(struct imap_cmd));
536 nfvasprintf(&cmd->cmd, fmt, ap);
537 cmd->tag = ++imap->nexttag;
542 memset(&cmd->cb, 0, sizeof(cmd->cb));
544 while (imap->literal_pending)
545 get_cmd_result(ctx, NULL);
547 bufl = nfsnprintf(buf, sizeof(buf), cmd->cb.data ? CAP(LITERALPLUS) ?
548 "%d %s{%d+}\r\n" : "%d %s{%d}\r\n" : "%d %s\r\n",
549 cmd->tag, cmd->cmd, cmd->cb.dlen);
551 if (imap->num_in_progress)
552 printf("(%d in progress) ", imap->num_in_progress);
553 if (memcmp(cmd->cmd, "LOGIN", 5))
554 printf(">>> %s", buf);
556 printf(">>> %d LOGIN <user> <pass>\n", cmd->tag);
558 if (socket_write(&imap->buf.sock, buf, bufl) != bufl) {
566 if (CAP(LITERALPLUS)) {
567 n = socket_write(&imap->buf.sock, cmd->cb.data, cmd->cb.dlen);
569 if (n != cmd->cb.dlen ||
570 socket_write(&imap->buf.sock, "\r\n", 2) != 2) {
577 imap->literal_pending = 1;
578 } else if (cmd->cb.cont)
579 imap->literal_pending = 1;
581 *imap->in_progress_append = cmd;
582 imap->in_progress_append = &cmd->next;
583 imap->num_in_progress++;
587 __attribute__((format (printf, 3, 4)))
588 static struct imap_cmd *issue_imap_cmd(struct imap_store *ctx,
589 struct imap_cmd_cb *cb,
590 const char *fmt, ...)
592 struct imap_cmd *ret;
596 ret = v_issue_imap_cmd(ctx, cb, fmt, ap);
601 __attribute__((format (printf, 3, 4)))
602 static int imap_exec(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);
614 return get_cmd_result(ctx, cmdp);
617 __attribute__((format (printf, 3, 4)))
618 static int imap_exec_m(struct imap_store *ctx, struct imap_cmd_cb *cb,
619 const char *fmt, ...)
622 struct imap_cmd *cmdp;
625 cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
628 return DRV_STORE_BAD;
630 switch (get_cmd_result(ctx, cmdp)) {
631 case RESP_BAD: return DRV_STORE_BAD;
632 case RESP_NO: return DRV_MSG_BAD;
633 default: return DRV_OK;
637 static int is_atom(struct imap_list *list)
639 return list && list->val && list->val != NIL && list->val != LIST;
642 static int is_list(struct imap_list *list)
644 return list && list->val == LIST;
647 static void free_list(struct imap_list *list)
649 struct imap_list *tmp;
651 for (; list; list = tmp) {
654 free_list(list->child);
655 else if (is_atom(list))
661 static int parse_imap_list_l(struct imap *imap, char **sp, struct imap_list **curp, int level)
663 struct imap_list *cur;
668 while (isspace((unsigned char)*s))
670 if (level && *s == ')') {
674 *curp = cur = xmalloc(sizeof(*cur));
676 cur->val = NULL; /* for clean bail */
681 if (parse_imap_list_l(imap, &s, &cur->child, level + 1))
683 } else if (imap && *s == '{') {
685 bytes = cur->len = strtol(s + 1, &s, 10);
689 s = cur->val = xmalloc(cur->len);
691 /* dump whats left over in the input buffer */
692 n = imap->buf.bytes - imap->buf.offset;
695 /* the entire message fit in the buffer */
698 memcpy(s, imap->buf.buf + imap->buf.offset, n);
702 /* mark that we used part of the buffer */
703 imap->buf.offset += n;
705 /* now read the rest of the message */
707 if ((n = socket_read(&imap->buf.sock, s, bytes)) <= 0)
713 if (buffer_gets(&imap->buf, &s))
715 } else if (*s == '"') {
719 for (; *s != '"'; s++)
724 cur->val = xmemdupz(p, cur->len);
728 for (; *s && !isspace((unsigned char)*s); s++)
729 if (level && *s == ')')
732 if (cur->len == 3 && !memcmp("NIL", p, 3))
735 cur->val = xmemdupz(p, cur->len);
752 static struct imap_list *parse_imap_list(struct imap *imap, char **sp)
754 struct imap_list *head;
756 if (!parse_imap_list_l(imap, sp, &head, 0))
762 static struct imap_list *parse_list(char **sp)
764 return parse_imap_list(NULL, sp);
767 static void parse_capability(struct imap *imap, char *cmd)
772 imap->caps = 0x80000000;
773 while ((arg = next_arg(&cmd)))
774 for (i = 0; i < ARRAY_SIZE(cap_list); i++)
775 if (!strcmp(cap_list[i], arg))
776 imap->caps |= 1 << i;
777 imap->rcaps = imap->caps;
780 static int parse_response_code(struct imap_store *ctx, struct imap_cmd_cb *cb,
783 struct imap *imap = ctx->imap;
787 return RESP_OK; /* no response code */
789 if (!(p = strchr(s, ']'))) {
790 fprintf(stderr, "IMAP error: malformed response code\n");
795 if (!strcmp("UIDVALIDITY", arg)) {
796 if (!(arg = next_arg(&s)) || !(ctx->gen.uidvalidity = atoi(arg))) {
797 fprintf(stderr, "IMAP error: malformed UIDVALIDITY status\n");
800 } else if (!strcmp("UIDNEXT", arg)) {
801 if (!(arg = next_arg(&s)) || !(imap->uidnext = atoi(arg))) {
802 fprintf(stderr, "IMAP error: malformed NEXTUID status\n");
805 } else if (!strcmp("CAPABILITY", arg)) {
806 parse_capability(imap, s);
807 } else if (!strcmp("ALERT", arg)) {
808 /* RFC2060 says that these messages MUST be displayed
811 for (; isspace((unsigned char)*p); p++);
812 fprintf(stderr, "*** IMAP ALERT *** %s\n", p);
813 } else if (cb && cb->ctx && !strcmp("APPENDUID", arg)) {
814 if (!(arg = next_arg(&s)) || !(ctx->gen.uidvalidity = atoi(arg)) ||
815 !(arg = next_arg(&s)) || !(*(int *)cb->ctx = atoi(arg))) {
816 fprintf(stderr, "IMAP error: malformed APPENDUID status\n");
823 static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd)
825 struct imap *imap = ctx->imap;
826 struct imap_cmd *cmdp, **pcmdp, *ncmdp;
827 char *cmd, *arg, *arg1, *p;
828 int n, resp, resp2, tag;
831 if (buffer_gets(&imap->buf, &cmd))
834 arg = next_arg(&cmd);
836 arg = next_arg(&cmd);
838 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
842 if (!strcmp("NAMESPACE", arg)) {
843 imap->ns_personal = parse_list(&cmd);
844 imap->ns_other = parse_list(&cmd);
845 imap->ns_shared = parse_list(&cmd);
846 } else if (!strcmp("OK", arg) || !strcmp("BAD", arg) ||
847 !strcmp("NO", arg) || !strcmp("BYE", arg)) {
848 if ((resp = parse_response_code(ctx, NULL, cmd)) != RESP_OK)
850 } else if (!strcmp("CAPABILITY", arg))
851 parse_capability(imap, cmd);
852 else if ((arg1 = next_arg(&cmd))) {
853 if (!strcmp("EXISTS", arg1))
854 ctx->gen.count = atoi(arg);
855 else if (!strcmp("RECENT", arg1))
856 ctx->gen.recent = atoi(arg);
858 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
861 } else if (!imap->in_progress) {
862 fprintf(stderr, "IMAP error: unexpected reply: %s %s\n", arg, cmd ? cmd : "");
864 } else if (*arg == '+') {
865 /* This can happen only with the last command underway, as
866 it enforces a round-trip. */
867 cmdp = (struct imap_cmd *)((char *)imap->in_progress_append -
868 offsetof(struct imap_cmd, next));
870 n = socket_write(&imap->buf.sock, cmdp->cb.data, cmdp->cb.dlen);
872 cmdp->cb.data = NULL;
873 if (n != (int)cmdp->cb.dlen)
875 } else if (cmdp->cb.cont) {
876 if (cmdp->cb.cont(ctx, cmdp, cmd))
879 fprintf(stderr, "IMAP error: unexpected command continuation request\n");
882 if (socket_write(&imap->buf.sock, "\r\n", 2) != 2)
885 imap->literal_pending = 0;
890 for (pcmdp = &imap->in_progress; (cmdp = *pcmdp); pcmdp = &cmdp->next)
891 if (cmdp->tag == tag)
893 fprintf(stderr, "IMAP error: unexpected tag %s\n", arg);
896 if (!(*pcmdp = cmdp->next))
897 imap->in_progress_append = pcmdp;
898 imap->num_in_progress--;
899 if (cmdp->cb.cont || cmdp->cb.data)
900 imap->literal_pending = 0;
901 arg = next_arg(&cmd);
902 if (!strcmp("OK", arg))
905 if (!strcmp("NO", arg)) {
906 if (cmdp->cb.create && cmd && (cmdp->cb.trycreate || !memcmp(cmd, "[TRYCREATE]", 11))) { /* SELECT, APPEND or UID COPY */
907 p = strchr(cmdp->cmd, '"');
908 if (!issue_imap_cmd(ctx, NULL, "CREATE \"%.*s\"", (int)(strchr(p + 1, '"') - p + 1), p)) {
912 /* not waiting here violates the spec, but a server that does not
913 grok this nonetheless violates it too. */
915 if (!(ncmdp = issue_imap_cmd(ctx, &cmdp->cb, "%s", cmdp->cmd))) {
922 return 0; /* ignored */
928 } else /*if (!strcmp("BAD", arg))*/
930 fprintf(stderr, "IMAP command '%s' returned response (%s) - %s\n",
931 memcmp(cmdp->cmd, "LOGIN", 5) ?
932 cmdp->cmd : "LOGIN <user> <pass>",
933 arg, cmd ? cmd : "");
935 if ((resp2 = parse_response_code(ctx, &cmdp->cb, cmd)) > resp)
939 cmdp->cb.done(ctx, cmdp, resp);
943 if (!tcmd || tcmd == cmdp)
950 static void imap_close_server(struct imap_store *ictx)
952 struct imap *imap = ictx->imap;
954 if (imap->buf.sock.fd[0] != -1) {
955 imap_exec(ictx, NULL, "LOGOUT");
956 socket_shutdown(&imap->buf.sock);
958 free_list(imap->ns_personal);
959 free_list(imap->ns_other);
960 free_list(imap->ns_shared);
964 static void imap_close_store(struct store *ctx)
966 imap_close_server((struct imap_store *)ctx);
967 free_generic_messages(ctx->msgs);
974 * hexchar() and cram() functions are based on the code from the isync
975 * project (http://isync.sf.net/).
977 static char hexchar(unsigned int b)
979 return b < 10 ? '0' + b : 'a' + (b - 10);
982 #define ENCODED_SIZE(n) (4*((n+2)/3))
983 static char *cram(const char *challenge_64, const char *user, const char *pass)
985 int i, resp_len, encoded_len, decoded_len;
987 unsigned char hash[16];
989 char *response, *response_64, *challenge;
992 * length of challenge_64 (i.e. base-64 encoded string) is a good
993 * enough upper bound for challenge (decoded result).
995 encoded_len = strlen(challenge_64);
996 challenge = xmalloc(encoded_len);
997 decoded_len = EVP_DecodeBlock((unsigned char *)challenge,
998 (unsigned char *)challenge_64, encoded_len);
1000 die("invalid challenge %s", challenge_64);
1001 HMAC_Init(&hmac, (unsigned char *)pass, strlen(pass), EVP_md5());
1002 HMAC_Update(&hmac, (unsigned char *)challenge, decoded_len);
1003 HMAC_Final(&hmac, hash, NULL);
1004 HMAC_CTX_cleanup(&hmac);
1007 for (i = 0; i < 16; i++) {
1008 hex[2 * i] = hexchar((hash[i] >> 4) & 0xf);
1009 hex[2 * i + 1] = hexchar(hash[i] & 0xf);
1012 /* response: "<user> <digest in hex>" */
1013 resp_len = strlen(user) + 1 + strlen(hex) + 1;
1014 response = xmalloc(resp_len);
1015 sprintf(response, "%s %s", user, hex);
1017 response_64 = xmalloc(ENCODED_SIZE(resp_len) + 1);
1018 encoded_len = EVP_EncodeBlock((unsigned char *)response_64,
1019 (unsigned char *)response, resp_len);
1020 if (encoded_len < 0)
1021 die("EVP_EncodeBlock error");
1022 response_64[encoded_len] = '\0';
1023 return (char *)response_64;
1028 static char *cram(const char *challenge_64, const char *user, const char *pass)
1030 die("If you want to use CRAM-MD5 authenticate method, "
1031 "you have to build git-imap-send with OpenSSL library.");
1036 static int auth_cram_md5(struct imap_store *ctx, struct imap_cmd *cmd, const char *prompt)
1041 response = cram(prompt, server.user, server.pass);
1043 ret = socket_write(&ctx->imap->buf.sock, response, strlen(response));
1044 if (ret != strlen(response))
1045 return error("IMAP error: sending response failed\n");
1052 static struct store *imap_open_store(struct imap_server_conf *srvc)
1054 struct imap_store *ctx;
1057 int s = -1, preauth;
1059 ctx = xcalloc(sizeof(*ctx), 1);
1061 ctx->imap = imap = xcalloc(sizeof(*imap), 1);
1062 imap->buf.sock.fd[0] = imap->buf.sock.fd[1] = -1;
1063 imap->in_progress_append = &imap->in_progress;
1065 /* open connection to IMAP server */
1068 const char *argv[] = { srvc->tunnel, NULL };
1069 struct child_process tunnel = {0};
1071 imap_info("Starting tunnel '%s'... ", srvc->tunnel);
1074 tunnel.use_shell = 1;
1077 if (start_command(&tunnel))
1078 die("cannot start proxy %s", argv[0]);
1080 imap->buf.sock.fd[0] = tunnel.out;
1081 imap->buf.sock.fd[1] = tunnel.in;
1086 struct addrinfo hints, *ai0, *ai;
1090 snprintf(portstr, sizeof(portstr), "%hu", srvc->port);
1092 memset(&hints, 0, sizeof(hints));
1093 hints.ai_socktype = SOCK_STREAM;
1094 hints.ai_protocol = IPPROTO_TCP;
1096 imap_info("Resolving %s... ", srvc->host);
1097 gai = getaddrinfo(srvc->host, portstr, &hints, &ai);
1099 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai));
1104 for (ai0 = ai; ai; ai = ai->ai_next) {
1105 char addr[NI_MAXHOST];
1107 s = socket(ai->ai_family, ai->ai_socktype,
1112 getnameinfo(ai->ai_addr, ai->ai_addrlen, addr,
1113 sizeof(addr), NULL, 0, NI_NUMERICHOST);
1114 imap_info("Connecting to [%s]:%s... ", addr, portstr);
1116 if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0) {
1128 struct sockaddr_in addr;
1130 memset(&addr, 0, sizeof(addr));
1131 addr.sin_port = htons(srvc->port);
1132 addr.sin_family = AF_INET;
1134 imap_info("Resolving %s... ", srvc->host);
1135 he = gethostbyname(srvc->host);
1137 perror("gethostbyname");
1142 addr.sin_addr.s_addr = *((int *) he->h_addr_list[0]);
1144 s = socket(PF_INET, SOCK_STREAM, 0);
1146 imap_info("Connecting to %s:%hu... ", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
1147 if (connect(s, (struct sockaddr *)&addr, sizeof(addr))) {
1154 fputs("Error: unable to connect to server.\n", stderr);
1158 imap->buf.sock.fd[0] = s;
1159 imap->buf.sock.fd[1] = dup(s);
1161 if (srvc->use_ssl &&
1162 ssl_socket_connect(&imap->buf.sock, 0, srvc->ssl_verify)) {
1169 /* read the greeting string */
1170 if (buffer_gets(&imap->buf, &rsp)) {
1171 fprintf(stderr, "IMAP error: no greeting response\n");
1174 arg = next_arg(&rsp);
1175 if (!arg || *arg != '*' || (arg = next_arg(&rsp)) == NULL) {
1176 fprintf(stderr, "IMAP error: invalid greeting response\n");
1180 if (!strcmp("PREAUTH", arg))
1182 else if (strcmp("OK", arg) != 0) {
1183 fprintf(stderr, "IMAP error: unknown greeting response\n");
1186 parse_response_code(ctx, NULL, rsp);
1187 if (!imap->caps && imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1192 if (!srvc->use_ssl && CAP(STARTTLS)) {
1193 if (imap_exec(ctx, 0, "STARTTLS") != RESP_OK)
1195 if (ssl_socket_connect(&imap->buf.sock, 1,
1198 /* capabilities may have changed, so get the new capabilities */
1199 if (imap_exec(ctx, 0, "CAPABILITY") != RESP_OK)
1203 imap_info("Logging in...\n");
1205 fprintf(stderr, "Skipping server %s, no user\n", srvc->host);
1210 sprintf(prompt, "Password (%s@%s): ", srvc->user, srvc->host);
1211 arg = getpass(prompt);
1217 fprintf(stderr, "Skipping account %s@%s, no password\n", srvc->user, srvc->host);
1221 * getpass() returns a pointer to a static buffer. make a copy
1222 * for long term storage.
1224 srvc->pass = xstrdup(arg);
1227 fprintf(stderr, "Skipping account %s@%s, server forbids LOGIN\n", srvc->user, srvc->host);
1230 if (!imap->buf.sock.ssl)
1231 imap_warn("*** IMAP Warning *** Password is being "
1232 "sent in the clear\n");
1234 if (srvc->auth_method) {
1235 struct imap_cmd_cb cb;
1237 if (!strcmp(srvc->auth_method, "CRAM-MD5")) {
1238 if (!CAP(AUTH_CRAM_MD5)) {
1239 fprintf(stderr, "You specified"
1240 "CRAM-MD5 as authentication method, "
1241 "but %s doesn't support it.\n", srvc->host);
1246 memset(&cb, 0, sizeof(cb));
1247 cb.cont = auth_cram_md5;
1248 if (imap_exec(ctx, &cb, "AUTHENTICATE CRAM-MD5") != RESP_OK) {
1249 fprintf(stderr, "IMAP error: AUTHENTICATE CRAM-MD5 failed\n");
1253 fprintf(stderr, "Unknown authentication method:%s\n", srvc->host);
1257 if (imap_exec(ctx, NULL, "LOGIN \"%s\" \"%s\"", srvc->user, srvc->pass) != RESP_OK) {
1258 fprintf(stderr, "IMAP error: LOGIN failed\n");
1266 return (struct store *)ctx;
1269 imap_close_store(&ctx->gen);
1273 static int imap_make_flags(int flags, char *buf)
1278 for (i = d = 0; i < ARRAY_SIZE(Flags); i++)
1279 if (flags & (1 << i)) {
1282 for (s = Flags[i]; *s; s++)
1290 static int imap_store_msg(struct store *gctx, struct msg_data *data)
1292 struct imap_store *ctx = (struct imap_store *)gctx;
1293 struct imap *imap = ctx->imap;
1294 struct imap_cmd_cb cb;
1295 const char *prefix, *box;
1299 memset(&cb, 0, sizeof(cb));
1301 cb.dlen = data->len;
1302 cb.data = xmalloc(cb.dlen);
1303 memcpy(cb.data, data->data, data->len);
1307 d = imap_make_flags(data->flags, flagstr);
1313 prefix = !strcmp(box, "INBOX") ? "" : ctx->prefix;
1315 ret = imap_exec_m(ctx, &cb, "APPEND \"%s%s\" %s", prefix, box, flagstr);
1316 imap->caps = imap->rcaps;
1324 static void encode_html_chars(struct strbuf *p)
1327 for (i = 0; i < p->len; i++) {
1328 if (p->buf[i] == '&')
1329 strbuf_splice(p, i, 1, "&", 5);
1330 if (p->buf[i] == '<')
1331 strbuf_splice(p, i, 1, "<", 4);
1332 if (p->buf[i] == '>')
1333 strbuf_splice(p, i, 1, ">", 4);
1334 if (p->buf[i] == '"')
1335 strbuf_splice(p, i, 1, """, 6);
1338 static void wrap_in_html(struct msg_data *msg)
1340 struct strbuf buf = STRBUF_INIT;
1341 struct strbuf **lines;
1343 static char *content_type = "Content-Type: text/html;\n";
1344 static char *pre_open = "<pre>\n";
1345 static char *pre_close = "</pre>\n";
1346 int added_header = 0;
1348 strbuf_attach(&buf, msg->data, msg->len, msg->len);
1349 lines = strbuf_split(&buf, '\n');
1350 strbuf_release(&buf);
1351 for (p = lines; *p; p++) {
1352 if (! added_header) {
1353 if ((*p)->len == 1 && *((*p)->buf) == '\n') {
1354 strbuf_addstr(&buf, content_type);
1355 strbuf_addbuf(&buf, *p);
1356 strbuf_addstr(&buf, pre_open);
1362 encode_html_chars(*p);
1363 strbuf_addbuf(&buf, *p);
1365 strbuf_addstr(&buf, pre_close);
1366 strbuf_list_free(lines);
1368 msg->data = strbuf_detach(&buf, NULL);
1371 #define CHUNKSIZE 0x1000
1373 static int read_message(FILE *f, struct msg_data *msg)
1375 struct strbuf buf = STRBUF_INIT;
1377 memset(msg, 0, sizeof(*msg));
1380 if (strbuf_fread(&buf, CHUNKSIZE, f) <= 0)
1385 msg->data = strbuf_detach(&buf, NULL);
1389 static int count_messages(struct msg_data *msg)
1392 char *p = msg->data;
1395 if (!prefixcmp(p, "From ")) {
1399 p = strstr(p+5, "\nFrom ");
1407 static int split_msg(struct msg_data *all_msgs, struct msg_data *msg, int *ofs)
1411 memset(msg, 0, sizeof *msg);
1412 if (*ofs >= all_msgs->len)
1415 data = &all_msgs->data[*ofs];
1416 msg->len = all_msgs->len - *ofs;
1418 if (msg->len < 5 || prefixcmp(data, "From "))
1421 p = strchr(data, '\n');
1429 p = strstr(data, "\nFrom ");
1431 msg->len = &p[1] - data;
1433 msg->data = xmemdupz(data, msg->len);
1438 static char *imap_folder;
1440 static int git_imap_config(const char *key, const char *val, void *cb)
1442 char imap_key[] = "imap.";
1444 if (strncmp(key, imap_key, sizeof imap_key - 1))
1447 key += sizeof imap_key - 1;
1449 /* check booleans first, and barf on others */
1450 if (!strcmp("sslverify", key))
1451 server.ssl_verify = git_config_bool(key, val);
1452 else if (!strcmp("preformattedhtml", key))
1453 server.use_html = git_config_bool(key, val);
1455 return config_error_nonbool(key);
1457 if (!strcmp("folder", key)) {
1458 imap_folder = xstrdup(val);
1459 } else if (!strcmp("host", key)) {
1460 if (!prefixcmp(val, "imap:"))
1462 else if (!prefixcmp(val, "imaps:")) {
1466 if (!prefixcmp(val, "//"))
1468 server.host = xstrdup(val);
1469 } else if (!strcmp("user", key))
1470 server.user = xstrdup(val);
1471 else if (!strcmp("pass", key))
1472 server.pass = xstrdup(val);
1473 else if (!strcmp("port", key))
1474 server.port = git_config_int(key, val);
1475 else if (!strcmp("tunnel", key))
1476 server.tunnel = xstrdup(val);
1477 else if (!strcmp("authmethod", key))
1478 server.auth_method = xstrdup(val);
1483 int main(int argc, char **argv)
1485 struct msg_data all_msgs, msg;
1486 struct store *ctx = NULL;
1492 git_extract_argv0_path(argv[0]);
1495 usage(imap_send_usage);
1497 setup_git_directory_gently(&nongit_ok);
1498 git_config(git_imap_config, NULL);
1501 server.port = server.use_ssl ? 993 : 143;
1504 fprintf(stderr, "no imap store specified\n");
1508 if (!server.tunnel) {
1509 fprintf(stderr, "no imap host specified\n");
1512 server.host = "tunnel";
1515 /* read the messages */
1516 if (!read_message(stdin, &all_msgs)) {
1517 fprintf(stderr, "nothing to send\n");
1521 total = count_messages(&all_msgs);
1523 fprintf(stderr, "no messages to send\n");
1527 /* write it to the imap server */
1528 ctx = imap_open_store(&server);
1530 fprintf(stderr, "failed to open store\n");
1534 fprintf(stderr, "sending %d message%s\n", total, (total != 1) ? "s" : "");
1535 ctx->name = imap_folder;
1537 unsigned percent = n * 100 / total;
1538 fprintf(stderr, "%4u%% (%d/%d) done\r", percent, n, total);
1539 if (!split_msg(&all_msgs, &msg, &ofs))
1541 if (server.use_html)
1543 r = imap_store_msg(ctx, &msg);
1548 fprintf(stderr, "\n");
1550 imap_close_store(ctx);