Merge branch 'wk/man-deny-current-branch-is-default-these-days' into maint
[git/jnareb-git.git] / imap-send.c
blobef500111ec0bca6514e519d39e7a269a7342cddf
1 /*
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
25 #include "cache.h"
26 #include "exec_cmd.h"
27 #include "run-command.h"
28 #include "prompt.h"
29 #ifdef NO_OPENSSL
30 typedef void *SSL;
31 #else
32 #include <openssl/evp.h>
33 #include <openssl/hmac.h>
34 #include <openssl/x509v3.h>
35 #endif
37 struct store_conf {
38 char *name;
39 const char *path; /* should this be here? its interpretation is driver-specific */
40 char *map_inbox;
41 char *trash;
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 */
51 struct message {
52 struct message *next;
53 size_t size; /* zero implies "not fetched" */
54 int uid;
55 unsigned char flags, status;
58 struct store {
59 struct store_conf *conf; /* foreign */
61 /* currently open mailbox */
62 const char *name; /* foreign! maybe preset? */
63 char *path; /* own */
64 struct message *msgs; /* own */
65 int uidvalidity;
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 */
72 struct msg_data {
73 char *data;
74 int len;
75 unsigned char flags;
78 static const char imap_send_usage[] = "git imap-send < <mbox>";
80 #undef DRV_OK
81 #define DRV_OK 0
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)
102 int len;
103 char tmp[8192];
105 len = vsnprintf(tmp, sizeof(tmp), fmt, ap);
106 if (len < 0)
107 die("Fatal: Out of memory");
108 if (len >= sizeof(tmp))
109 die("imap command overflow!");
110 *strp = xmemdupz(tmp, len);
111 return len;
114 struct imap_server_conf {
115 char *name;
116 char *tunnel;
117 char *host;
118 int port;
119 char *user;
120 char *pass;
121 int use_ssl;
122 int ssl_verify;
123 int use_html;
124 char *auth_method;
127 static struct imap_server_conf server = {
128 NULL, /* name */
129 NULL, /* tunnel */
130 NULL, /* host */
131 0, /* port */
132 NULL, /* user */
133 NULL, /* pass */
134 0, /* use_ssl */
135 1, /* ssl_verify */
136 0, /* use_html */
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
148 struct imap_list {
149 struct imap_list *next, *child;
150 char *val;
151 int len;
154 struct imap_socket {
155 int fd[2];
156 SSL *ssl;
159 struct imap_buffer {
160 struct imap_socket sock;
161 int bytes;
162 int offset;
163 char buf[1024];
166 struct imap_cmd;
168 struct imap {
169 int uidnext; /* from SELECT responses */
170 struct imap_list *ns_personal, *ns_other, *ns_shared; /* NAMESPACE info */
171 unsigned caps, rcaps; /* CAPABILITY results */
172 /* command queue */
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 */
178 struct imap_store {
179 struct store gen;
180 int uidvalidity;
181 struct imap *imap;
182 const char *prefix;
183 unsigned /*currentnc:1,*/ trashnc:1;
186 struct imap_cmd_cb {
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);
189 void *ctx;
190 char *data;
191 int dlen;
192 int uid;
193 unsigned create:1, trycreate:1;
196 struct imap_cmd {
197 struct imap_cmd *next;
198 struct imap_cmd_cb cb;
199 char *cmd;
200 int tag;
203 #define CAP(cap) (imap->caps & (1 << (cap)))
205 enum CAPABILITY {
206 NOLOGIN = 0,
207 UIDPLUS,
208 LITERALPLUS,
209 NAMESPACE,
210 STARTTLS,
211 AUTH_CRAM_MD5
214 static const char *cap_list[] = {
215 "LOGINDISABLED",
216 "UIDPLUS",
217 "LITERAL+",
218 "NAMESPACE",
219 "STARTTLS",
220 "AUTH=CRAM-MD5",
223 #define RESP_OK 0
224 #define RESP_NO 1
225 #define RESP_BAD 2
227 static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd);
230 static const char *Flags[] = {
231 "Draft",
232 "Flagged",
233 "Answered",
234 "Seen",
235 "Deleted",
238 #ifndef NO_OPENSSL
239 static void ssl_socket_perror(const char *func)
241 fprintf(stderr, "%s: %s\n", func, ERR_error_string(ERR_get_error(), NULL));
243 #endif
245 static void socket_perror(const char *func, struct imap_socket *sock, int ret)
247 #ifndef NO_OPENSSL
248 if (sock->ssl) {
249 int sslerr = SSL_get_error(sock->ssl, ret);
250 switch (sslerr) {
251 case SSL_ERROR_NONE:
252 break;
253 case SSL_ERROR_SYSCALL:
254 perror("SSL_connect");
255 break;
256 default:
257 ssl_socket_perror("SSL_connect");
258 break;
260 } else
261 #endif
263 if (ret < 0)
264 perror(func);
265 else
266 fprintf(stderr, "%s: unexpected EOF\n", func);
270 #ifdef NO_OPENSSL
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");
274 return -1;
277 #else
279 static int host_matches(const char *host, const char *pattern)
281 if (pattern[0] == '*' && pattern[1] == '.') {
282 pattern += 2;
283 if (!(host = strchr(host, '.')))
284 return 0;
285 host++;
288 return *host && *pattern && !strcasecmp(host, pattern);
291 static int verify_hostname(X509 *cert, const char *hostname)
293 int len;
294 X509_NAME *subj;
295 char cname[1000];
296 int i, found;
297 STACK_OF(GENERAL_NAME) *subj_alt_names;
299 /* try the DNS subjectAltNames */
300 found = 0;
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)))
308 found = 1;
310 sk_GENERAL_NAME_pop_free(subj_alt_names, GENERAL_NAME_free);
312 if (found)
313 return 0;
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))
321 return 0;
322 return error("certificate owner '%s' does not match hostname '%s'",
323 cname, hostname);
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;
330 #else
331 SSL_METHOD *meth;
332 #endif
333 SSL_CTX *ctx;
334 int ret;
335 X509 *cert;
337 SSL_library_init();
338 SSL_load_error_strings();
340 if (use_tls_only)
341 meth = TLSv1_method();
342 else
343 meth = SSLv23_method();
345 if (!meth) {
346 ssl_socket_perror("SSLv23_method");
347 return -1;
350 ctx = SSL_CTX_new(meth);
352 if (verify)
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");
357 return -1;
359 sock->ssl = SSL_new(ctx);
360 if (!sock->ssl) {
361 ssl_socket_perror("SSL_new");
362 return -1;
364 if (!SSL_set_rfd(sock->ssl, sock->fd[0])) {
365 ssl_socket_perror("SSL_set_rfd");
366 return -1;
368 if (!SSL_set_wfd(sock->ssl, sock->fd[1])) {
369 ssl_socket_perror("SSL_set_wfd");
370 return -1;
373 ret = SSL_connect(sock->ssl);
374 if (ret <= 0) {
375 socket_perror("SSL_connect", sock, ret);
376 return -1;
379 if (verify) {
380 /* make sure the hostname matches that of the certificate */
381 cert = SSL_get_peer_certificate(sock->ssl);
382 if (!cert)
383 return error("unable to get peer certificate.");
384 if (verify_hostname(cert, server.host) < 0)
385 return -1;
388 return 0;
390 #endif
392 static int socket_read(struct imap_socket *sock, char *buf, int len)
394 ssize_t n;
395 #ifndef NO_OPENSSL
396 if (sock->ssl)
397 n = SSL_read(sock->ssl, buf, len);
398 else
399 #endif
400 n = xread(sock->fd[0], buf, len);
401 if (n <= 0) {
402 socket_perror("read", sock, n);
403 close(sock->fd[0]);
404 close(sock->fd[1]);
405 sock->fd[0] = sock->fd[1] = -1;
407 return n;
410 static int socket_write(struct imap_socket *sock, const char *buf, int len)
412 int n;
413 #ifndef NO_OPENSSL
414 if (sock->ssl)
415 n = SSL_write(sock->ssl, buf, len);
416 else
417 #endif
418 n = write_in_full(sock->fd[1], buf, len);
419 if (n != len) {
420 socket_perror("write", sock, n);
421 close(sock->fd[0]);
422 close(sock->fd[1]);
423 sock->fd[0] = sock->fd[1] = -1;
425 return n;
428 static void socket_shutdown(struct imap_socket *sock)
430 #ifndef NO_OPENSSL
431 if (sock->ssl) {
432 SSL_shutdown(sock->ssl);
433 SSL_free(sock->ssl);
435 #endif
436 close(sock->fd[0]);
437 close(sock->fd[1]);
440 /* simple line buffering */
441 static int buffer_gets(struct imap_buffer *b, char **s)
443 int n;
444 int start = b->offset;
446 *s = b->buf + start;
448 for (;;) {
449 /* make sure we have enough data to read the \r\n sequence */
450 if (b->offset + 1 >= b->bytes) {
451 if (start) {
452 /* shift down used bytes */
453 *s = b->buf;
455 assert(start <= b->bytes);
456 n = b->bytes - start;
458 if (n)
459 memmove(b->buf, b->buf + start, n);
460 b->offset -= start;
461 b->bytes = n;
462 start = 0;
465 n = socket_read(&b->sock, b->buf + b->bytes,
466 sizeof(b->buf) - b->bytes);
468 if (n <= 0)
469 return -1;
471 b->bytes += n;
474 if (b->buf[b->offset] == '\r') {
475 assert(b->offset + 1 < b->bytes);
476 if (b->buf[b->offset + 1] == '\n') {
477 b->buf[b->offset] = 0; /* terminate the string */
478 b->offset += 2; /* next line */
479 if (Verbose)
480 puts(*s);
481 return 0;
485 b->offset++;
487 /* not reached */
490 static void imap_info(const char *msg, ...)
492 va_list va;
494 if (!Quiet) {
495 va_start(va, msg);
496 vprintf(msg, va);
497 va_end(va);
498 fflush(stdout);
502 static void imap_warn(const char *msg, ...)
504 va_list va;
506 if (Quiet < 2) {
507 va_start(va, msg);
508 vfprintf(stderr, msg, va);
509 va_end(va);
513 static char *next_arg(char **s)
515 char *ret;
517 if (!s || !*s)
518 return NULL;
519 while (isspace((unsigned char) **s))
520 (*s)++;
521 if (!**s) {
522 *s = NULL;
523 return NULL;
525 if (**s == '"') {
526 ++*s;
527 ret = *s;
528 *s = strchr(*s, '"');
529 } else {
530 ret = *s;
531 while (**s && !isspace((unsigned char) **s))
532 (*s)++;
534 if (*s) {
535 if (**s)
536 *(*s)++ = 0;
537 if (!**s)
538 *s = NULL;
540 return ret;
543 static void free_generic_messages(struct message *msgs)
545 struct message *tmsg;
547 for (; msgs; msgs = tmsg) {
548 tmsg = msgs->next;
549 free(msgs);
553 static int nfsnprintf(char *buf, int blen, const char *fmt, ...)
555 int ret;
556 va_list va;
558 va_start(va, fmt);
559 if (blen <= 0 || (unsigned)(ret = vsnprintf(buf, blen, fmt, va)) >= (unsigned)blen)
560 die("Fatal: buffer too small. Please report a bug.");
561 va_end(va);
562 return ret;
565 static struct imap_cmd *v_issue_imap_cmd(struct imap_store *ctx,
566 struct imap_cmd_cb *cb,
567 const char *fmt, va_list ap)
569 struct imap *imap = ctx->imap;
570 struct imap_cmd *cmd;
571 int n, bufl;
572 char buf[1024];
574 cmd = xmalloc(sizeof(struct imap_cmd));
575 nfvasprintf(&cmd->cmd, fmt, ap);
576 cmd->tag = ++imap->nexttag;
578 if (cb)
579 cmd->cb = *cb;
580 else
581 memset(&cmd->cb, 0, sizeof(cmd->cb));
583 while (imap->literal_pending)
584 get_cmd_result(ctx, NULL);
586 if (!cmd->cb.data)
587 bufl = nfsnprintf(buf, sizeof(buf), "%d %s\r\n", cmd->tag, cmd->cmd);
588 else
589 bufl = nfsnprintf(buf, sizeof(buf), "%d %s{%d%s}\r\n",
590 cmd->tag, cmd->cmd, cmd->cb.dlen,
591 CAP(LITERALPLUS) ? "+" : "");
593 if (Verbose) {
594 if (imap->num_in_progress)
595 printf("(%d in progress) ", imap->num_in_progress);
596 if (memcmp(cmd->cmd, "LOGIN", 5))
597 printf(">>> %s", buf);
598 else
599 printf(">>> %d LOGIN <user> <pass>\n", cmd->tag);
601 if (socket_write(&imap->buf.sock, buf, bufl) != bufl) {
602 free(cmd->cmd);
603 free(cmd);
604 if (cb)
605 free(cb->data);
606 return NULL;
608 if (cmd->cb.data) {
609 if (CAP(LITERALPLUS)) {
610 n = socket_write(&imap->buf.sock, cmd->cb.data, cmd->cb.dlen);
611 free(cmd->cb.data);
612 if (n != cmd->cb.dlen ||
613 socket_write(&imap->buf.sock, "\r\n", 2) != 2) {
614 free(cmd->cmd);
615 free(cmd);
616 return NULL;
618 cmd->cb.data = NULL;
619 } else
620 imap->literal_pending = 1;
621 } else if (cmd->cb.cont)
622 imap->literal_pending = 1;
623 cmd->next = NULL;
624 *imap->in_progress_append = cmd;
625 imap->in_progress_append = &cmd->next;
626 imap->num_in_progress++;
627 return cmd;
630 __attribute__((format (printf, 3, 4)))
631 static struct imap_cmd *issue_imap_cmd(struct imap_store *ctx,
632 struct imap_cmd_cb *cb,
633 const char *fmt, ...)
635 struct imap_cmd *ret;
636 va_list ap;
638 va_start(ap, fmt);
639 ret = v_issue_imap_cmd(ctx, cb, fmt, ap);
640 va_end(ap);
641 return ret;
644 __attribute__((format (printf, 3, 4)))
645 static int imap_exec(struct imap_store *ctx, struct imap_cmd_cb *cb,
646 const char *fmt, ...)
648 va_list ap;
649 struct imap_cmd *cmdp;
651 va_start(ap, fmt);
652 cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
653 va_end(ap);
654 if (!cmdp)
655 return RESP_BAD;
657 return get_cmd_result(ctx, cmdp);
660 __attribute__((format (printf, 3, 4)))
661 static int imap_exec_m(struct imap_store *ctx, struct imap_cmd_cb *cb,
662 const char *fmt, ...)
664 va_list ap;
665 struct imap_cmd *cmdp;
667 va_start(ap, fmt);
668 cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
669 va_end(ap);
670 if (!cmdp)
671 return DRV_STORE_BAD;
673 switch (get_cmd_result(ctx, cmdp)) {
674 case RESP_BAD: return DRV_STORE_BAD;
675 case RESP_NO: return DRV_MSG_BAD;
676 default: return DRV_OK;
680 static int is_atom(struct imap_list *list)
682 return list && list->val && list->val != NIL && list->val != LIST;
685 static int is_list(struct imap_list *list)
687 return list && list->val == LIST;
690 static void free_list(struct imap_list *list)
692 struct imap_list *tmp;
694 for (; list; list = tmp) {
695 tmp = list->next;
696 if (is_list(list))
697 free_list(list->child);
698 else if (is_atom(list))
699 free(list->val);
700 free(list);
704 static int parse_imap_list_l(struct imap *imap, char **sp, struct imap_list **curp, int level)
706 struct imap_list *cur;
707 char *s = *sp, *p;
708 int n, bytes;
710 for (;;) {
711 while (isspace((unsigned char)*s))
712 s++;
713 if (level && *s == ')') {
714 s++;
715 break;
717 *curp = cur = xmalloc(sizeof(*cur));
718 curp = &cur->next;
719 cur->val = NULL; /* for clean bail */
720 if (*s == '(') {
721 /* sublist */
722 s++;
723 cur->val = LIST;
724 if (parse_imap_list_l(imap, &s, &cur->child, level + 1))
725 goto bail;
726 } else if (imap && *s == '{') {
727 /* literal */
728 bytes = cur->len = strtol(s + 1, &s, 10);
729 if (*s != '}')
730 goto bail;
732 s = cur->val = xmalloc(cur->len);
734 /* dump whats left over in the input buffer */
735 n = imap->buf.bytes - imap->buf.offset;
737 if (n > bytes)
738 /* the entire message fit in the buffer */
739 n = bytes;
741 memcpy(s, imap->buf.buf + imap->buf.offset, n);
742 s += n;
743 bytes -= n;
745 /* mark that we used part of the buffer */
746 imap->buf.offset += n;
748 /* now read the rest of the message */
749 while (bytes > 0) {
750 if ((n = socket_read(&imap->buf.sock, s, bytes)) <= 0)
751 goto bail;
752 s += n;
753 bytes -= n;
756 if (buffer_gets(&imap->buf, &s))
757 goto bail;
758 } else if (*s == '"') {
759 /* quoted string */
760 s++;
761 p = s;
762 for (; *s != '"'; s++)
763 if (!*s)
764 goto bail;
765 cur->len = s - p;
766 s++;
767 cur->val = xmemdupz(p, cur->len);
768 } else {
769 /* atom */
770 p = s;
771 for (; *s && !isspace((unsigned char)*s); s++)
772 if (level && *s == ')')
773 break;
774 cur->len = s - p;
775 if (cur->len == 3 && !memcmp("NIL", p, 3))
776 cur->val = NIL;
777 else
778 cur->val = xmemdupz(p, cur->len);
781 if (!level)
782 break;
783 if (!*s)
784 goto bail;
786 *sp = s;
787 *curp = NULL;
788 return 0;
790 bail:
791 *curp = NULL;
792 return -1;
795 static struct imap_list *parse_imap_list(struct imap *imap, char **sp)
797 struct imap_list *head;
799 if (!parse_imap_list_l(imap, sp, &head, 0))
800 return head;
801 free_list(head);
802 return NULL;
805 static struct imap_list *parse_list(char **sp)
807 return parse_imap_list(NULL, sp);
810 static void parse_capability(struct imap *imap, char *cmd)
812 char *arg;
813 unsigned i;
815 imap->caps = 0x80000000;
816 while ((arg = next_arg(&cmd)))
817 for (i = 0; i < ARRAY_SIZE(cap_list); i++)
818 if (!strcmp(cap_list[i], arg))
819 imap->caps |= 1 << i;
820 imap->rcaps = imap->caps;
823 static int parse_response_code(struct imap_store *ctx, struct imap_cmd_cb *cb,
824 char *s)
826 struct imap *imap = ctx->imap;
827 char *arg, *p;
829 if (*s != '[')
830 return RESP_OK; /* no response code */
831 s++;
832 if (!(p = strchr(s, ']'))) {
833 fprintf(stderr, "IMAP error: malformed response code\n");
834 return RESP_BAD;
836 *p++ = 0;
837 arg = next_arg(&s);
838 if (!strcmp("UIDVALIDITY", arg)) {
839 if (!(arg = next_arg(&s)) || !(ctx->gen.uidvalidity = atoi(arg))) {
840 fprintf(stderr, "IMAP error: malformed UIDVALIDITY status\n");
841 return RESP_BAD;
843 } else if (!strcmp("UIDNEXT", arg)) {
844 if (!(arg = next_arg(&s)) || !(imap->uidnext = atoi(arg))) {
845 fprintf(stderr, "IMAP error: malformed NEXTUID status\n");
846 return RESP_BAD;
848 } else if (!strcmp("CAPABILITY", arg)) {
849 parse_capability(imap, s);
850 } else if (!strcmp("ALERT", arg)) {
851 /* RFC2060 says that these messages MUST be displayed
852 * to the user
854 for (; isspace((unsigned char)*p); p++);
855 fprintf(stderr, "*** IMAP ALERT *** %s\n", p);
856 } else if (cb && cb->ctx && !strcmp("APPENDUID", arg)) {
857 if (!(arg = next_arg(&s)) || !(ctx->gen.uidvalidity = atoi(arg)) ||
858 !(arg = next_arg(&s)) || !(*(int *)cb->ctx = atoi(arg))) {
859 fprintf(stderr, "IMAP error: malformed APPENDUID status\n");
860 return RESP_BAD;
863 return RESP_OK;
866 static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd)
868 struct imap *imap = ctx->imap;
869 struct imap_cmd *cmdp, **pcmdp, *ncmdp;
870 char *cmd, *arg, *arg1, *p;
871 int n, resp, resp2, tag;
873 for (;;) {
874 if (buffer_gets(&imap->buf, &cmd))
875 return RESP_BAD;
877 arg = next_arg(&cmd);
878 if (*arg == '*') {
879 arg = next_arg(&cmd);
880 if (!arg) {
881 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
882 return RESP_BAD;
885 if (!strcmp("NAMESPACE", arg)) {
886 imap->ns_personal = parse_list(&cmd);
887 imap->ns_other = parse_list(&cmd);
888 imap->ns_shared = parse_list(&cmd);
889 } else if (!strcmp("OK", arg) || !strcmp("BAD", arg) ||
890 !strcmp("NO", arg) || !strcmp("BYE", arg)) {
891 if ((resp = parse_response_code(ctx, NULL, cmd)) != RESP_OK)
892 return resp;
893 } else if (!strcmp("CAPABILITY", arg))
894 parse_capability(imap, cmd);
895 else if ((arg1 = next_arg(&cmd))) {
896 if (!strcmp("EXISTS", arg1))
897 ctx->gen.count = atoi(arg);
898 else if (!strcmp("RECENT", arg1))
899 ctx->gen.recent = atoi(arg);
900 } else {
901 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
902 return RESP_BAD;
904 } else if (!imap->in_progress) {
905 fprintf(stderr, "IMAP error: unexpected reply: %s %s\n", arg, cmd ? cmd : "");
906 return RESP_BAD;
907 } else if (*arg == '+') {
908 /* This can happen only with the last command underway, as
909 it enforces a round-trip. */
910 cmdp = (struct imap_cmd *)((char *)imap->in_progress_append -
911 offsetof(struct imap_cmd, next));
912 if (cmdp->cb.data) {
913 n = socket_write(&imap->buf.sock, cmdp->cb.data, cmdp->cb.dlen);
914 free(cmdp->cb.data);
915 cmdp->cb.data = NULL;
916 if (n != (int)cmdp->cb.dlen)
917 return RESP_BAD;
918 } else if (cmdp->cb.cont) {
919 if (cmdp->cb.cont(ctx, cmdp, cmd))
920 return RESP_BAD;
921 } else {
922 fprintf(stderr, "IMAP error: unexpected command continuation request\n");
923 return RESP_BAD;
925 if (socket_write(&imap->buf.sock, "\r\n", 2) != 2)
926 return RESP_BAD;
927 if (!cmdp->cb.cont)
928 imap->literal_pending = 0;
929 if (!tcmd)
930 return DRV_OK;
931 } else {
932 tag = atoi(arg);
933 for (pcmdp = &imap->in_progress; (cmdp = *pcmdp); pcmdp = &cmdp->next)
934 if (cmdp->tag == tag)
935 goto gottag;
936 fprintf(stderr, "IMAP error: unexpected tag %s\n", arg);
937 return RESP_BAD;
938 gottag:
939 if (!(*pcmdp = cmdp->next))
940 imap->in_progress_append = pcmdp;
941 imap->num_in_progress--;
942 if (cmdp->cb.cont || cmdp->cb.data)
943 imap->literal_pending = 0;
944 arg = next_arg(&cmd);
945 if (!strcmp("OK", arg))
946 resp = DRV_OK;
947 else {
948 if (!strcmp("NO", arg)) {
949 if (cmdp->cb.create && cmd && (cmdp->cb.trycreate || !memcmp(cmd, "[TRYCREATE]", 11))) { /* SELECT, APPEND or UID COPY */
950 p = strchr(cmdp->cmd, '"');
951 if (!issue_imap_cmd(ctx, NULL, "CREATE \"%.*s\"", (int)(strchr(p + 1, '"') - p + 1), p)) {
952 resp = RESP_BAD;
953 goto normal;
955 /* not waiting here violates the spec, but a server that does not
956 grok this nonetheless violates it too. */
957 cmdp->cb.create = 0;
958 if (!(ncmdp = issue_imap_cmd(ctx, &cmdp->cb, "%s", cmdp->cmd))) {
959 resp = RESP_BAD;
960 goto normal;
962 free(cmdp->cmd);
963 free(cmdp);
964 if (!tcmd)
965 return 0; /* ignored */
966 if (cmdp == tcmd)
967 tcmd = ncmdp;
968 continue;
970 resp = RESP_NO;
971 } else /*if (!strcmp("BAD", arg))*/
972 resp = RESP_BAD;
973 fprintf(stderr, "IMAP command '%s' returned response (%s) - %s\n",
974 memcmp(cmdp->cmd, "LOGIN", 5) ?
975 cmdp->cmd : "LOGIN <user> <pass>",
976 arg, cmd ? cmd : "");
978 if ((resp2 = parse_response_code(ctx, &cmdp->cb, cmd)) > resp)
979 resp = resp2;
980 normal:
981 if (cmdp->cb.done)
982 cmdp->cb.done(ctx, cmdp, resp);
983 free(cmdp->cb.data);
984 free(cmdp->cmd);
985 free(cmdp);
986 if (!tcmd || tcmd == cmdp)
987 return resp;
990 /* not reached */
993 static void imap_close_server(struct imap_store *ictx)
995 struct imap *imap = ictx->imap;
997 if (imap->buf.sock.fd[0] != -1) {
998 imap_exec(ictx, NULL, "LOGOUT");
999 socket_shutdown(&imap->buf.sock);
1001 free_list(imap->ns_personal);
1002 free_list(imap->ns_other);
1003 free_list(imap->ns_shared);
1004 free(imap);
1007 static void imap_close_store(struct store *ctx)
1009 imap_close_server((struct imap_store *)ctx);
1010 free_generic_messages(ctx->msgs);
1011 free(ctx);
1014 #ifndef NO_OPENSSL
1017 * hexchar() and cram() functions are based on the code from the isync
1018 * project (http://isync.sf.net/).
1020 static char hexchar(unsigned int b)
1022 return b < 10 ? '0' + b : 'a' + (b - 10);
1025 #define ENCODED_SIZE(n) (4*((n+2)/3))
1026 static char *cram(const char *challenge_64, const char *user, const char *pass)
1028 int i, resp_len, encoded_len, decoded_len;
1029 HMAC_CTX hmac;
1030 unsigned char hash[16];
1031 char hex[33];
1032 char *response, *response_64, *challenge;
1035 * length of challenge_64 (i.e. base-64 encoded string) is a good
1036 * enough upper bound for challenge (decoded result).
1038 encoded_len = strlen(challenge_64);
1039 challenge = xmalloc(encoded_len);
1040 decoded_len = EVP_DecodeBlock((unsigned char *)challenge,
1041 (unsigned char *)challenge_64, encoded_len);
1042 if (decoded_len < 0)
1043 die("invalid challenge %s", challenge_64);
1044 HMAC_Init(&hmac, (unsigned char *)pass, strlen(pass), EVP_md5());
1045 HMAC_Update(&hmac, (unsigned char *)challenge, decoded_len);
1046 HMAC_Final(&hmac, hash, NULL);
1047 HMAC_CTX_cleanup(&hmac);
1049 hex[32] = 0;
1050 for (i = 0; i < 16; i++) {
1051 hex[2 * i] = hexchar((hash[i] >> 4) & 0xf);
1052 hex[2 * i + 1] = hexchar(hash[i] & 0xf);
1055 /* response: "<user> <digest in hex>" */
1056 resp_len = strlen(user) + 1 + strlen(hex) + 1;
1057 response = xmalloc(resp_len);
1058 sprintf(response, "%s %s", user, hex);
1060 response_64 = xmalloc(ENCODED_SIZE(resp_len) + 1);
1061 encoded_len = EVP_EncodeBlock((unsigned char *)response_64,
1062 (unsigned char *)response, resp_len);
1063 if (encoded_len < 0)
1064 die("EVP_EncodeBlock error");
1065 response_64[encoded_len] = '\0';
1066 return (char *)response_64;
1069 #else
1071 static char *cram(const char *challenge_64, const char *user, const char *pass)
1073 die("If you want to use CRAM-MD5 authenticate method, "
1074 "you have to build git-imap-send with OpenSSL library.");
1077 #endif
1079 static int auth_cram_md5(struct imap_store *ctx, struct imap_cmd *cmd, const char *prompt)
1081 int ret;
1082 char *response;
1084 response = cram(prompt, server.user, server.pass);
1086 ret = socket_write(&ctx->imap->buf.sock, response, strlen(response));
1087 if (ret != strlen(response))
1088 return error("IMAP error: sending response failed");
1090 free(response);
1092 return 0;
1095 static struct store *imap_open_store(struct imap_server_conf *srvc)
1097 struct imap_store *ctx;
1098 struct imap *imap;
1099 char *arg, *rsp;
1100 int s = -1, preauth;
1102 ctx = xcalloc(sizeof(*ctx), 1);
1104 ctx->imap = imap = xcalloc(sizeof(*imap), 1);
1105 imap->buf.sock.fd[0] = imap->buf.sock.fd[1] = -1;
1106 imap->in_progress_append = &imap->in_progress;
1108 /* open connection to IMAP server */
1110 if (srvc->tunnel) {
1111 const char *argv[] = { srvc->tunnel, NULL };
1112 struct child_process tunnel = {NULL};
1114 imap_info("Starting tunnel '%s'... ", srvc->tunnel);
1116 tunnel.argv = argv;
1117 tunnel.use_shell = 1;
1118 tunnel.in = -1;
1119 tunnel.out = -1;
1120 if (start_command(&tunnel))
1121 die("cannot start proxy %s", argv[0]);
1123 imap->buf.sock.fd[0] = tunnel.out;
1124 imap->buf.sock.fd[1] = tunnel.in;
1126 imap_info("ok\n");
1127 } else {
1128 #ifndef NO_IPV6
1129 struct addrinfo hints, *ai0, *ai;
1130 int gai;
1131 char portstr[6];
1133 snprintf(portstr, sizeof(portstr), "%d", srvc->port);
1135 memset(&hints, 0, sizeof(hints));
1136 hints.ai_socktype = SOCK_STREAM;
1137 hints.ai_protocol = IPPROTO_TCP;
1139 imap_info("Resolving %s... ", srvc->host);
1140 gai = getaddrinfo(srvc->host, portstr, &hints, &ai);
1141 if (gai) {
1142 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai));
1143 goto bail;
1145 imap_info("ok\n");
1147 for (ai0 = ai; ai; ai = ai->ai_next) {
1148 char addr[NI_MAXHOST];
1150 s = socket(ai->ai_family, ai->ai_socktype,
1151 ai->ai_protocol);
1152 if (s < 0)
1153 continue;
1155 getnameinfo(ai->ai_addr, ai->ai_addrlen, addr,
1156 sizeof(addr), NULL, 0, NI_NUMERICHOST);
1157 imap_info("Connecting to [%s]:%s... ", addr, portstr);
1159 if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0) {
1160 close(s);
1161 s = -1;
1162 perror("connect");
1163 continue;
1166 break;
1168 freeaddrinfo(ai0);
1169 #else /* NO_IPV6 */
1170 struct hostent *he;
1171 struct sockaddr_in addr;
1173 memset(&addr, 0, sizeof(addr));
1174 addr.sin_port = htons(srvc->port);
1175 addr.sin_family = AF_INET;
1177 imap_info("Resolving %s... ", srvc->host);
1178 he = gethostbyname(srvc->host);
1179 if (!he) {
1180 perror("gethostbyname");
1181 goto bail;
1183 imap_info("ok\n");
1185 addr.sin_addr.s_addr = *((int *) he->h_addr_list[0]);
1187 s = socket(PF_INET, SOCK_STREAM, 0);
1189 imap_info("Connecting to %s:%hu... ", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
1190 if (connect(s, (struct sockaddr *)&addr, sizeof(addr))) {
1191 close(s);
1192 s = -1;
1193 perror("connect");
1195 #endif
1196 if (s < 0) {
1197 fputs("Error: unable to connect to server.\n", stderr);
1198 goto bail;
1201 imap->buf.sock.fd[0] = s;
1202 imap->buf.sock.fd[1] = dup(s);
1204 if (srvc->use_ssl &&
1205 ssl_socket_connect(&imap->buf.sock, 0, srvc->ssl_verify)) {
1206 close(s);
1207 goto bail;
1209 imap_info("ok\n");
1212 /* read the greeting string */
1213 if (buffer_gets(&imap->buf, &rsp)) {
1214 fprintf(stderr, "IMAP error: no greeting response\n");
1215 goto bail;
1217 arg = next_arg(&rsp);
1218 if (!arg || *arg != '*' || (arg = next_arg(&rsp)) == NULL) {
1219 fprintf(stderr, "IMAP error: invalid greeting response\n");
1220 goto bail;
1222 preauth = 0;
1223 if (!strcmp("PREAUTH", arg))
1224 preauth = 1;
1225 else if (strcmp("OK", arg) != 0) {
1226 fprintf(stderr, "IMAP error: unknown greeting response\n");
1227 goto bail;
1229 parse_response_code(ctx, NULL, rsp);
1230 if (!imap->caps && imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1231 goto bail;
1233 if (!preauth) {
1234 #ifndef NO_OPENSSL
1235 if (!srvc->use_ssl && CAP(STARTTLS)) {
1236 if (imap_exec(ctx, NULL, "STARTTLS") != RESP_OK)
1237 goto bail;
1238 if (ssl_socket_connect(&imap->buf.sock, 1,
1239 srvc->ssl_verify))
1240 goto bail;
1241 /* capabilities may have changed, so get the new capabilities */
1242 if (imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1243 goto bail;
1245 #endif
1246 imap_info("Logging in...\n");
1247 if (!srvc->user) {
1248 fprintf(stderr, "Skipping server %s, no user\n", srvc->host);
1249 goto bail;
1251 if (!srvc->pass) {
1252 struct strbuf prompt = STRBUF_INIT;
1253 strbuf_addf(&prompt, "Password (%s@%s): ", srvc->user, srvc->host);
1254 arg = git_getpass(prompt.buf);
1255 strbuf_release(&prompt);
1256 if (!*arg) {
1257 fprintf(stderr, "Skipping account %s@%s, no password\n", srvc->user, srvc->host);
1258 goto bail;
1261 * getpass() returns a pointer to a static buffer. make a copy
1262 * for long term storage.
1264 srvc->pass = xstrdup(arg);
1266 if (CAP(NOLOGIN)) {
1267 fprintf(stderr, "Skipping account %s@%s, server forbids LOGIN\n", srvc->user, srvc->host);
1268 goto bail;
1271 if (srvc->auth_method) {
1272 struct imap_cmd_cb cb;
1274 if (!strcmp(srvc->auth_method, "CRAM-MD5")) {
1275 if (!CAP(AUTH_CRAM_MD5)) {
1276 fprintf(stderr, "You specified"
1277 "CRAM-MD5 as authentication method, "
1278 "but %s doesn't support it.\n", srvc->host);
1279 goto bail;
1281 /* CRAM-MD5 */
1283 memset(&cb, 0, sizeof(cb));
1284 cb.cont = auth_cram_md5;
1285 if (imap_exec(ctx, &cb, "AUTHENTICATE CRAM-MD5") != RESP_OK) {
1286 fprintf(stderr, "IMAP error: AUTHENTICATE CRAM-MD5 failed\n");
1287 goto bail;
1289 } else {
1290 fprintf(stderr, "Unknown authentication method:%s\n", srvc->host);
1291 goto bail;
1293 } else {
1294 if (!imap->buf.sock.ssl)
1295 imap_warn("*** IMAP Warning *** Password is being "
1296 "sent in the clear\n");
1297 if (imap_exec(ctx, NULL, "LOGIN \"%s\" \"%s\"", srvc->user, srvc->pass) != RESP_OK) {
1298 fprintf(stderr, "IMAP error: LOGIN failed\n");
1299 goto bail;
1302 } /* !preauth */
1304 ctx->prefix = "";
1305 ctx->trashnc = 1;
1306 return (struct store *)ctx;
1308 bail:
1309 imap_close_store(&ctx->gen);
1310 return NULL;
1313 static int imap_make_flags(int flags, char *buf)
1315 const char *s;
1316 unsigned i, d;
1318 for (i = d = 0; i < ARRAY_SIZE(Flags); i++)
1319 if (flags & (1 << i)) {
1320 buf[d++] = ' ';
1321 buf[d++] = '\\';
1322 for (s = Flags[i]; *s; s++)
1323 buf[d++] = *s;
1325 buf[0] = '(';
1326 buf[d++] = ')';
1327 return d;
1330 static void lf_to_crlf(struct msg_data *msg)
1332 char *new;
1333 int i, j, lfnum = 0;
1335 if (msg->data[0] == '\n')
1336 lfnum++;
1337 for (i = 1; i < msg->len; i++) {
1338 if (msg->data[i - 1] != '\r' && msg->data[i] == '\n')
1339 lfnum++;
1342 new = xmalloc(msg->len + lfnum);
1343 if (msg->data[0] == '\n') {
1344 new[0] = '\r';
1345 new[1] = '\n';
1346 i = 1;
1347 j = 2;
1348 } else {
1349 new[0] = msg->data[0];
1350 i = 1;
1351 j = 1;
1353 for ( ; i < msg->len; i++) {
1354 if (msg->data[i] != '\n') {
1355 new[j++] = msg->data[i];
1356 continue;
1358 if (msg->data[i - 1] != '\r')
1359 new[j++] = '\r';
1360 /* otherwise it already had CR before */
1361 new[j++] = '\n';
1363 msg->len += lfnum;
1364 free(msg->data);
1365 msg->data = new;
1368 static int imap_store_msg(struct store *gctx, struct msg_data *data)
1370 struct imap_store *ctx = (struct imap_store *)gctx;
1371 struct imap *imap = ctx->imap;
1372 struct imap_cmd_cb cb;
1373 const char *prefix, *box;
1374 int ret, d;
1375 char flagstr[128];
1377 lf_to_crlf(data);
1378 memset(&cb, 0, sizeof(cb));
1380 cb.dlen = data->len;
1381 cb.data = xmalloc(cb.dlen);
1382 memcpy(cb.data, data->data, data->len);
1384 d = 0;
1385 if (data->flags) {
1386 d = imap_make_flags(data->flags, flagstr);
1387 flagstr[d++] = ' ';
1389 flagstr[d] = 0;
1391 box = gctx->name;
1392 prefix = !strcmp(box, "INBOX") ? "" : ctx->prefix;
1393 cb.create = 0;
1394 ret = imap_exec_m(ctx, &cb, "APPEND \"%s%s\" %s", prefix, box, flagstr);
1395 imap->caps = imap->rcaps;
1396 if (ret != DRV_OK)
1397 return ret;
1398 gctx->count++;
1400 return DRV_OK;
1403 static void encode_html_chars(struct strbuf *p)
1405 int i;
1406 for (i = 0; i < p->len; i++) {
1407 if (p->buf[i] == '&')
1408 strbuf_splice(p, i, 1, "&amp;", 5);
1409 if (p->buf[i] == '<')
1410 strbuf_splice(p, i, 1, "&lt;", 4);
1411 if (p->buf[i] == '>')
1412 strbuf_splice(p, i, 1, "&gt;", 4);
1413 if (p->buf[i] == '"')
1414 strbuf_splice(p, i, 1, "&quot;", 6);
1417 static void wrap_in_html(struct msg_data *msg)
1419 struct strbuf buf = STRBUF_INIT;
1420 struct strbuf **lines;
1421 struct strbuf **p;
1422 static char *content_type = "Content-Type: text/html;\n";
1423 static char *pre_open = "<pre>\n";
1424 static char *pre_close = "</pre>\n";
1425 int added_header = 0;
1427 strbuf_attach(&buf, msg->data, msg->len, msg->len);
1428 lines = strbuf_split(&buf, '\n');
1429 strbuf_release(&buf);
1430 for (p = lines; *p; p++) {
1431 if (! added_header) {
1432 if ((*p)->len == 1 && *((*p)->buf) == '\n') {
1433 strbuf_addstr(&buf, content_type);
1434 strbuf_addbuf(&buf, *p);
1435 strbuf_addstr(&buf, pre_open);
1436 added_header = 1;
1437 continue;
1440 else
1441 encode_html_chars(*p);
1442 strbuf_addbuf(&buf, *p);
1444 strbuf_addstr(&buf, pre_close);
1445 strbuf_list_free(lines);
1446 msg->len = buf.len;
1447 msg->data = strbuf_detach(&buf, NULL);
1450 #define CHUNKSIZE 0x1000
1452 static int read_message(FILE *f, struct msg_data *msg)
1454 struct strbuf buf = STRBUF_INIT;
1456 memset(msg, 0, sizeof(*msg));
1458 do {
1459 if (strbuf_fread(&buf, CHUNKSIZE, f) <= 0)
1460 break;
1461 } while (!feof(f));
1463 msg->len = buf.len;
1464 msg->data = strbuf_detach(&buf, NULL);
1465 return msg->len;
1468 static int count_messages(struct msg_data *msg)
1470 int count = 0;
1471 char *p = msg->data;
1473 while (1) {
1474 if (!prefixcmp(p, "From ")) {
1475 p = strstr(p+5, "\nFrom: ");
1476 if (!p) break;
1477 p = strstr(p+7, "\nDate: ");
1478 if (!p) break;
1479 p = strstr(p+7, "\nSubject: ");
1480 if (!p) break;
1481 p += 10;
1482 count++;
1484 p = strstr(p+5, "\nFrom ");
1485 if (!p)
1486 break;
1487 p++;
1489 return count;
1492 static int split_msg(struct msg_data *all_msgs, struct msg_data *msg, int *ofs)
1494 char *p, *data;
1496 memset(msg, 0, sizeof *msg);
1497 if (*ofs >= all_msgs->len)
1498 return 0;
1500 data = &all_msgs->data[*ofs];
1501 msg->len = all_msgs->len - *ofs;
1503 if (msg->len < 5 || prefixcmp(data, "From "))
1504 return 0;
1506 p = strchr(data, '\n');
1507 if (p) {
1508 p = &p[1];
1509 msg->len -= p-data;
1510 *ofs += p-data;
1511 data = p;
1514 p = strstr(data, "\nFrom ");
1515 if (p)
1516 msg->len = &p[1] - data;
1518 msg->data = xmemdupz(data, msg->len);
1519 *ofs += msg->len;
1520 return 1;
1523 static char *imap_folder;
1525 static int git_imap_config(const char *key, const char *val, void *cb)
1527 char imap_key[] = "imap.";
1529 if (strncmp(key, imap_key, sizeof imap_key - 1))
1530 return 0;
1532 key += sizeof imap_key - 1;
1534 /* check booleans first, and barf on others */
1535 if (!strcmp("sslverify", key))
1536 server.ssl_verify = git_config_bool(key, val);
1537 else if (!strcmp("preformattedhtml", key))
1538 server.use_html = git_config_bool(key, val);
1539 else if (!val)
1540 return config_error_nonbool(key);
1542 if (!strcmp("folder", key)) {
1543 imap_folder = xstrdup(val);
1544 } else if (!strcmp("host", key)) {
1545 if (!prefixcmp(val, "imap:"))
1546 val += 5;
1547 else if (!prefixcmp(val, "imaps:")) {
1548 val += 6;
1549 server.use_ssl = 1;
1551 if (!prefixcmp(val, "//"))
1552 val += 2;
1553 server.host = xstrdup(val);
1554 } else if (!strcmp("user", key))
1555 server.user = xstrdup(val);
1556 else if (!strcmp("pass", key))
1557 server.pass = xstrdup(val);
1558 else if (!strcmp("port", key))
1559 server.port = git_config_int(key, val);
1560 else if (!strcmp("tunnel", key))
1561 server.tunnel = xstrdup(val);
1562 else if (!strcmp("authmethod", key))
1563 server.auth_method = xstrdup(val);
1565 return 0;
1568 int main(int argc, char **argv)
1570 struct msg_data all_msgs, msg;
1571 struct store *ctx = NULL;
1572 int ofs = 0;
1573 int r;
1574 int total, n = 0;
1575 int nongit_ok;
1577 git_extract_argv0_path(argv[0]);
1579 git_setup_gettext();
1581 if (argc != 1)
1582 usage(imap_send_usage);
1584 setup_git_directory_gently(&nongit_ok);
1585 git_config(git_imap_config, NULL);
1587 if (!server.port)
1588 server.port = server.use_ssl ? 993 : 143;
1590 if (!imap_folder) {
1591 fprintf(stderr, "no imap store specified\n");
1592 return 1;
1594 if (!server.host) {
1595 if (!server.tunnel) {
1596 fprintf(stderr, "no imap host specified\n");
1597 return 1;
1599 server.host = "tunnel";
1602 /* read the messages */
1603 if (!read_message(stdin, &all_msgs)) {
1604 fprintf(stderr, "nothing to send\n");
1605 return 1;
1608 total = count_messages(&all_msgs);
1609 if (!total) {
1610 fprintf(stderr, "no messages to send\n");
1611 return 1;
1614 /* write it to the imap server */
1615 ctx = imap_open_store(&server);
1616 if (!ctx) {
1617 fprintf(stderr, "failed to open store\n");
1618 return 1;
1621 fprintf(stderr, "sending %d message%s\n", total, (total != 1) ? "s" : "");
1622 ctx->name = imap_folder;
1623 while (1) {
1624 unsigned percent = n * 100 / total;
1625 fprintf(stderr, "%4u%% (%d/%d) done\r", percent, n, total);
1626 if (!split_msg(&all_msgs, &msg, &ofs))
1627 break;
1628 if (server.use_html)
1629 wrap_in_html(&msg);
1630 r = imap_store_msg(ctx, &msg);
1631 if (r != DRV_OK)
1632 break;
1633 n++;
1635 fprintf(stderr, "\n");
1637 imap_close_store(ctx);
1639 return 0;