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>
34 #include <openssl/x509v3.h>
39 const char *path; /* should this be here? its interpretation is driver-specific */
42 unsigned max_size; /* off_t is overkill */
43 unsigned trash_remote_new:1, trash_only_new:1;
46 /* For message->status */
47 #define M_RECENT (1<<0) /* unsyncable flag; maildir_* depend on this being 1<<0 */
48 #define M_DEAD (1<<1) /* expunged */
49 #define M_FLAGS (1<<2) /* flags fetched */
53 size_t size; /* zero implies "not fetched" */
55 unsigned char flags, status;
59 struct store_conf *conf; /* foreign */
61 /* currently open mailbox */
62 const char *name; /* foreign! maybe preset? */
64 struct message *msgs; /* own */
66 unsigned char opts; /* maybe preset? */
67 /* note that the following do _not_ reflect stats from msgs, but mailbox totals */
68 int count; /* # of messages */
69 int recent; /* # of recent messages - don't trust this beyond the initial read */
78 static const char imap_send_usage[] = "git imap-send < <mbox>";
82 #define DRV_MSG_BAD -1
83 #define DRV_BOX_BAD -2
84 #define DRV_STORE_BAD -3
86 static int Verbose, Quiet;
88 __attribute__((format (printf, 1, 2)))
89 static void imap_info(const char *, ...);
90 __attribute__((format (printf, 1, 2)))
91 static void imap_warn(const char *, ...);
93 static char *next_arg(char **);
95 static void free_generic_messages(struct message *);
97 __attribute__((format (printf, 3, 4)))
98 static int nfsnprintf(char *buf, int blen, const char *fmt, ...);
100 static int nfvasprintf(char **strp, const char *fmt, va_list ap)
105 len = vsnprintf(tmp, sizeof(tmp), fmt, ap);
107 die("Fatal: Out of memory");
108 if (len >= sizeof(tmp))
109 die("imap command overflow!");
110 *strp = xmemdupz(tmp, len);
114 struct imap_server_conf {
127 static struct imap_server_conf server = {
137 NULL, /* auth_method */
140 struct imap_store_conf {
141 struct store_conf gen;
142 struct imap_server_conf *server;
145 #define NIL (void *)0x1
146 #define LIST (void *)0x2
149 struct imap_list *next, *child;
160 struct imap_socket sock;
169 int uidnext; /* from SELECT responses */
170 struct imap_list *ns_personal, *ns_other, *ns_shared; /* NAMESPACE info */
171 unsigned caps, rcaps; /* CAPABILITY results */
173 int nexttag, num_in_progress, literal_pending;
174 struct imap_cmd *in_progress, **in_progress_append;
175 struct imap_buffer buf; /* this is BIG, so put it last */
183 unsigned /*currentnc:1,*/ trashnc:1;
187 int (*cont)(struct imap_store *ctx, struct imap_cmd *cmd, const char *prompt);
188 void (*done)(struct imap_store *ctx, struct imap_cmd *cmd, int response);
193 unsigned create:1, trycreate:1;
197 struct imap_cmd *next;
198 struct imap_cmd_cb cb;
203 #define CAP(cap) (imap->caps & (1 << (cap)))
214 static const char *cap_list[] = {
227 static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd);
230 static const char *Flags[] = {
239 static void ssl_socket_perror(const char *func)
241 fprintf(stderr, "%s: %s\n", func, ERR_error_string(ERR_get_error(), NULL));
245 static void socket_perror(const char *func, struct imap_socket *sock, int ret)
249 int sslerr = SSL_get_error(sock->ssl, ret);
253 case SSL_ERROR_SYSCALL:
254 perror("SSL_connect");
257 ssl_socket_perror("SSL_connect");
266 fprintf(stderr, "%s: unexpected EOF\n", func);
271 static int ssl_socket_connect(struct imap_socket *sock, int use_tls_only, int verify)
273 fprintf(stderr, "SSL requested but SSL support not compiled in\n");
279 static int host_matches(const char *host, const char *pattern)
281 if (pattern[0] == '*' && pattern[1] == '.') {
283 if (!(host = strchr(host, '.')))
288 return *host && *pattern && !strcasecmp(host, pattern);
291 static int verify_hostname(X509 *cert, const char *hostname)
297 STACK_OF(GENERAL_NAME) *subj_alt_names;
299 /* try the DNS subjectAltNames */
301 if ((subj_alt_names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL))) {
302 int num_subj_alt_names = sk_GENERAL_NAME_num(subj_alt_names);
303 for (i = 0; !found && i < num_subj_alt_names; i++) {
304 GENERAL_NAME *subj_alt_name = sk_GENERAL_NAME_value(subj_alt_names, i);
305 if (subj_alt_name->type == GEN_DNS &&
306 strlen((const char *)subj_alt_name->d.ia5->data) == (size_t)subj_alt_name->d.ia5->length &&
307 host_matches(hostname, (const char *)(subj_alt_name->d.ia5->data)))
310 sk_GENERAL_NAME_pop_free(subj_alt_names, GENERAL_NAME_free);
315 /* try the common name */
316 if (!(subj = X509_get_subject_name(cert)))
317 return error("cannot get certificate subject");
318 if ((len = X509_NAME_get_text_by_NID(subj, NID_commonName, cname, sizeof(cname))) < 0)
319 return error("cannot get certificate common name");
320 if (strlen(cname) == (size_t)len && host_matches(hostname, cname))
322 return error("certificate owner '%s' does not match hostname '%s'",
326 static int ssl_socket_connect(struct imap_socket *sock, int use_tls_only, int verify)
328 #if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
329 const SSL_METHOD *meth;
338 SSL_load_error_strings();
341 meth = TLSv1_method();
343 meth = SSLv23_method();
346 ssl_socket_perror("SSLv23_method");
350 ctx = SSL_CTX_new(meth);
353 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
355 if (!SSL_CTX_set_default_verify_paths(ctx)) {
356 ssl_socket_perror("SSL_CTX_set_default_verify_paths");
359 sock->ssl = SSL_new(ctx);
361 ssl_socket_perror("SSL_new");
364 if (!SSL_set_rfd(sock->ssl, sock->fd[0])) {
365 ssl_socket_perror("SSL_set_rfd");
368 if (!SSL_set_wfd(sock->ssl, sock->fd[1])) {
369 ssl_socket_perror("SSL_set_wfd");
373 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
376 * OpenSSL does not document this function, but the implementation
377 * returns 1 on success, 0 on failure after calling SSLerr().
379 ret = SSL_set_tlsext_host_name(sock->ssl, server.host);
381 warning("SSL_set_tlsext_host_name(%s) failed.", server.host);
384 ret = SSL_connect(sock->ssl);
386 socket_perror("SSL_connect", sock, ret);
391 /* make sure the hostname matches that of the certificate */
392 cert = SSL_get_peer_certificate(sock->ssl);
394 return error("unable to get peer certificate.");
395 if (verify_hostname(cert, server.host) < 0)
403 static int socket_read(struct imap_socket *sock, char *buf, int len)
408 n = SSL_read(sock->ssl, buf, len);
411 n = xread(sock->fd[0], buf, len);
413 socket_perror("read", sock, n);
416 sock->fd[0] = sock->fd[1] = -1;
421 static int socket_write(struct imap_socket *sock, const char *buf, int len)
426 n = SSL_write(sock->ssl, buf, len);
429 n = write_in_full(sock->fd[1], buf, len);
431 socket_perror("write", sock, n);
434 sock->fd[0] = sock->fd[1] = -1;
439 static void socket_shutdown(struct imap_socket *sock)
443 SSL_shutdown(sock->ssl);
451 /* simple line buffering */
452 static int buffer_gets(struct imap_buffer *b, char **s)
455 int start = b->offset;
460 /* make sure we have enough data to read the \r\n sequence */
461 if (b->offset + 1 >= b->bytes) {
463 /* shift down used bytes */
466 assert(start <= b->bytes);
467 n = b->bytes - start;
470 memmove(b->buf, b->buf + start, n);
476 n = socket_read(&b->sock, b->buf + b->bytes,
477 sizeof(b->buf) - b->bytes);
485 if (b->buf[b->offset] == '\r') {
486 assert(b->offset + 1 < b->bytes);
487 if (b->buf[b->offset + 1] == '\n') {
488 b->buf[b->offset] = 0; /* terminate the string */
489 b->offset += 2; /* next line */
501 static void imap_info(const char *msg, ...)
513 static void imap_warn(const char *msg, ...)
519 vfprintf(stderr, msg, va);
524 static char *next_arg(char **s)
530 while (isspace((unsigned char) **s))
539 *s = strchr(*s, '"');
542 while (**s && !isspace((unsigned char) **s))
554 static void free_generic_messages(struct message *msgs)
556 struct message *tmsg;
558 for (; msgs; msgs = tmsg) {
564 static int nfsnprintf(char *buf, int blen, const char *fmt, ...)
570 if (blen <= 0 || (unsigned)(ret = vsnprintf(buf, blen, fmt, va)) >= (unsigned)blen)
571 die("Fatal: buffer too small. Please report a bug.");
576 static struct imap_cmd *v_issue_imap_cmd(struct imap_store *ctx,
577 struct imap_cmd_cb *cb,
578 const char *fmt, va_list ap)
580 struct imap *imap = ctx->imap;
581 struct imap_cmd *cmd;
585 cmd = xmalloc(sizeof(struct imap_cmd));
586 nfvasprintf(&cmd->cmd, fmt, ap);
587 cmd->tag = ++imap->nexttag;
592 memset(&cmd->cb, 0, sizeof(cmd->cb));
594 while (imap->literal_pending)
595 get_cmd_result(ctx, NULL);
598 bufl = nfsnprintf(buf, sizeof(buf), "%d %s\r\n", cmd->tag, cmd->cmd);
600 bufl = nfsnprintf(buf, sizeof(buf), "%d %s{%d%s}\r\n",
601 cmd->tag, cmd->cmd, cmd->cb.dlen,
602 CAP(LITERALPLUS) ? "+" : "");
605 if (imap->num_in_progress)
606 printf("(%d in progress) ", imap->num_in_progress);
607 if (memcmp(cmd->cmd, "LOGIN", 5))
608 printf(">>> %s", buf);
610 printf(">>> %d LOGIN <user> <pass>\n", cmd->tag);
612 if (socket_write(&imap->buf.sock, buf, bufl) != bufl) {
620 if (CAP(LITERALPLUS)) {
621 n = socket_write(&imap->buf.sock, cmd->cb.data, cmd->cb.dlen);
623 if (n != cmd->cb.dlen ||
624 socket_write(&imap->buf.sock, "\r\n", 2) != 2) {
631 imap->literal_pending = 1;
632 } else if (cmd->cb.cont)
633 imap->literal_pending = 1;
635 *imap->in_progress_append = cmd;
636 imap->in_progress_append = &cmd->next;
637 imap->num_in_progress++;
641 __attribute__((format (printf, 3, 4)))
642 static struct imap_cmd *issue_imap_cmd(struct imap_store *ctx,
643 struct imap_cmd_cb *cb,
644 const char *fmt, ...)
646 struct imap_cmd *ret;
650 ret = v_issue_imap_cmd(ctx, cb, fmt, ap);
655 __attribute__((format (printf, 3, 4)))
656 static int imap_exec(struct imap_store *ctx, struct imap_cmd_cb *cb,
657 const char *fmt, ...)
660 struct imap_cmd *cmdp;
663 cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
668 return get_cmd_result(ctx, cmdp);
671 __attribute__((format (printf, 3, 4)))
672 static int imap_exec_m(struct imap_store *ctx, struct imap_cmd_cb *cb,
673 const char *fmt, ...)
676 struct imap_cmd *cmdp;
679 cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
682 return DRV_STORE_BAD;
684 switch (get_cmd_result(ctx, cmdp)) {
685 case RESP_BAD: return DRV_STORE_BAD;
686 case RESP_NO: return DRV_MSG_BAD;
687 default: return DRV_OK;
691 static int is_atom(struct imap_list *list)
693 return list && list->val && list->val != NIL && list->val != LIST;
696 static int is_list(struct imap_list *list)
698 return list && list->val == LIST;
701 static void free_list(struct imap_list *list)
703 struct imap_list *tmp;
705 for (; list; list = tmp) {
708 free_list(list->child);
709 else if (is_atom(list))
715 static int parse_imap_list_l(struct imap *imap, char **sp, struct imap_list **curp, int level)
717 struct imap_list *cur;
722 while (isspace((unsigned char)*s))
724 if (level && *s == ')') {
728 *curp = cur = xmalloc(sizeof(*cur));
730 cur->val = NULL; /* for clean bail */
735 if (parse_imap_list_l(imap, &s, &cur->child, level + 1))
737 } else if (imap && *s == '{') {
739 bytes = cur->len = strtol(s + 1, &s, 10);
743 s = cur->val = xmalloc(cur->len);
745 /* dump whats left over in the input buffer */
746 n = imap->buf.bytes - imap->buf.offset;
749 /* the entire message fit in the buffer */
752 memcpy(s, imap->buf.buf + imap->buf.offset, n);
756 /* mark that we used part of the buffer */
757 imap->buf.offset += n;
759 /* now read the rest of the message */
761 if ((n = socket_read(&imap->buf.sock, s, bytes)) <= 0)
767 if (buffer_gets(&imap->buf, &s))
769 } else if (*s == '"') {
773 for (; *s != '"'; s++)
778 cur->val = xmemdupz(p, cur->len);
782 for (; *s && !isspace((unsigned char)*s); s++)
783 if (level && *s == ')')
786 if (cur->len == 3 && !memcmp("NIL", p, 3))
789 cur->val = xmemdupz(p, cur->len);
806 static struct imap_list *parse_imap_list(struct imap *imap, char **sp)
808 struct imap_list *head;
810 if (!parse_imap_list_l(imap, sp, &head, 0))
816 static struct imap_list *parse_list(char **sp)
818 return parse_imap_list(NULL, sp);
821 static void parse_capability(struct imap *imap, char *cmd)
826 imap->caps = 0x80000000;
827 while ((arg = next_arg(&cmd)))
828 for (i = 0; i < ARRAY_SIZE(cap_list); i++)
829 if (!strcmp(cap_list[i], arg))
830 imap->caps |= 1 << i;
831 imap->rcaps = imap->caps;
834 static int parse_response_code(struct imap_store *ctx, struct imap_cmd_cb *cb,
837 struct imap *imap = ctx->imap;
841 return RESP_OK; /* no response code */
843 if (!(p = strchr(s, ']'))) {
844 fprintf(stderr, "IMAP error: malformed response code\n");
849 if (!strcmp("UIDVALIDITY", arg)) {
850 if (!(arg = next_arg(&s)) || !(ctx->gen.uidvalidity = atoi(arg))) {
851 fprintf(stderr, "IMAP error: malformed UIDVALIDITY status\n");
854 } else if (!strcmp("UIDNEXT", arg)) {
855 if (!(arg = next_arg(&s)) || !(imap->uidnext = atoi(arg))) {
856 fprintf(stderr, "IMAP error: malformed NEXTUID status\n");
859 } else if (!strcmp("CAPABILITY", arg)) {
860 parse_capability(imap, s);
861 } else if (!strcmp("ALERT", arg)) {
862 /* RFC2060 says that these messages MUST be displayed
865 for (; isspace((unsigned char)*p); p++);
866 fprintf(stderr, "*** IMAP ALERT *** %s\n", p);
867 } else if (cb && cb->ctx && !strcmp("APPENDUID", arg)) {
868 if (!(arg = next_arg(&s)) || !(ctx->gen.uidvalidity = atoi(arg)) ||
869 !(arg = next_arg(&s)) || !(*(int *)cb->ctx = atoi(arg))) {
870 fprintf(stderr, "IMAP error: malformed APPENDUID status\n");
877 static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd)
879 struct imap *imap = ctx->imap;
880 struct imap_cmd *cmdp, **pcmdp, *ncmdp;
881 char *cmd, *arg, *arg1, *p;
882 int n, resp, resp2, tag;
885 if (buffer_gets(&imap->buf, &cmd))
888 arg = next_arg(&cmd);
890 arg = next_arg(&cmd);
892 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
896 if (!strcmp("NAMESPACE", arg)) {
897 imap->ns_personal = parse_list(&cmd);
898 imap->ns_other = parse_list(&cmd);
899 imap->ns_shared = parse_list(&cmd);
900 } else if (!strcmp("OK", arg) || !strcmp("BAD", arg) ||
901 !strcmp("NO", arg) || !strcmp("BYE", arg)) {
902 if ((resp = parse_response_code(ctx, NULL, cmd)) != RESP_OK)
904 } else if (!strcmp("CAPABILITY", arg))
905 parse_capability(imap, cmd);
906 else if ((arg1 = next_arg(&cmd))) {
907 if (!strcmp("EXISTS", arg1))
908 ctx->gen.count = atoi(arg);
909 else if (!strcmp("RECENT", arg1))
910 ctx->gen.recent = atoi(arg);
912 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
915 } else if (!imap->in_progress) {
916 fprintf(stderr, "IMAP error: unexpected reply: %s %s\n", arg, cmd ? cmd : "");
918 } else if (*arg == '+') {
919 /* This can happen only with the last command underway, as
920 it enforces a round-trip. */
921 cmdp = (struct imap_cmd *)((char *)imap->in_progress_append -
922 offsetof(struct imap_cmd, next));
924 n = socket_write(&imap->buf.sock, cmdp->cb.data, cmdp->cb.dlen);
926 cmdp->cb.data = NULL;
927 if (n != (int)cmdp->cb.dlen)
929 } else if (cmdp->cb.cont) {
930 if (cmdp->cb.cont(ctx, cmdp, cmd))
933 fprintf(stderr, "IMAP error: unexpected command continuation request\n");
936 if (socket_write(&imap->buf.sock, "\r\n", 2) != 2)
939 imap->literal_pending = 0;
944 for (pcmdp = &imap->in_progress; (cmdp = *pcmdp); pcmdp = &cmdp->next)
945 if (cmdp->tag == tag)
947 fprintf(stderr, "IMAP error: unexpected tag %s\n", arg);
950 if (!(*pcmdp = cmdp->next))
951 imap->in_progress_append = pcmdp;
952 imap->num_in_progress--;
953 if (cmdp->cb.cont || cmdp->cb.data)
954 imap->literal_pending = 0;
955 arg = next_arg(&cmd);
956 if (!strcmp("OK", arg))
959 if (!strcmp("NO", arg)) {
960 if (cmdp->cb.create && cmd && (cmdp->cb.trycreate || !memcmp(cmd, "[TRYCREATE]", 11))) { /* SELECT, APPEND or UID COPY */
961 p = strchr(cmdp->cmd, '"');
962 if (!issue_imap_cmd(ctx, NULL, "CREATE \"%.*s\"", (int)(strchr(p + 1, '"') - p + 1), p)) {
966 /* not waiting here violates the spec, but a server that does not
967 grok this nonetheless violates it too. */
969 if (!(ncmdp = issue_imap_cmd(ctx, &cmdp->cb, "%s", cmdp->cmd))) {
976 return 0; /* ignored */
982 } else /*if (!strcmp("BAD", arg))*/
984 fprintf(stderr, "IMAP command '%s' returned response (%s) - %s\n",
985 memcmp(cmdp->cmd, "LOGIN", 5) ?
986 cmdp->cmd : "LOGIN <user> <pass>",
987 arg, cmd ? cmd : "");
989 if ((resp2 = parse_response_code(ctx, &cmdp->cb, cmd)) > resp)
993 cmdp->cb.done(ctx, cmdp, resp);
997 if (!tcmd || tcmd == cmdp)
1004 static void imap_close_server(struct imap_store *ictx)
1006 struct imap *imap = ictx->imap;
1008 if (imap->buf.sock.fd[0] != -1) {
1009 imap_exec(ictx, NULL, "LOGOUT");
1010 socket_shutdown(&imap->buf.sock);
1012 free_list(imap->ns_personal);
1013 free_list(imap->ns_other);
1014 free_list(imap->ns_shared);
1018 static void imap_close_store(struct store *ctx)
1020 imap_close_server((struct imap_store *)ctx);
1021 free_generic_messages(ctx->msgs);
1028 * hexchar() and cram() functions are based on the code from the isync
1029 * project (http://isync.sf.net/).
1031 static char hexchar(unsigned int b)
1033 return b < 10 ? '0' + b : 'a' + (b - 10);
1036 #define ENCODED_SIZE(n) (4*((n+2)/3))
1037 static char *cram(const char *challenge_64, const char *user, const char *pass)
1039 int i, resp_len, encoded_len, decoded_len;
1041 unsigned char hash[16];
1043 char *response, *response_64, *challenge;
1046 * length of challenge_64 (i.e. base-64 encoded string) is a good
1047 * enough upper bound for challenge (decoded result).
1049 encoded_len = strlen(challenge_64);
1050 challenge = xmalloc(encoded_len);
1051 decoded_len = EVP_DecodeBlock((unsigned char *)challenge,
1052 (unsigned char *)challenge_64, encoded_len);
1053 if (decoded_len < 0)
1054 die("invalid challenge %s", challenge_64);
1055 HMAC_Init(&hmac, (unsigned char *)pass, strlen(pass), EVP_md5());
1056 HMAC_Update(&hmac, (unsigned char *)challenge, decoded_len);
1057 HMAC_Final(&hmac, hash, NULL);
1058 HMAC_CTX_cleanup(&hmac);
1061 for (i = 0; i < 16; i++) {
1062 hex[2 * i] = hexchar((hash[i] >> 4) & 0xf);
1063 hex[2 * i + 1] = hexchar(hash[i] & 0xf);
1066 /* response: "<user> <digest in hex>" */
1067 resp_len = strlen(user) + 1 + strlen(hex) + 1;
1068 response = xmalloc(resp_len);
1069 sprintf(response, "%s %s", user, hex);
1071 response_64 = xmalloc(ENCODED_SIZE(resp_len) + 1);
1072 encoded_len = EVP_EncodeBlock((unsigned char *)response_64,
1073 (unsigned char *)response, resp_len);
1074 if (encoded_len < 0)
1075 die("EVP_EncodeBlock error");
1076 response_64[encoded_len] = '\0';
1077 return (char *)response_64;
1082 static char *cram(const char *challenge_64, const char *user, const char *pass)
1084 die("If you want to use CRAM-MD5 authenticate method, "
1085 "you have to build git-imap-send with OpenSSL library.");
1090 static int auth_cram_md5(struct imap_store *ctx, struct imap_cmd *cmd, const char *prompt)
1095 response = cram(prompt, server.user, server.pass);
1097 ret = socket_write(&ctx->imap->buf.sock, response, strlen(response));
1098 if (ret != strlen(response))
1099 return error("IMAP error: sending response failed");
1106 static struct store *imap_open_store(struct imap_server_conf *srvc)
1108 struct imap_store *ctx;
1111 int s = -1, preauth;
1113 ctx = xcalloc(sizeof(*ctx), 1);
1115 ctx->imap = imap = xcalloc(sizeof(*imap), 1);
1116 imap->buf.sock.fd[0] = imap->buf.sock.fd[1] = -1;
1117 imap->in_progress_append = &imap->in_progress;
1119 /* open connection to IMAP server */
1122 const char *argv[] = { srvc->tunnel, NULL };
1123 struct child_process tunnel = {NULL};
1125 imap_info("Starting tunnel '%s'... ", srvc->tunnel);
1128 tunnel.use_shell = 1;
1131 if (start_command(&tunnel))
1132 die("cannot start proxy %s", argv[0]);
1134 imap->buf.sock.fd[0] = tunnel.out;
1135 imap->buf.sock.fd[1] = tunnel.in;
1140 struct addrinfo hints, *ai0, *ai;
1144 snprintf(portstr, sizeof(portstr), "%d", srvc->port);
1146 memset(&hints, 0, sizeof(hints));
1147 hints.ai_socktype = SOCK_STREAM;
1148 hints.ai_protocol = IPPROTO_TCP;
1150 imap_info("Resolving %s... ", srvc->host);
1151 gai = getaddrinfo(srvc->host, portstr, &hints, &ai);
1153 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai));
1158 for (ai0 = ai; ai; ai = ai->ai_next) {
1159 char addr[NI_MAXHOST];
1161 s = socket(ai->ai_family, ai->ai_socktype,
1166 getnameinfo(ai->ai_addr, ai->ai_addrlen, addr,
1167 sizeof(addr), NULL, 0, NI_NUMERICHOST);
1168 imap_info("Connecting to [%s]:%s... ", addr, portstr);
1170 if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0) {
1182 struct sockaddr_in addr;
1184 memset(&addr, 0, sizeof(addr));
1185 addr.sin_port = htons(srvc->port);
1186 addr.sin_family = AF_INET;
1188 imap_info("Resolving %s... ", srvc->host);
1189 he = gethostbyname(srvc->host);
1191 perror("gethostbyname");
1196 addr.sin_addr.s_addr = *((int *) he->h_addr_list[0]);
1198 s = socket(PF_INET, SOCK_STREAM, 0);
1200 imap_info("Connecting to %s:%hu... ", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
1201 if (connect(s, (struct sockaddr *)&addr, sizeof(addr))) {
1208 fputs("Error: unable to connect to server.\n", stderr);
1212 imap->buf.sock.fd[0] = s;
1213 imap->buf.sock.fd[1] = dup(s);
1215 if (srvc->use_ssl &&
1216 ssl_socket_connect(&imap->buf.sock, 0, srvc->ssl_verify)) {
1223 /* read the greeting string */
1224 if (buffer_gets(&imap->buf, &rsp)) {
1225 fprintf(stderr, "IMAP error: no greeting response\n");
1228 arg = next_arg(&rsp);
1229 if (!arg || *arg != '*' || (arg = next_arg(&rsp)) == NULL) {
1230 fprintf(stderr, "IMAP error: invalid greeting response\n");
1234 if (!strcmp("PREAUTH", arg))
1236 else if (strcmp("OK", arg) != 0) {
1237 fprintf(stderr, "IMAP error: unknown greeting response\n");
1240 parse_response_code(ctx, NULL, rsp);
1241 if (!imap->caps && imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1246 if (!srvc->use_ssl && CAP(STARTTLS)) {
1247 if (imap_exec(ctx, NULL, "STARTTLS") != RESP_OK)
1249 if (ssl_socket_connect(&imap->buf.sock, 1,
1252 /* capabilities may have changed, so get the new capabilities */
1253 if (imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1257 imap_info("Logging in...\n");
1259 fprintf(stderr, "Skipping server %s, no user\n", srvc->host);
1263 struct strbuf prompt = STRBUF_INIT;
1264 strbuf_addf(&prompt, "Password (%s@%s): ", srvc->user, srvc->host);
1265 arg = git_getpass(prompt.buf);
1266 strbuf_release(&prompt);
1268 fprintf(stderr, "Skipping account %s@%s, no password\n", srvc->user, srvc->host);
1272 * getpass() returns a pointer to a static buffer. make a copy
1273 * for long term storage.
1275 srvc->pass = xstrdup(arg);
1278 fprintf(stderr, "Skipping account %s@%s, server forbids LOGIN\n", srvc->user, srvc->host);
1282 if (srvc->auth_method) {
1283 struct imap_cmd_cb cb;
1285 if (!strcmp(srvc->auth_method, "CRAM-MD5")) {
1286 if (!CAP(AUTH_CRAM_MD5)) {
1287 fprintf(stderr, "You specified"
1288 "CRAM-MD5 as authentication method, "
1289 "but %s doesn't support it.\n", srvc->host);
1294 memset(&cb, 0, sizeof(cb));
1295 cb.cont = auth_cram_md5;
1296 if (imap_exec(ctx, &cb, "AUTHENTICATE CRAM-MD5") != RESP_OK) {
1297 fprintf(stderr, "IMAP error: AUTHENTICATE CRAM-MD5 failed\n");
1301 fprintf(stderr, "Unknown authentication method:%s\n", srvc->host);
1305 if (!imap->buf.sock.ssl)
1306 imap_warn("*** IMAP Warning *** Password is being "
1307 "sent in the clear\n");
1308 if (imap_exec(ctx, NULL, "LOGIN \"%s\" \"%s\"", srvc->user, srvc->pass) != RESP_OK) {
1309 fprintf(stderr, "IMAP error: LOGIN failed\n");
1317 return (struct store *)ctx;
1320 imap_close_store(&ctx->gen);
1324 static int imap_make_flags(int flags, char *buf)
1329 for (i = d = 0; i < ARRAY_SIZE(Flags); i++)
1330 if (flags & (1 << i)) {
1333 for (s = Flags[i]; *s; s++)
1341 static void lf_to_crlf(struct msg_data *msg)
1344 int i, j, lfnum = 0;
1346 if (msg->data[0] == '\n')
1348 for (i = 1; i < msg->len; i++) {
1349 if (msg->data[i - 1] != '\r' && msg->data[i] == '\n')
1353 new = xmalloc(msg->len + lfnum);
1354 if (msg->data[0] == '\n') {
1360 new[0] = msg->data[0];
1364 for ( ; i < msg->len; i++) {
1365 if (msg->data[i] != '\n') {
1366 new[j++] = msg->data[i];
1369 if (msg->data[i - 1] != '\r')
1371 /* otherwise it already had CR before */
1379 static int imap_store_msg(struct store *gctx, struct msg_data *data)
1381 struct imap_store *ctx = (struct imap_store *)gctx;
1382 struct imap *imap = ctx->imap;
1383 struct imap_cmd_cb cb;
1384 const char *prefix, *box;
1389 memset(&cb, 0, sizeof(cb));
1391 cb.dlen = data->len;
1392 cb.data = xmalloc(cb.dlen);
1393 memcpy(cb.data, data->data, data->len);
1397 d = imap_make_flags(data->flags, flagstr);
1403 prefix = !strcmp(box, "INBOX") ? "" : ctx->prefix;
1405 ret = imap_exec_m(ctx, &cb, "APPEND \"%s%s\" %s", prefix, box, flagstr);
1406 imap->caps = imap->rcaps;
1414 static void encode_html_chars(struct strbuf *p)
1417 for (i = 0; i < p->len; i++) {
1418 if (p->buf[i] == '&')
1419 strbuf_splice(p, i, 1, "&", 5);
1420 if (p->buf[i] == '<')
1421 strbuf_splice(p, i, 1, "<", 4);
1422 if (p->buf[i] == '>')
1423 strbuf_splice(p, i, 1, ">", 4);
1424 if (p->buf[i] == '"')
1425 strbuf_splice(p, i, 1, """, 6);
1428 static void wrap_in_html(struct msg_data *msg)
1430 struct strbuf buf = STRBUF_INIT;
1431 struct strbuf **lines;
1433 static char *content_type = "Content-Type: text/html;\n";
1434 static char *pre_open = "<pre>\n";
1435 static char *pre_close = "</pre>\n";
1436 int added_header = 0;
1438 strbuf_attach(&buf, msg->data, msg->len, msg->len);
1439 lines = strbuf_split(&buf, '\n');
1440 strbuf_release(&buf);
1441 for (p = lines; *p; p++) {
1442 if (! added_header) {
1443 if ((*p)->len == 1 && *((*p)->buf) == '\n') {
1444 strbuf_addstr(&buf, content_type);
1445 strbuf_addbuf(&buf, *p);
1446 strbuf_addstr(&buf, pre_open);
1452 encode_html_chars(*p);
1453 strbuf_addbuf(&buf, *p);
1455 strbuf_addstr(&buf, pre_close);
1456 strbuf_list_free(lines);
1458 msg->data = strbuf_detach(&buf, NULL);
1461 #define CHUNKSIZE 0x1000
1463 static int read_message(FILE *f, struct msg_data *msg)
1465 struct strbuf buf = STRBUF_INIT;
1467 memset(msg, 0, sizeof(*msg));
1470 if (strbuf_fread(&buf, CHUNKSIZE, f) <= 0)
1475 msg->data = strbuf_detach(&buf, NULL);
1479 static int count_messages(struct msg_data *msg)
1482 char *p = msg->data;
1485 if (!prefixcmp(p, "From ")) {
1486 p = strstr(p+5, "\nFrom: ");
1488 p = strstr(p+7, "\nDate: ");
1490 p = strstr(p+7, "\nSubject: ");
1495 p = strstr(p+5, "\nFrom ");
1503 static int split_msg(struct msg_data *all_msgs, struct msg_data *msg, int *ofs)
1507 memset(msg, 0, sizeof *msg);
1508 if (*ofs >= all_msgs->len)
1511 data = &all_msgs->data[*ofs];
1512 msg->len = all_msgs->len - *ofs;
1514 if (msg->len < 5 || prefixcmp(data, "From "))
1517 p = strchr(data, '\n');
1525 p = strstr(data, "\nFrom ");
1527 msg->len = &p[1] - data;
1529 msg->data = xmemdupz(data, msg->len);
1534 static char *imap_folder;
1536 static int git_imap_config(const char *key, const char *val, void *cb)
1538 char imap_key[] = "imap.";
1540 if (strncmp(key, imap_key, sizeof imap_key - 1))
1543 key += sizeof imap_key - 1;
1545 /* check booleans first, and barf on others */
1546 if (!strcmp("sslverify", key))
1547 server.ssl_verify = git_config_bool(key, val);
1548 else if (!strcmp("preformattedhtml", key))
1549 server.use_html = git_config_bool(key, val);
1551 return config_error_nonbool(key);
1553 if (!strcmp("folder", key)) {
1554 imap_folder = xstrdup(val);
1555 } else if (!strcmp("host", key)) {
1556 if (!prefixcmp(val, "imap:"))
1558 else if (!prefixcmp(val, "imaps:")) {
1562 if (!prefixcmp(val, "//"))
1564 server.host = xstrdup(val);
1565 } else if (!strcmp("user", key))
1566 server.user = xstrdup(val);
1567 else if (!strcmp("pass", key))
1568 server.pass = xstrdup(val);
1569 else if (!strcmp("port", key))
1570 server.port = git_config_int(key, val);
1571 else if (!strcmp("tunnel", key))
1572 server.tunnel = xstrdup(val);
1573 else if (!strcmp("authmethod", key))
1574 server.auth_method = xstrdup(val);
1579 int main(int argc, char **argv)
1581 struct msg_data all_msgs, msg;
1582 struct store *ctx = NULL;
1588 git_extract_argv0_path(argv[0]);
1590 git_setup_gettext();
1593 usage(imap_send_usage);
1595 setup_git_directory_gently(&nongit_ok);
1596 git_config(git_imap_config, NULL);
1599 server.port = server.use_ssl ? 993 : 143;
1602 fprintf(stderr, "no imap store specified\n");
1606 if (!server.tunnel) {
1607 fprintf(stderr, "no imap host specified\n");
1610 server.host = "tunnel";
1613 /* read the messages */
1614 if (!read_message(stdin, &all_msgs)) {
1615 fprintf(stderr, "nothing to send\n");
1619 total = count_messages(&all_msgs);
1621 fprintf(stderr, "no messages to send\n");
1625 /* write it to the imap server */
1626 ctx = imap_open_store(&server);
1628 fprintf(stderr, "failed to open store\n");
1632 fprintf(stderr, "sending %d message%s\n", total, (total != 1) ? "s" : "");
1633 ctx->name = imap_folder;
1635 unsigned percent = n * 100 / total;
1636 fprintf(stderr, "%4u%% (%d/%d) done\r", percent, n, total);
1637 if (!split_msg(&all_msgs, &msg, &ofs))
1639 if (server.use_html)
1641 r = imap_store_msg(ctx, &msg);
1646 fprintf(stderr, "\n");
1648 imap_close_store(ctx);