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"
34 const char *path; /* should this be here? its interpretation is driver-specific */
37 unsigned max_size; /* off_t is overkill */
38 unsigned trash_remote_new:1, trash_only_new:1;
42 struct string_list *next;
47 struct channel_conf *next;
49 struct store_conf *master, *slave;
50 char *master_name, *slave_name;
52 struct string_list *patterns;
54 unsigned max_messages; /* for slave only */
58 struct group_conf *next;
60 struct string_list *channels;
63 /* For message->status */
64 #define M_RECENT (1<<0) /* unsyncable flag; maildir_* depend on this being 1<<0 */
65 #define M_DEAD (1<<1) /* expunged */
66 #define M_FLAGS (1<<2) /* flags fetched */
70 /* struct string_list *keywords; */
71 size_t size; /* zero implies "not fetched" */
73 unsigned char flags, status;
77 struct store_conf *conf; /* foreign */
79 /* currently open mailbox */
80 const char *name; /* foreign! maybe preset? */
82 struct message *msgs; /* own */
84 unsigned char opts; /* maybe preset? */
85 /* note that the following do _not_ reflect stats from msgs, but mailbox totals */
86 int count; /* # of messages */
87 int recent; /* # of recent messages - don't trust this beyond the initial read */
97 static const char imap_send_usage[] = "git imap-send < <mbox>";
101 #define DRV_MSG_BAD -1
102 #define DRV_BOX_BAD -2
103 #define DRV_STORE_BAD -3
105 static int Verbose, Quiet;
107 __attribute__((format (printf, 1, 2)))
108 static void imap_info(const char *, ...);
109 __attribute__((format (printf, 1, 2)))
110 static void imap_warn(const char *, ...);
112 static char *next_arg(char **);
114 static void free_generic_messages(struct message *);
116 __attribute__((format (printf, 3, 4)))
117 static int nfsnprintf(char *buf, int blen, const char *fmt, ...);
119 static int nfvasprintf(char **strp, const char *fmt, va_list ap)
124 len = vsnprintf(tmp, sizeof(tmp), fmt, ap);
126 die("Fatal: Out of memory");
127 if (len >= sizeof(tmp))
128 die("imap command overflow!");
129 *strp = xmemdupz(tmp, len);
133 struct imap_server_conf {
145 struct imap_store_conf {
146 struct store_conf gen;
147 struct imap_server_conf *server;
148 unsigned use_namespace:1;
151 #define NIL (void *)0x1
152 #define LIST (void *)0x2
155 struct imap_list *next, *child;
166 struct imap_socket sock;
175 int uidnext; /* from SELECT responses */
176 struct imap_list *ns_personal, *ns_other, *ns_shared; /* NAMESPACE info */
177 unsigned caps, rcaps; /* CAPABILITY results */
179 int nexttag, num_in_progress, literal_pending;
180 struct imap_cmd *in_progress, **in_progress_append;
181 struct imap_buffer buf; /* this is BIG, so put it last */
189 unsigned /*currentnc:1,*/ trashnc:1;
193 int (*cont)(struct imap_store *ctx, struct imap_cmd *cmd, const char *prompt);
194 void (*done)(struct imap_store *ctx, struct imap_cmd *cmd, int response);
199 unsigned create:1, trycreate:1;
203 struct imap_cmd *next;
204 struct imap_cmd_cb cb;
209 #define CAP(cap) (imap->caps & (1 << (cap)))
219 static const char *cap_list[] = {
231 static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd);
234 static const char *Flags[] = {
243 static void ssl_socket_perror(const char *func)
245 fprintf(stderr, "%s: %s\n", func, ERR_error_string(ERR_get_error(), NULL));
249 static void socket_perror(const char *func, struct imap_socket *sock, int ret)
253 int sslerr = SSL_get_error(sock->ssl, ret);
257 case SSL_ERROR_SYSCALL:
258 perror("SSL_connect");
261 ssl_socket_perror("SSL_connect");
270 fprintf(stderr, "%s: unexpected EOF\n", func);
274 static int ssl_socket_connect(struct imap_socket *sock, int use_tls_only, int verify)
277 fprintf(stderr, "SSL requested but SSL support not compiled in\n");
280 #if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
281 const SSL_METHOD *meth;
289 SSL_load_error_strings();
292 meth = TLSv1_method();
294 meth = SSLv23_method();
297 ssl_socket_perror("SSLv23_method");
301 ctx = SSL_CTX_new(meth);
304 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
306 if (!SSL_CTX_set_default_verify_paths(ctx)) {
307 ssl_socket_perror("SSL_CTX_set_default_verify_paths");
310 sock->ssl = SSL_new(ctx);
312 ssl_socket_perror("SSL_new");
315 if (!SSL_set_rfd(sock->ssl, sock->fd[0])) {
316 ssl_socket_perror("SSL_set_rfd");
319 if (!SSL_set_wfd(sock->ssl, sock->fd[1])) {
320 ssl_socket_perror("SSL_set_wfd");
324 ret = SSL_connect(sock->ssl);
326 socket_perror("SSL_connect", sock, ret);
334 static int socket_read(struct imap_socket *sock, char *buf, int len)
339 n = SSL_read(sock->ssl, buf, len);
342 n = xread(sock->fd[0], buf, len);
344 socket_perror("read", sock, n);
347 sock->fd[0] = sock->fd[1] = -1;
352 static int socket_write(struct imap_socket *sock, const char *buf, int len)
357 n = SSL_write(sock->ssl, buf, len);
360 n = write_in_full(sock->fd[1], buf, len);
362 socket_perror("write", sock, n);
365 sock->fd[0] = sock->fd[1] = -1;
370 static void socket_shutdown(struct imap_socket *sock)
374 SSL_shutdown(sock->ssl);
382 /* simple line buffering */
383 static int buffer_gets(struct imap_buffer *b, char **s)
386 int start = b->offset;
391 /* make sure we have enough data to read the \r\n sequence */
392 if (b->offset + 1 >= b->bytes) {
394 /* shift down used bytes */
397 assert(start <= b->bytes);
398 n = b->bytes - start;
401 memmove(b->buf, b->buf + start, n);
407 n = socket_read(&b->sock, b->buf + b->bytes,
408 sizeof(b->buf) - b->bytes);
416 if (b->buf[b->offset] == '\r') {
417 assert(b->offset + 1 < b->bytes);
418 if (b->buf[b->offset + 1] == '\n') {
419 b->buf[b->offset] = 0; /* terminate the string */
420 b->offset += 2; /* next line */
432 static void imap_info(const char *msg, ...)
444 static void imap_warn(const char *msg, ...)
450 vfprintf(stderr, msg, va);
455 static char *next_arg(char **s)
461 while (isspace((unsigned char) **s))
470 *s = strchr(*s, '"');
473 while (**s && !isspace((unsigned char) **s))
485 static void free_generic_messages(struct message *msgs)
487 struct message *tmsg;
489 for (; msgs; msgs = tmsg) {
495 static int nfsnprintf(char *buf, int blen, const char *fmt, ...)
501 if (blen <= 0 || (unsigned)(ret = vsnprintf(buf, blen, fmt, va)) >= (unsigned)blen)
502 die("Fatal: buffer too small. Please report a bug.");
507 static struct imap_cmd *v_issue_imap_cmd(struct imap_store *ctx,
508 struct imap_cmd_cb *cb,
509 const char *fmt, va_list ap)
511 struct imap *imap = ctx->imap;
512 struct imap_cmd *cmd;
516 cmd = xmalloc(sizeof(struct imap_cmd));
517 nfvasprintf(&cmd->cmd, fmt, ap);
518 cmd->tag = ++imap->nexttag;
523 memset(&cmd->cb, 0, sizeof(cmd->cb));
525 while (imap->literal_pending)
526 get_cmd_result(ctx, NULL);
528 bufl = nfsnprintf(buf, sizeof(buf), cmd->cb.data ? CAP(LITERALPLUS) ?
529 "%d %s{%d+}\r\n" : "%d %s{%d}\r\n" : "%d %s\r\n",
530 cmd->tag, cmd->cmd, cmd->cb.dlen);
532 if (imap->num_in_progress)
533 printf("(%d in progress) ", imap->num_in_progress);
534 if (memcmp(cmd->cmd, "LOGIN", 5))
535 printf(">>> %s", buf);
537 printf(">>> %d LOGIN <user> <pass>\n", cmd->tag);
539 if (socket_write(&imap->buf.sock, buf, bufl) != bufl) {
547 if (CAP(LITERALPLUS)) {
548 n = socket_write(&imap->buf.sock, cmd->cb.data, cmd->cb.dlen);
550 if (n != cmd->cb.dlen ||
551 socket_write(&imap->buf.sock, "\r\n", 2) != 2) {
558 imap->literal_pending = 1;
559 } else if (cmd->cb.cont)
560 imap->literal_pending = 1;
562 *imap->in_progress_append = cmd;
563 imap->in_progress_append = &cmd->next;
564 imap->num_in_progress++;
568 __attribute__((format (printf, 3, 4)))
569 static struct imap_cmd *issue_imap_cmd(struct imap_store *ctx,
570 struct imap_cmd_cb *cb,
571 const char *fmt, ...)
573 struct imap_cmd *ret;
577 ret = v_issue_imap_cmd(ctx, cb, fmt, ap);
582 __attribute__((format (printf, 3, 4)))
583 static int imap_exec(struct imap_store *ctx, struct imap_cmd_cb *cb,
584 const char *fmt, ...)
587 struct imap_cmd *cmdp;
590 cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
595 return get_cmd_result(ctx, cmdp);
598 __attribute__((format (printf, 3, 4)))
599 static int imap_exec_m(struct imap_store *ctx, struct imap_cmd_cb *cb,
600 const char *fmt, ...)
603 struct imap_cmd *cmdp;
606 cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
609 return DRV_STORE_BAD;
611 switch (get_cmd_result(ctx, cmdp)) {
612 case RESP_BAD: return DRV_STORE_BAD;
613 case RESP_NO: return DRV_MSG_BAD;
614 default: return DRV_OK;
618 static int is_atom(struct imap_list *list)
620 return list && list->val && list->val != NIL && list->val != LIST;
623 static int is_list(struct imap_list *list)
625 return list && list->val == LIST;
628 static void free_list(struct imap_list *list)
630 struct imap_list *tmp;
632 for (; list; list = tmp) {
635 free_list(list->child);
636 else if (is_atom(list))
642 static int parse_imap_list_l(struct imap *imap, char **sp, struct imap_list **curp, int level)
644 struct imap_list *cur;
649 while (isspace((unsigned char)*s))
651 if (level && *s == ')') {
655 *curp = cur = xmalloc(sizeof(*cur));
657 cur->val = NULL; /* for clean bail */
662 if (parse_imap_list_l(imap, &s, &cur->child, level + 1))
664 } else if (imap && *s == '{') {
666 bytes = cur->len = strtol(s + 1, &s, 10);
670 s = cur->val = xmalloc(cur->len);
672 /* dump whats left over in the input buffer */
673 n = imap->buf.bytes - imap->buf.offset;
676 /* the entire message fit in the buffer */
679 memcpy(s, imap->buf.buf + imap->buf.offset, n);
683 /* mark that we used part of the buffer */
684 imap->buf.offset += n;
686 /* now read the rest of the message */
688 if ((n = socket_read(&imap->buf.sock, s, bytes)) <= 0)
694 if (buffer_gets(&imap->buf, &s))
696 } else if (*s == '"') {
700 for (; *s != '"'; s++)
705 cur->val = xmemdupz(p, cur->len);
709 for (; *s && !isspace((unsigned char)*s); s++)
710 if (level && *s == ')')
713 if (cur->len == 3 && !memcmp("NIL", p, 3))
716 cur->val = xmemdupz(p, cur->len);
733 static struct imap_list *parse_imap_list(struct imap *imap, char **sp)
735 struct imap_list *head;
737 if (!parse_imap_list_l(imap, sp, &head, 0))
743 static struct imap_list *parse_list(char **sp)
745 return parse_imap_list(NULL, sp);
748 static void parse_capability(struct imap *imap, char *cmd)
753 imap->caps = 0x80000000;
754 while ((arg = next_arg(&cmd)))
755 for (i = 0; i < ARRAY_SIZE(cap_list); i++)
756 if (!strcmp(cap_list[i], arg))
757 imap->caps |= 1 << i;
758 imap->rcaps = imap->caps;
761 static int parse_response_code(struct imap_store *ctx, struct imap_cmd_cb *cb,
764 struct imap *imap = ctx->imap;
768 return RESP_OK; /* no response code */
770 if (!(p = strchr(s, ']'))) {
771 fprintf(stderr, "IMAP error: malformed response code\n");
776 if (!strcmp("UIDVALIDITY", arg)) {
777 if (!(arg = next_arg(&s)) || !(ctx->gen.uidvalidity = atoi(arg))) {
778 fprintf(stderr, "IMAP error: malformed UIDVALIDITY status\n");
781 } else if (!strcmp("UIDNEXT", arg)) {
782 if (!(arg = next_arg(&s)) || !(imap->uidnext = atoi(arg))) {
783 fprintf(stderr, "IMAP error: malformed NEXTUID status\n");
786 } else if (!strcmp("CAPABILITY", arg)) {
787 parse_capability(imap, s);
788 } else if (!strcmp("ALERT", arg)) {
789 /* RFC2060 says that these messages MUST be displayed
792 for (; isspace((unsigned char)*p); p++);
793 fprintf(stderr, "*** IMAP ALERT *** %s\n", p);
794 } else if (cb && cb->ctx && !strcmp("APPENDUID", arg)) {
795 if (!(arg = next_arg(&s)) || !(ctx->gen.uidvalidity = atoi(arg)) ||
796 !(arg = next_arg(&s)) || !(*(int *)cb->ctx = atoi(arg))) {
797 fprintf(stderr, "IMAP error: malformed APPENDUID status\n");
804 static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd)
806 struct imap *imap = ctx->imap;
807 struct imap_cmd *cmdp, **pcmdp, *ncmdp;
808 char *cmd, *arg, *arg1, *p;
809 int n, resp, resp2, tag;
812 if (buffer_gets(&imap->buf, &cmd))
815 arg = next_arg(&cmd);
817 arg = next_arg(&cmd);
819 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
823 if (!strcmp("NAMESPACE", arg)) {
824 imap->ns_personal = parse_list(&cmd);
825 imap->ns_other = parse_list(&cmd);
826 imap->ns_shared = parse_list(&cmd);
827 } else if (!strcmp("OK", arg) || !strcmp("BAD", arg) ||
828 !strcmp("NO", arg) || !strcmp("BYE", arg)) {
829 if ((resp = parse_response_code(ctx, NULL, cmd)) != RESP_OK)
831 } else if (!strcmp("CAPABILITY", arg))
832 parse_capability(imap, cmd);
833 else if ((arg1 = next_arg(&cmd))) {
834 if (!strcmp("EXISTS", arg1))
835 ctx->gen.count = atoi(arg);
836 else if (!strcmp("RECENT", arg1))
837 ctx->gen.recent = atoi(arg);
839 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
842 } else if (!imap->in_progress) {
843 fprintf(stderr, "IMAP error: unexpected reply: %s %s\n", arg, cmd ? cmd : "");
845 } else if (*arg == '+') {
846 /* This can happen only with the last command underway, as
847 it enforces a round-trip. */
848 cmdp = (struct imap_cmd *)((char *)imap->in_progress_append -
849 offsetof(struct imap_cmd, next));
851 n = socket_write(&imap->buf.sock, cmdp->cb.data, cmdp->cb.dlen);
853 cmdp->cb.data = NULL;
854 if (n != (int)cmdp->cb.dlen)
856 } else if (cmdp->cb.cont) {
857 if (cmdp->cb.cont(ctx, cmdp, cmd))
860 fprintf(stderr, "IMAP error: unexpected command continuation request\n");
863 if (socket_write(&imap->buf.sock, "\r\n", 2) != 2)
866 imap->literal_pending = 0;
871 for (pcmdp = &imap->in_progress; (cmdp = *pcmdp); pcmdp = &cmdp->next)
872 if (cmdp->tag == tag)
874 fprintf(stderr, "IMAP error: unexpected tag %s\n", arg);
877 if (!(*pcmdp = cmdp->next))
878 imap->in_progress_append = pcmdp;
879 imap->num_in_progress--;
880 if (cmdp->cb.cont || cmdp->cb.data)
881 imap->literal_pending = 0;
882 arg = next_arg(&cmd);
883 if (!strcmp("OK", arg))
886 if (!strcmp("NO", arg)) {
887 if (cmdp->cb.create && cmd && (cmdp->cb.trycreate || !memcmp(cmd, "[TRYCREATE]", 11))) { /* SELECT, APPEND or UID COPY */
888 p = strchr(cmdp->cmd, '"');
889 if (!issue_imap_cmd(ctx, NULL, "CREATE \"%.*s\"", (int)(strchr(p + 1, '"') - p + 1), p)) {
893 /* not waiting here violates the spec, but a server that does not
894 grok this nonetheless violates it too. */
896 if (!(ncmdp = issue_imap_cmd(ctx, &cmdp->cb, "%s", cmdp->cmd))) {
903 return 0; /* ignored */
909 } else /*if (!strcmp("BAD", arg))*/
911 fprintf(stderr, "IMAP command '%s' returned response (%s) - %s\n",
912 memcmp(cmdp->cmd, "LOGIN", 5) ?
913 cmdp->cmd : "LOGIN <user> <pass>",
914 arg, cmd ? cmd : "");
916 if ((resp2 = parse_response_code(ctx, &cmdp->cb, cmd)) > resp)
920 cmdp->cb.done(ctx, cmdp, resp);
924 if (!tcmd || tcmd == cmdp)
931 static void imap_close_server(struct imap_store *ictx)
933 struct imap *imap = ictx->imap;
935 if (imap->buf.sock.fd[0] != -1) {
936 imap_exec(ictx, NULL, "LOGOUT");
937 socket_shutdown(&imap->buf.sock);
939 free_list(imap->ns_personal);
940 free_list(imap->ns_other);
941 free_list(imap->ns_shared);
945 static void imap_close_store(struct store *ctx)
947 imap_close_server((struct imap_store *)ctx);
948 free_generic_messages(ctx->msgs);
952 static struct store *imap_open_store(struct imap_server_conf *srvc)
954 struct imap_store *ctx;
959 ctx = xcalloc(sizeof(*ctx), 1);
961 ctx->imap = imap = xcalloc(sizeof(*imap), 1);
962 imap->buf.sock.fd[0] = imap->buf.sock.fd[1] = -1;
963 imap->in_progress_append = &imap->in_progress;
965 /* open connection to IMAP server */
968 const char *argv[] = { srvc->tunnel, NULL };
969 struct child_process tunnel = {0};
971 imap_info("Starting tunnel '%s'... ", srvc->tunnel);
974 tunnel.use_shell = 1;
977 if (start_command(&tunnel))
978 die("cannot start proxy %s", argv[0]);
980 imap->buf.sock.fd[0] = tunnel.out;
981 imap->buf.sock.fd[1] = tunnel.in;
986 struct addrinfo hints, *ai0, *ai;
990 snprintf(portstr, sizeof(portstr), "%hu", srvc->port);
992 memset(&hints, 0, sizeof(hints));
993 hints.ai_socktype = SOCK_STREAM;
994 hints.ai_protocol = IPPROTO_TCP;
996 imap_info("Resolving %s... ", srvc->host);
997 gai = getaddrinfo(srvc->host, portstr, &hints, &ai);
999 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai));
1004 for (ai0 = ai; ai; ai = ai->ai_next) {
1005 char addr[NI_MAXHOST];
1007 s = socket(ai->ai_family, ai->ai_socktype,
1012 getnameinfo(ai->ai_addr, ai->ai_addrlen, addr,
1013 sizeof(addr), NULL, 0, NI_NUMERICHOST);
1014 imap_info("Connecting to [%s]:%s... ", addr, portstr);
1016 if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0) {
1028 struct sockaddr_in addr;
1030 memset(&addr, 0, sizeof(addr));
1031 addr.sin_port = htons(srvc->port);
1032 addr.sin_family = AF_INET;
1034 imap_info("Resolving %s... ", srvc->host);
1035 he = gethostbyname(srvc->host);
1037 perror("gethostbyname");
1042 addr.sin_addr.s_addr = *((int *) he->h_addr_list[0]);
1044 s = socket(PF_INET, SOCK_STREAM, 0);
1046 imap_info("Connecting to %s:%hu... ", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
1047 if (connect(s, (struct sockaddr *)&addr, sizeof(addr))) {
1054 fputs("Error: unable to connect to server.\n", stderr);
1058 imap->buf.sock.fd[0] = s;
1059 imap->buf.sock.fd[1] = dup(s);
1061 if (srvc->use_ssl &&
1062 ssl_socket_connect(&imap->buf.sock, 0, srvc->ssl_verify)) {
1069 /* read the greeting string */
1070 if (buffer_gets(&imap->buf, &rsp)) {
1071 fprintf(stderr, "IMAP error: no greeting response\n");
1074 arg = next_arg(&rsp);
1075 if (!arg || *arg != '*' || (arg = next_arg(&rsp)) == NULL) {
1076 fprintf(stderr, "IMAP error: invalid greeting response\n");
1080 if (!strcmp("PREAUTH", arg))
1082 else if (strcmp("OK", arg) != 0) {
1083 fprintf(stderr, "IMAP error: unknown greeting response\n");
1086 parse_response_code(ctx, NULL, rsp);
1087 if (!imap->caps && imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1092 if (!srvc->use_ssl && CAP(STARTTLS)) {
1093 if (imap_exec(ctx, 0, "STARTTLS") != RESP_OK)
1095 if (ssl_socket_connect(&imap->buf.sock, 1,
1098 /* capabilities may have changed, so get the new capabilities */
1099 if (imap_exec(ctx, 0, "CAPABILITY") != RESP_OK)
1103 imap_info("Logging in...\n");
1105 fprintf(stderr, "Skipping server %s, no user\n", srvc->host);
1110 sprintf(prompt, "Password (%s@%s): ", srvc->user, srvc->host);
1111 arg = getpass(prompt);
1117 fprintf(stderr, "Skipping account %s@%s, no password\n", srvc->user, srvc->host);
1121 * getpass() returns a pointer to a static buffer. make a copy
1122 * for long term storage.
1124 srvc->pass = xstrdup(arg);
1127 fprintf(stderr, "Skipping account %s@%s, server forbids LOGIN\n", srvc->user, srvc->host);
1130 if (!imap->buf.sock.ssl)
1131 imap_warn("*** IMAP Warning *** Password is being "
1132 "sent in the clear\n");
1133 if (imap_exec(ctx, NULL, "LOGIN \"%s\" \"%s\"", srvc->user, srvc->pass) != RESP_OK) {
1134 fprintf(stderr, "IMAP error: LOGIN failed\n");
1141 return (struct store *)ctx;
1144 imap_close_store(&ctx->gen);
1148 static int imap_make_flags(int flags, char *buf)
1153 for (i = d = 0; i < ARRAY_SIZE(Flags); i++)
1154 if (flags & (1 << i)) {
1157 for (s = Flags[i]; *s; s++)
1165 static int imap_store_msg(struct store *gctx, struct msg_data *data)
1167 struct imap_store *ctx = (struct imap_store *)gctx;
1168 struct imap *imap = ctx->imap;
1169 struct imap_cmd_cb cb;
1170 const char *prefix, *box;
1174 memset(&cb, 0, sizeof(cb));
1176 cb.dlen = data->len;
1177 cb.data = xmalloc(cb.dlen);
1178 memcpy(cb.data, data->data, data->len);
1182 d = imap_make_flags(data->flags, flagstr);
1188 prefix = !strcmp(box, "INBOX") ? "" : ctx->prefix;
1190 ret = imap_exec_m(ctx, &cb, "APPEND \"%s%s\" %s", prefix, box, flagstr);
1191 imap->caps = imap->rcaps;
1199 static void encode_html_chars(struct strbuf *p)
1202 for (i = 0; i < p->len; i++) {
1203 if (p->buf[i] == '&')
1204 strbuf_splice(p, i, 1, "&", 5);
1205 if (p->buf[i] == '<')
1206 strbuf_splice(p, i, 1, "<", 4);
1207 if (p->buf[i] == '>')
1208 strbuf_splice(p, i, 1, ">", 4);
1209 if (p->buf[i] == '"')
1210 strbuf_splice(p, i, 1, """, 6);
1213 static void wrap_in_html(struct msg_data *msg)
1215 struct strbuf buf = STRBUF_INIT;
1216 struct strbuf **lines;
1218 static char *content_type = "Content-Type: text/html;\n";
1219 static char *pre_open = "<pre>\n";
1220 static char *pre_close = "</pre>\n";
1221 int added_header = 0;
1223 strbuf_attach(&buf, msg->data, msg->len, msg->len);
1224 lines = strbuf_split(&buf, '\n');
1225 strbuf_release(&buf);
1226 for (p = lines; *p; p++) {
1227 if (! added_header) {
1228 if ((*p)->len == 1 && *((*p)->buf) == '\n') {
1229 strbuf_addstr(&buf, content_type);
1230 strbuf_addbuf(&buf, *p);
1231 strbuf_addstr(&buf, pre_open);
1237 encode_html_chars(*p);
1238 strbuf_addbuf(&buf, *p);
1240 strbuf_addstr(&buf, pre_close);
1241 strbuf_list_free(lines);
1243 msg->data = strbuf_detach(&buf, NULL);
1246 #define CHUNKSIZE 0x1000
1248 static int read_message(FILE *f, struct msg_data *msg)
1250 struct strbuf buf = STRBUF_INIT;
1252 memset(msg, 0, sizeof(*msg));
1255 if (strbuf_fread(&buf, CHUNKSIZE, f) <= 0)
1260 msg->data = strbuf_detach(&buf, NULL);
1264 static int count_messages(struct msg_data *msg)
1267 char *p = msg->data;
1270 if (!prefixcmp(p, "From ")) {
1274 p = strstr(p+5, "\nFrom ");
1282 static int split_msg(struct msg_data *all_msgs, struct msg_data *msg, int *ofs)
1286 memset(msg, 0, sizeof *msg);
1287 if (*ofs >= all_msgs->len)
1290 data = &all_msgs->data[*ofs];
1291 msg->len = all_msgs->len - *ofs;
1293 if (msg->len < 5 || prefixcmp(data, "From "))
1296 p = strchr(data, '\n');
1304 p = strstr(data, "\nFrom ");
1306 msg->len = &p[1] - data;
1308 msg->data = xmemdupz(data, msg->len);
1313 static struct imap_server_conf server = {
1325 static char *imap_folder;
1327 static int git_imap_config(const char *key, const char *val, void *cb)
1329 char imap_key[] = "imap.";
1331 if (strncmp(key, imap_key, sizeof imap_key - 1))
1335 return config_error_nonbool(key);
1337 key += sizeof imap_key - 1;
1339 if (!strcmp("folder", key)) {
1340 imap_folder = xstrdup(val);
1341 } else if (!strcmp("host", key)) {
1342 if (!prefixcmp(val, "imap:"))
1344 else if (!prefixcmp(val, "imaps:")) {
1348 if (!prefixcmp(val, "//"))
1350 server.host = xstrdup(val);
1351 } else if (!strcmp("user", key))
1352 server.user = xstrdup(val);
1353 else if (!strcmp("pass", key))
1354 server.pass = xstrdup(val);
1355 else if (!strcmp("port", key))
1356 server.port = git_config_int(key, val);
1357 else if (!strcmp("tunnel", key))
1358 server.tunnel = xstrdup(val);
1359 else if (!strcmp("sslverify", key))
1360 server.ssl_verify = git_config_bool(key, val);
1361 else if (!strcmp("preformattedHTML", key))
1362 server.use_html = git_config_bool(key, val);
1366 int main(int argc, char **argv)
1368 struct msg_data all_msgs, msg;
1369 struct store *ctx = NULL;
1375 git_extract_argv0_path(argv[0]);
1378 usage(imap_send_usage);
1380 setup_git_directory_gently(&nongit_ok);
1381 git_config(git_imap_config, NULL);
1384 server.port = server.use_ssl ? 993 : 143;
1387 fprintf(stderr, "no imap store specified\n");
1391 if (!server.tunnel) {
1392 fprintf(stderr, "no imap host specified\n");
1395 server.host = "tunnel";
1398 /* read the messages */
1399 if (!read_message(stdin, &all_msgs)) {
1400 fprintf(stderr, "nothing to send\n");
1404 total = count_messages(&all_msgs);
1406 fprintf(stderr, "no messages to send\n");
1410 /* write it to the imap server */
1411 ctx = imap_open_store(&server);
1413 fprintf(stderr, "failed to open store\n");
1417 fprintf(stderr, "sending %d message%s\n", total, (total != 1) ? "s" : "");
1418 ctx->name = imap_folder;
1420 unsigned percent = n * 100 / total;
1421 fprintf(stderr, "%4u%% (%d/%d) done\r", percent, n, total);
1422 if (!split_msg(&all_msgs, &msg, &ofs))
1424 if (server.use_html)
1426 r = imap_store_msg(ctx, &msg);
1431 fprintf(stderr, "\n");
1433 imap_close_store(ctx);