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
26 #include "credential.h"
28 #include "run-command.h"
33 static const char imap_send_usage[] = "git imap-send < <mbox>";
37 #define DRV_MSG_BAD -1
38 #define DRV_BOX_BAD -2
39 #define DRV_STORE_BAD -3
41 static int Verbose, Quiet;
43 __attribute__((format (printf, 1, 2)))
44 static void imap_info(const char *, ...);
45 __attribute__((format (printf, 1, 2)))
46 static void imap_warn(const char *, ...);
48 static char *next_arg(char **);
50 __attribute__((format (printf, 3, 4)))
51 static int nfsnprintf(char *buf, int blen, const char *fmt, ...);
53 static int nfvasprintf(char **strp, const char *fmt, va_list ap)
58 len = vsnprintf(tmp, sizeof(tmp), fmt, ap);
60 die("Fatal: Out of memory");
61 if (len >= sizeof(tmp))
62 die("imap command overflow!");
63 *strp = xmemdupz(tmp, len);
67 struct imap_server_conf {
81 static struct imap_server_conf server = {
92 NULL, /* auth_method */
101 struct imap_socket sock;
110 int uidnext; /* from SELECT responses */
111 unsigned caps, rcaps; /* CAPABILITY results */
113 int nexttag, num_in_progress, literal_pending;
114 struct imap_cmd *in_progress, **in_progress_append;
115 struct imap_buffer buf; /* this is BIG, so put it last */
119 /* currently open mailbox */
120 const char *name; /* foreign! maybe preset? */
127 int (*cont)(struct imap_store *ctx, struct imap_cmd *cmd, const char *prompt);
128 void (*done)(struct imap_store *ctx, struct imap_cmd *cmd, int response);
136 struct imap_cmd *next;
137 struct imap_cmd_cb cb;
142 #define CAP(cap) (imap->caps & (1 << (cap)))
153 static const char *cap_list[] = {
166 static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd);
170 static void ssl_socket_perror(const char *func)
172 fprintf(stderr, "%s: %s\n", func, ERR_error_string(ERR_get_error(), NULL));
176 static void socket_perror(const char *func, struct imap_socket *sock, int ret)
180 int sslerr = SSL_get_error(sock->ssl, ret);
184 case SSL_ERROR_SYSCALL:
185 perror("SSL_connect");
188 ssl_socket_perror("SSL_connect");
197 fprintf(stderr, "%s: unexpected EOF\n", func);
202 static int ssl_socket_connect(struct imap_socket *sock, int use_tls_only, int verify)
204 fprintf(stderr, "SSL requested but SSL support not compiled in\n");
210 static int host_matches(const char *host, const char *pattern)
212 if (pattern[0] == '*' && pattern[1] == '.') {
214 if (!(host = strchr(host, '.')))
219 return *host && *pattern && !strcasecmp(host, pattern);
222 static int verify_hostname(X509 *cert, const char *hostname)
228 STACK_OF(GENERAL_NAME) *subj_alt_names;
230 /* try the DNS subjectAltNames */
232 if ((subj_alt_names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL))) {
233 int num_subj_alt_names = sk_GENERAL_NAME_num(subj_alt_names);
234 for (i = 0; !found && i < num_subj_alt_names; i++) {
235 GENERAL_NAME *subj_alt_name = sk_GENERAL_NAME_value(subj_alt_names, i);
236 if (subj_alt_name->type == GEN_DNS &&
237 strlen((const char *)subj_alt_name->d.ia5->data) == (size_t)subj_alt_name->d.ia5->length &&
238 host_matches(hostname, (const char *)(subj_alt_name->d.ia5->data)))
241 sk_GENERAL_NAME_pop_free(subj_alt_names, GENERAL_NAME_free);
246 /* try the common name */
247 if (!(subj = X509_get_subject_name(cert)))
248 return error("cannot get certificate subject");
249 if ((len = X509_NAME_get_text_by_NID(subj, NID_commonName, cname, sizeof(cname))) < 0)
250 return error("cannot get certificate common name");
251 if (strlen(cname) == (size_t)len && host_matches(hostname, cname))
253 return error("certificate owner '%s' does not match hostname '%s'",
257 static int ssl_socket_connect(struct imap_socket *sock, int use_tls_only, int verify)
259 #if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
260 const SSL_METHOD *meth;
269 SSL_load_error_strings();
272 meth = TLSv1_method();
274 meth = SSLv23_method();
277 ssl_socket_perror("SSLv23_method");
281 ctx = SSL_CTX_new(meth);
284 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
286 if (!SSL_CTX_set_default_verify_paths(ctx)) {
287 ssl_socket_perror("SSL_CTX_set_default_verify_paths");
290 sock->ssl = SSL_new(ctx);
292 ssl_socket_perror("SSL_new");
295 if (!SSL_set_rfd(sock->ssl, sock->fd[0])) {
296 ssl_socket_perror("SSL_set_rfd");
299 if (!SSL_set_wfd(sock->ssl, sock->fd[1])) {
300 ssl_socket_perror("SSL_set_wfd");
304 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
307 * OpenSSL does not document this function, but the implementation
308 * returns 1 on success, 0 on failure after calling SSLerr().
310 ret = SSL_set_tlsext_host_name(sock->ssl, server.host);
312 warning("SSL_set_tlsext_host_name(%s) failed.", server.host);
315 ret = SSL_connect(sock->ssl);
317 socket_perror("SSL_connect", sock, ret);
322 /* make sure the hostname matches that of the certificate */
323 cert = SSL_get_peer_certificate(sock->ssl);
325 return error("unable to get peer certificate.");
326 if (verify_hostname(cert, server.host) < 0)
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 int nfsnprintf(char *buf, int blen, const char *fmt, ...)
491 if (blen <= 0 || (unsigned)(ret = vsnprintf(buf, blen, fmt, va)) >= (unsigned)blen)
492 die("Fatal: buffer too small. Please report a bug.");
497 static struct imap_cmd *issue_imap_cmd(struct imap_store *ctx,
498 struct imap_cmd_cb *cb,
499 const char *fmt, va_list ap)
501 struct imap *imap = ctx->imap;
502 struct imap_cmd *cmd;
506 cmd = xmalloc(sizeof(struct imap_cmd));
507 nfvasprintf(&cmd->cmd, fmt, ap);
508 cmd->tag = ++imap->nexttag;
513 memset(&cmd->cb, 0, sizeof(cmd->cb));
515 while (imap->literal_pending)
516 get_cmd_result(ctx, NULL);
519 bufl = nfsnprintf(buf, sizeof(buf), "%d %s\r\n", cmd->tag, cmd->cmd);
521 bufl = nfsnprintf(buf, sizeof(buf), "%d %s{%d%s}\r\n",
522 cmd->tag, cmd->cmd, cmd->cb.dlen,
523 CAP(LITERALPLUS) ? "+" : "");
526 if (imap->num_in_progress)
527 printf("(%d in progress) ", imap->num_in_progress);
528 if (!starts_with(cmd->cmd, "LOGIN"))
529 printf(">>> %s", buf);
531 printf(">>> %d LOGIN <user> <pass>\n", cmd->tag);
533 if (socket_write(&imap->buf.sock, buf, bufl) != bufl) {
541 if (CAP(LITERALPLUS)) {
542 n = socket_write(&imap->buf.sock, cmd->cb.data, cmd->cb.dlen);
544 if (n != cmd->cb.dlen ||
545 socket_write(&imap->buf.sock, "\r\n", 2) != 2) {
552 imap->literal_pending = 1;
553 } else if (cmd->cb.cont)
554 imap->literal_pending = 1;
556 *imap->in_progress_append = cmd;
557 imap->in_progress_append = &cmd->next;
558 imap->num_in_progress++;
562 __attribute__((format (printf, 3, 4)))
563 static int imap_exec(struct imap_store *ctx, struct imap_cmd_cb *cb,
564 const char *fmt, ...)
567 struct imap_cmd *cmdp;
570 cmdp = issue_imap_cmd(ctx, cb, fmt, ap);
575 return get_cmd_result(ctx, cmdp);
578 __attribute__((format (printf, 3, 4)))
579 static int imap_exec_m(struct imap_store *ctx, struct imap_cmd_cb *cb,
580 const char *fmt, ...)
583 struct imap_cmd *cmdp;
586 cmdp = issue_imap_cmd(ctx, cb, fmt, ap);
589 return DRV_STORE_BAD;
591 switch (get_cmd_result(ctx, cmdp)) {
592 case RESP_BAD: return DRV_STORE_BAD;
593 case RESP_NO: return DRV_MSG_BAD;
594 default: return DRV_OK;
598 static int skip_imap_list_l(char **sp, int level)
603 while (isspace((unsigned char)*s))
605 if (level && *s == ')') {
612 if (skip_imap_list_l(&s, level + 1))
614 } else if (*s == '"') {
617 for (; *s != '"'; s++)
623 for (; *s && !isspace((unsigned char)*s); s++)
624 if (level && *s == ')')
640 static void skip_list(char **sp)
642 skip_imap_list_l(sp, 0);
645 static void parse_capability(struct imap *imap, char *cmd)
650 imap->caps = 0x80000000;
651 while ((arg = next_arg(&cmd)))
652 for (i = 0; i < ARRAY_SIZE(cap_list); i++)
653 if (!strcmp(cap_list[i], arg))
654 imap->caps |= 1 << i;
655 imap->rcaps = imap->caps;
658 static int parse_response_code(struct imap_store *ctx, struct imap_cmd_cb *cb,
661 struct imap *imap = ctx->imap;
665 return RESP_OK; /* no response code */
667 if (!(p = strchr(s, ']'))) {
668 fprintf(stderr, "IMAP error: malformed response code\n");
673 if (!strcmp("UIDVALIDITY", arg)) {
674 if (!(arg = next_arg(&s)) || !(ctx->uidvalidity = atoi(arg))) {
675 fprintf(stderr, "IMAP error: malformed UIDVALIDITY status\n");
678 } else if (!strcmp("UIDNEXT", arg)) {
679 if (!(arg = next_arg(&s)) || !(imap->uidnext = atoi(arg))) {
680 fprintf(stderr, "IMAP error: malformed NEXTUID status\n");
683 } else if (!strcmp("CAPABILITY", arg)) {
684 parse_capability(imap, s);
685 } else if (!strcmp("ALERT", arg)) {
686 /* RFC2060 says that these messages MUST be displayed
689 for (; isspace((unsigned char)*p); p++);
690 fprintf(stderr, "*** IMAP ALERT *** %s\n", p);
691 } else if (cb && cb->ctx && !strcmp("APPENDUID", arg)) {
692 if (!(arg = next_arg(&s)) || !(ctx->uidvalidity = atoi(arg)) ||
693 !(arg = next_arg(&s)) || !(*(int *)cb->ctx = atoi(arg))) {
694 fprintf(stderr, "IMAP error: malformed APPENDUID status\n");
701 static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd)
703 struct imap *imap = ctx->imap;
704 struct imap_cmd *cmdp, **pcmdp;
705 char *cmd, *arg, *arg1;
706 int n, resp, resp2, tag;
709 if (buffer_gets(&imap->buf, &cmd))
712 arg = next_arg(&cmd);
714 arg = next_arg(&cmd);
716 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
720 if (!strcmp("NAMESPACE", arg)) {
721 /* rfc2342 NAMESPACE response. */
722 skip_list(&cmd); /* Personal mailboxes */
723 skip_list(&cmd); /* Others' mailboxes */
724 skip_list(&cmd); /* Shared mailboxes */
725 } else if (!strcmp("OK", arg) || !strcmp("BAD", arg) ||
726 !strcmp("NO", arg) || !strcmp("BYE", arg)) {
727 if ((resp = parse_response_code(ctx, NULL, cmd)) != RESP_OK)
729 } else if (!strcmp("CAPABILITY", arg)) {
730 parse_capability(imap, cmd);
731 } else if ((arg1 = next_arg(&cmd))) {
733 * Unhandled response-data with at least two words.
736 * NEEDSWORK: Previously this case handled '<num> EXISTS'
737 * and '<num> RECENT' but as a probably-unintended side
738 * effect it ignores other unrecognized two-word
739 * responses. imap-send doesn't ever try to read
740 * messages or mailboxes these days, so consider
741 * eliminating this case.
744 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
747 } else if (!imap->in_progress) {
748 fprintf(stderr, "IMAP error: unexpected reply: %s %s\n", arg, cmd ? cmd : "");
750 } else if (*arg == '+') {
751 /* This can happen only with the last command underway, as
752 it enforces a round-trip. */
753 cmdp = (struct imap_cmd *)((char *)imap->in_progress_append -
754 offsetof(struct imap_cmd, next));
756 n = socket_write(&imap->buf.sock, cmdp->cb.data, cmdp->cb.dlen);
758 cmdp->cb.data = NULL;
759 if (n != (int)cmdp->cb.dlen)
761 } else if (cmdp->cb.cont) {
762 if (cmdp->cb.cont(ctx, cmdp, cmd))
765 fprintf(stderr, "IMAP error: unexpected command continuation request\n");
768 if (socket_write(&imap->buf.sock, "\r\n", 2) != 2)
771 imap->literal_pending = 0;
776 for (pcmdp = &imap->in_progress; (cmdp = *pcmdp); pcmdp = &cmdp->next)
777 if (cmdp->tag == tag)
779 fprintf(stderr, "IMAP error: unexpected tag %s\n", arg);
782 if (!(*pcmdp = cmdp->next))
783 imap->in_progress_append = pcmdp;
784 imap->num_in_progress--;
785 if (cmdp->cb.cont || cmdp->cb.data)
786 imap->literal_pending = 0;
787 arg = next_arg(&cmd);
788 if (!strcmp("OK", arg))
791 if (!strcmp("NO", arg))
793 else /*if (!strcmp("BAD", arg))*/
795 fprintf(stderr, "IMAP command '%s' returned response (%s) - %s\n",
796 !starts_with(cmdp->cmd, "LOGIN") ?
797 cmdp->cmd : "LOGIN <user> <pass>",
798 arg, cmd ? cmd : "");
800 if ((resp2 = parse_response_code(ctx, &cmdp->cb, cmd)) > resp)
803 cmdp->cb.done(ctx, cmdp, resp);
807 if (!tcmd || tcmd == cmdp)
814 static void imap_close_server(struct imap_store *ictx)
816 struct imap *imap = ictx->imap;
818 if (imap->buf.sock.fd[0] != -1) {
819 imap_exec(ictx, NULL, "LOGOUT");
820 socket_shutdown(&imap->buf.sock);
825 static void imap_close_store(struct imap_store *ctx)
827 imap_close_server(ctx);
834 * hexchar() and cram() functions are based on the code from the isync
835 * project (http://isync.sf.net/).
837 static char hexchar(unsigned int b)
839 return b < 10 ? '0' + b : 'a' + (b - 10);
842 #define ENCODED_SIZE(n) (4*((n+2)/3))
843 static char *cram(const char *challenge_64, const char *user, const char *pass)
845 int i, resp_len, encoded_len, decoded_len;
847 unsigned char hash[16];
849 char *response, *response_64, *challenge;
852 * length of challenge_64 (i.e. base-64 encoded string) is a good
853 * enough upper bound for challenge (decoded result).
855 encoded_len = strlen(challenge_64);
856 challenge = xmalloc(encoded_len);
857 decoded_len = EVP_DecodeBlock((unsigned char *)challenge,
858 (unsigned char *)challenge_64, encoded_len);
860 die("invalid challenge %s", challenge_64);
861 HMAC_Init(&hmac, (unsigned char *)pass, strlen(pass), EVP_md5());
862 HMAC_Update(&hmac, (unsigned char *)challenge, decoded_len);
863 HMAC_Final(&hmac, hash, NULL);
864 HMAC_CTX_cleanup(&hmac);
867 for (i = 0; i < 16; i++) {
868 hex[2 * i] = hexchar((hash[i] >> 4) & 0xf);
869 hex[2 * i + 1] = hexchar(hash[i] & 0xf);
872 /* response: "<user> <digest in hex>" */
873 resp_len = strlen(user) + 1 + strlen(hex) + 1;
874 response = xmalloc(resp_len);
875 sprintf(response, "%s %s", user, hex);
877 response_64 = xmalloc(ENCODED_SIZE(resp_len) + 1);
878 encoded_len = EVP_EncodeBlock((unsigned char *)response_64,
879 (unsigned char *)response, resp_len);
881 die("EVP_EncodeBlock error");
882 response_64[encoded_len] = '\0';
883 return (char *)response_64;
888 static char *cram(const char *challenge_64, const char *user, const char *pass)
890 die("If you want to use CRAM-MD5 authenticate method, "
891 "you have to build git-imap-send with OpenSSL library.");
896 static int auth_cram_md5(struct imap_store *ctx, struct imap_cmd *cmd, const char *prompt)
901 response = cram(prompt, server.user, server.pass);
903 ret = socket_write(&ctx->imap->buf.sock, response, strlen(response));
904 if (ret != strlen(response))
905 return error("IMAP error: sending response failed");
912 static struct imap_store *imap_open_store(struct imap_server_conf *srvc, char *folder)
914 struct credential cred = CREDENTIAL_INIT;
915 struct imap_store *ctx;
920 ctx = xcalloc(1, sizeof(*ctx));
922 ctx->imap = imap = xcalloc(1, sizeof(*imap));
923 imap->buf.sock.fd[0] = imap->buf.sock.fd[1] = -1;
924 imap->in_progress_append = &imap->in_progress;
926 /* open connection to IMAP server */
929 struct child_process tunnel = CHILD_PROCESS_INIT;
931 imap_info("Starting tunnel '%s'... ", srvc->tunnel);
933 argv_array_push(&tunnel.args, srvc->tunnel);
934 tunnel.use_shell = 1;
937 if (start_command(&tunnel))
938 die("cannot start proxy %s", srvc->tunnel);
940 imap->buf.sock.fd[0] = tunnel.out;
941 imap->buf.sock.fd[1] = tunnel.in;
946 struct addrinfo hints, *ai0, *ai;
950 snprintf(portstr, sizeof(portstr), "%d", srvc->port);
952 memset(&hints, 0, sizeof(hints));
953 hints.ai_socktype = SOCK_STREAM;
954 hints.ai_protocol = IPPROTO_TCP;
956 imap_info("Resolving %s... ", srvc->host);
957 gai = getaddrinfo(srvc->host, portstr, &hints, &ai);
959 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai));
964 for (ai0 = ai; ai; ai = ai->ai_next) {
965 char addr[NI_MAXHOST];
967 s = socket(ai->ai_family, ai->ai_socktype,
972 getnameinfo(ai->ai_addr, ai->ai_addrlen, addr,
973 sizeof(addr), NULL, 0, NI_NUMERICHOST);
974 imap_info("Connecting to [%s]:%s... ", addr, portstr);
976 if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0) {
988 struct sockaddr_in addr;
990 memset(&addr, 0, sizeof(addr));
991 addr.sin_port = htons(srvc->port);
992 addr.sin_family = AF_INET;
994 imap_info("Resolving %s... ", srvc->host);
995 he = gethostbyname(srvc->host);
997 perror("gethostbyname");
1002 addr.sin_addr.s_addr = *((int *) he->h_addr_list[0]);
1004 s = socket(PF_INET, SOCK_STREAM, 0);
1006 imap_info("Connecting to %s:%hu... ", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
1007 if (connect(s, (struct sockaddr *)&addr, sizeof(addr))) {
1014 fputs("Error: unable to connect to server.\n", stderr);
1018 imap->buf.sock.fd[0] = s;
1019 imap->buf.sock.fd[1] = dup(s);
1021 if (srvc->use_ssl &&
1022 ssl_socket_connect(&imap->buf.sock, 0, srvc->ssl_verify)) {
1029 /* read the greeting string */
1030 if (buffer_gets(&imap->buf, &rsp)) {
1031 fprintf(stderr, "IMAP error: no greeting response\n");
1034 arg = next_arg(&rsp);
1035 if (!arg || *arg != '*' || (arg = next_arg(&rsp)) == NULL) {
1036 fprintf(stderr, "IMAP error: invalid greeting response\n");
1040 if (!strcmp("PREAUTH", arg))
1042 else if (strcmp("OK", arg) != 0) {
1043 fprintf(stderr, "IMAP error: unknown greeting response\n");
1046 parse_response_code(ctx, NULL, rsp);
1047 if (!imap->caps && imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1052 if (!srvc->use_ssl && CAP(STARTTLS)) {
1053 if (imap_exec(ctx, NULL, "STARTTLS") != RESP_OK)
1055 if (ssl_socket_connect(&imap->buf.sock, 1,
1058 /* capabilities may have changed, so get the new capabilities */
1059 if (imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1063 imap_info("Logging in...\n");
1064 if (!srvc->user || !srvc->pass) {
1065 cred.protocol = xstrdup(srvc->use_ssl ? "imaps" : "imap");
1066 cred.host = xstrdup(srvc->host);
1069 cred.username = xstrdup(srvc->user);
1071 cred.password = xstrdup(srvc->pass);
1073 credential_fill(&cred);
1076 srvc->user = xstrdup(cred.username);
1078 srvc->pass = xstrdup(cred.password);
1082 fprintf(stderr, "Skipping account %s@%s, server forbids LOGIN\n", srvc->user, srvc->host);
1086 if (srvc->auth_method) {
1087 struct imap_cmd_cb cb;
1089 if (!strcmp(srvc->auth_method, "CRAM-MD5")) {
1090 if (!CAP(AUTH_CRAM_MD5)) {
1091 fprintf(stderr, "You specified"
1092 "CRAM-MD5 as authentication method, "
1093 "but %s doesn't support it.\n", srvc->host);
1098 memset(&cb, 0, sizeof(cb));
1099 cb.cont = auth_cram_md5;
1100 if (imap_exec(ctx, &cb, "AUTHENTICATE CRAM-MD5") != RESP_OK) {
1101 fprintf(stderr, "IMAP error: AUTHENTICATE CRAM-MD5 failed\n");
1105 fprintf(stderr, "Unknown authentication method:%s\n", srvc->host);
1109 if (!imap->buf.sock.ssl)
1110 imap_warn("*** IMAP Warning *** Password is being "
1111 "sent in the clear\n");
1112 if (imap_exec(ctx, NULL, "LOGIN \"%s\" \"%s\"", srvc->user, srvc->pass) != RESP_OK) {
1113 fprintf(stderr, "IMAP error: LOGIN failed\n");
1120 credential_approve(&cred);
1121 credential_clear(&cred);
1123 /* check the target mailbox exists */
1125 switch (imap_exec(ctx, NULL, "EXAMINE \"%s\"", ctx->name)) {
1130 fprintf(stderr, "IMAP error: could not check mailbox\n");
1133 if (imap_exec(ctx, NULL, "CREATE \"%s\"", ctx->name) == RESP_OK) {
1134 imap_info("Created missing mailbox\n");
1136 fprintf(stderr, "IMAP error: could not create missing mailbox\n");
1147 credential_reject(&cred);
1148 credential_clear(&cred);
1151 imap_close_store(ctx);
1156 * Insert CR characters as necessary in *msg to ensure that every LF
1157 * character in *msg is preceded by a CR.
1159 static void lf_to_crlf(struct strbuf *msg)
1165 /* First pass: tally, in j, the size of the new string: */
1166 for (i = j = 0, lastc = '\0'; i < msg->len; i++) {
1167 if (msg->buf[i] == '\n' && lastc != '\r')
1168 j++; /* a CR will need to be added here */
1169 lastc = msg->buf[i];
1173 new = xmalloc(j + 1);
1176 * Second pass: write the new string. Note that this loop is
1177 * otherwise identical to the first pass.
1179 for (i = j = 0, lastc = '\0'; i < msg->len; i++) {
1180 if (msg->buf[i] == '\n' && lastc != '\r')
1182 lastc = new[j++] = msg->buf[i];
1184 strbuf_attach(msg, new, j, j + 1);
1188 * Store msg to IMAP. Also detach and free the data from msg->data,
1189 * leaving msg->data empty.
1191 static int imap_store_msg(struct imap_store *ctx, struct strbuf *msg)
1193 struct imap *imap = ctx->imap;
1194 struct imap_cmd_cb cb;
1195 const char *prefix, *box;
1199 memset(&cb, 0, sizeof(cb));
1202 cb.data = strbuf_detach(msg, NULL);
1205 prefix = !strcmp(box, "INBOX") ? "" : ctx->prefix;
1206 ret = imap_exec_m(ctx, &cb, "APPEND \"%s%s\" ", prefix, box);
1207 imap->caps = imap->rcaps;
1214 static void wrap_in_html(struct strbuf *msg)
1216 struct strbuf buf = STRBUF_INIT;
1217 static char *content_type = "Content-Type: text/html;\n";
1218 static char *pre_open = "<pre>\n";
1219 static char *pre_close = "</pre>\n";
1220 const char *body = strstr(msg->buf, "\n\n");
1223 return; /* Headers but no body; no wrapping needed */
1227 strbuf_add(&buf, msg->buf, body - msg->buf - 1);
1228 strbuf_addstr(&buf, content_type);
1229 strbuf_addch(&buf, '\n');
1230 strbuf_addstr(&buf, pre_open);
1231 strbuf_addstr_xml_quoted(&buf, body);
1232 strbuf_addstr(&buf, pre_close);
1234 strbuf_release(msg);
1238 #define CHUNKSIZE 0x1000
1240 static int read_message(FILE *f, struct strbuf *all_msgs)
1243 if (strbuf_fread(all_msgs, CHUNKSIZE, f) <= 0)
1247 return ferror(f) ? -1 : 0;
1250 static int count_messages(struct strbuf *all_msgs)
1253 char *p = all_msgs->buf;
1256 if (starts_with(p, "From ")) {
1257 p = strstr(p+5, "\nFrom: ");
1259 p = strstr(p+7, "\nDate: ");
1261 p = strstr(p+7, "\nSubject: ");
1266 p = strstr(p+5, "\nFrom ");
1275 * Copy the next message from all_msgs, starting at offset *ofs, to
1276 * msg. Update *ofs to the start of the following message. Return
1277 * true iff a message was successfully copied.
1279 static int split_msg(struct strbuf *all_msgs, struct strbuf *msg, int *ofs)
1284 if (*ofs >= all_msgs->len)
1287 data = &all_msgs->buf[*ofs];
1288 len = all_msgs->len - *ofs;
1290 if (len < 5 || !starts_with(data, "From "))
1293 p = strchr(data, '\n');
1301 p = strstr(data, "\nFrom ");
1305 strbuf_add(msg, data, len);
1310 static void git_imap_config(void)
1312 const char *val = NULL;
1314 git_config_get_bool("imap.sslverify", &server.ssl_verify);
1315 git_config_get_bool("imap.preformattedhtml", &server.use_html);
1316 git_config_get_string("imap.folder", &server.folder);
1318 if (!git_config_get_value("imap.host", &val)) {
1320 git_die_config("imap.host", "Missing value for 'imap.host'");
1322 if (starts_with(val, "imap:"))
1324 else if (starts_with(val, "imaps:")) {
1328 if (starts_with(val, "//"))
1330 server.host = xstrdup(val);
1334 git_config_get_string("imap.user", &server.user);
1335 git_config_get_string("imap.pass", &server.pass);
1336 git_config_get_int("imap.port", &server.port);
1337 git_config_get_string("imap.tunnel", &server.tunnel);
1338 git_config_get_string("imap.authmethod", &server.auth_method);
1341 int main(int argc, char **argv)
1343 struct strbuf all_msgs = STRBUF_INIT;
1344 struct strbuf msg = STRBUF_INIT;
1345 struct imap_store *ctx = NULL;
1351 git_extract_argv0_path(argv[0]);
1353 git_setup_gettext();
1356 usage(imap_send_usage);
1358 setup_git_directory_gently(&nongit_ok);
1362 server.port = server.use_ssl ? 993 : 143;
1364 if (!server.folder) {
1365 fprintf(stderr, "no imap store specified\n");
1369 if (!server.tunnel) {
1370 fprintf(stderr, "no imap host specified\n");
1373 server.host = "tunnel";
1376 /* read the messages */
1377 if (read_message(stdin, &all_msgs)) {
1378 fprintf(stderr, "error reading input\n");
1382 if (all_msgs.len == 0) {
1383 fprintf(stderr, "nothing to send\n");
1387 total = count_messages(&all_msgs);
1389 fprintf(stderr, "no messages to send\n");
1393 /* write it to the imap server */
1394 ctx = imap_open_store(&server, server.folder);
1396 fprintf(stderr, "failed to open store\n");
1400 fprintf(stderr, "sending %d message%s\n", total, (total != 1) ? "s" : "");
1402 unsigned percent = n * 100 / total;
1404 fprintf(stderr, "%4u%% (%d/%d) done\r", percent, n, total);
1405 if (!split_msg(&all_msgs, &msg, &ofs))
1407 if (server.use_html)
1409 r = imap_store_msg(ctx, &msg);
1414 fprintf(stderr, "\n");
1416 imap_close_store(ctx);