Merge branch 'jk/fully-peeled-packed-ref' into maint-1.8.1
[git/jnareb-git.git] / imap-send.c
blob49ba841cbaabb6da9bfab1bf54f63a50c3069dd9
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 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
375 * SNI (RFC4366)
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);
380 if (ret != 1)
381 warning("SSL_set_tlsext_host_name(%s) failed.", server.host);
382 #endif
384 ret = SSL_connect(sock->ssl);
385 if (ret <= 0) {
386 socket_perror("SSL_connect", sock, ret);
387 return -1;
390 if (verify) {
391 /* make sure the hostname matches that of the certificate */
392 cert = SSL_get_peer_certificate(sock->ssl);
393 if (!cert)
394 return error("unable to get peer certificate.");
395 if (verify_hostname(cert, server.host) < 0)
396 return -1;
399 return 0;
401 #endif
403 static int socket_read(struct imap_socket *sock, char *buf, int len)
405 ssize_t n;
406 #ifndef NO_OPENSSL
407 if (sock->ssl)
408 n = SSL_read(sock->ssl, buf, len);
409 else
410 #endif
411 n = xread(sock->fd[0], buf, len);
412 if (n <= 0) {
413 socket_perror("read", sock, n);
414 close(sock->fd[0]);
415 close(sock->fd[1]);
416 sock->fd[0] = sock->fd[1] = -1;
418 return n;
421 static int socket_write(struct imap_socket *sock, const char *buf, int len)
423 int n;
424 #ifndef NO_OPENSSL
425 if (sock->ssl)
426 n = SSL_write(sock->ssl, buf, len);
427 else
428 #endif
429 n = write_in_full(sock->fd[1], buf, len);
430 if (n != len) {
431 socket_perror("write", sock, n);
432 close(sock->fd[0]);
433 close(sock->fd[1]);
434 sock->fd[0] = sock->fd[1] = -1;
436 return n;
439 static void socket_shutdown(struct imap_socket *sock)
441 #ifndef NO_OPENSSL
442 if (sock->ssl) {
443 SSL_shutdown(sock->ssl);
444 SSL_free(sock->ssl);
446 #endif
447 close(sock->fd[0]);
448 close(sock->fd[1]);
451 /* simple line buffering */
452 static int buffer_gets(struct imap_buffer *b, char **s)
454 int n;
455 int start = b->offset;
457 *s = b->buf + start;
459 for (;;) {
460 /* make sure we have enough data to read the \r\n sequence */
461 if (b->offset + 1 >= b->bytes) {
462 if (start) {
463 /* shift down used bytes */
464 *s = b->buf;
466 assert(start <= b->bytes);
467 n = b->bytes - start;
469 if (n)
470 memmove(b->buf, b->buf + start, n);
471 b->offset -= start;
472 b->bytes = n;
473 start = 0;
476 n = socket_read(&b->sock, b->buf + b->bytes,
477 sizeof(b->buf) - b->bytes);
479 if (n <= 0)
480 return -1;
482 b->bytes += n;
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 */
490 if (Verbose)
491 puts(*s);
492 return 0;
496 b->offset++;
498 /* not reached */
501 static void imap_info(const char *msg, ...)
503 va_list va;
505 if (!Quiet) {
506 va_start(va, msg);
507 vprintf(msg, va);
508 va_end(va);
509 fflush(stdout);
513 static void imap_warn(const char *msg, ...)
515 va_list va;
517 if (Quiet < 2) {
518 va_start(va, msg);
519 vfprintf(stderr, msg, va);
520 va_end(va);
524 static char *next_arg(char **s)
526 char *ret;
528 if (!s || !*s)
529 return NULL;
530 while (isspace((unsigned char) **s))
531 (*s)++;
532 if (!**s) {
533 *s = NULL;
534 return NULL;
536 if (**s == '"') {
537 ++*s;
538 ret = *s;
539 *s = strchr(*s, '"');
540 } else {
541 ret = *s;
542 while (**s && !isspace((unsigned char) **s))
543 (*s)++;
545 if (*s) {
546 if (**s)
547 *(*s)++ = 0;
548 if (!**s)
549 *s = NULL;
551 return ret;
554 static void free_generic_messages(struct message *msgs)
556 struct message *tmsg;
558 for (; msgs; msgs = tmsg) {
559 tmsg = msgs->next;
560 free(msgs);
564 static int nfsnprintf(char *buf, int blen, const char *fmt, ...)
566 int ret;
567 va_list va;
569 va_start(va, fmt);
570 if (blen <= 0 || (unsigned)(ret = vsnprintf(buf, blen, fmt, va)) >= (unsigned)blen)
571 die("Fatal: buffer too small. Please report a bug.");
572 va_end(va);
573 return ret;
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;
582 int n, bufl;
583 char buf[1024];
585 cmd = xmalloc(sizeof(struct imap_cmd));
586 nfvasprintf(&cmd->cmd, fmt, ap);
587 cmd->tag = ++imap->nexttag;
589 if (cb)
590 cmd->cb = *cb;
591 else
592 memset(&cmd->cb, 0, sizeof(cmd->cb));
594 while (imap->literal_pending)
595 get_cmd_result(ctx, NULL);
597 if (!cmd->cb.data)
598 bufl = nfsnprintf(buf, sizeof(buf), "%d %s\r\n", cmd->tag, cmd->cmd);
599 else
600 bufl = nfsnprintf(buf, sizeof(buf), "%d %s{%d%s}\r\n",
601 cmd->tag, cmd->cmd, cmd->cb.dlen,
602 CAP(LITERALPLUS) ? "+" : "");
604 if (Verbose) {
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);
609 else
610 printf(">>> %d LOGIN <user> <pass>\n", cmd->tag);
612 if (socket_write(&imap->buf.sock, buf, bufl) != bufl) {
613 free(cmd->cmd);
614 free(cmd);
615 if (cb)
616 free(cb->data);
617 return NULL;
619 if (cmd->cb.data) {
620 if (CAP(LITERALPLUS)) {
621 n = socket_write(&imap->buf.sock, cmd->cb.data, cmd->cb.dlen);
622 free(cmd->cb.data);
623 if (n != cmd->cb.dlen ||
624 socket_write(&imap->buf.sock, "\r\n", 2) != 2) {
625 free(cmd->cmd);
626 free(cmd);
627 return NULL;
629 cmd->cb.data = NULL;
630 } else
631 imap->literal_pending = 1;
632 } else if (cmd->cb.cont)
633 imap->literal_pending = 1;
634 cmd->next = NULL;
635 *imap->in_progress_append = cmd;
636 imap->in_progress_append = &cmd->next;
637 imap->num_in_progress++;
638 return cmd;
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;
647 va_list ap;
649 va_start(ap, fmt);
650 ret = v_issue_imap_cmd(ctx, cb, fmt, ap);
651 va_end(ap);
652 return ret;
655 __attribute__((format (printf, 3, 4)))
656 static int imap_exec(struct imap_store *ctx, struct imap_cmd_cb *cb,
657 const char *fmt, ...)
659 va_list ap;
660 struct imap_cmd *cmdp;
662 va_start(ap, fmt);
663 cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
664 va_end(ap);
665 if (!cmdp)
666 return RESP_BAD;
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, ...)
675 va_list ap;
676 struct imap_cmd *cmdp;
678 va_start(ap, fmt);
679 cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
680 va_end(ap);
681 if (!cmdp)
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) {
706 tmp = list->next;
707 if (is_list(list))
708 free_list(list->child);
709 else if (is_atom(list))
710 free(list->val);
711 free(list);
715 static int parse_imap_list_l(struct imap *imap, char **sp, struct imap_list **curp, int level)
717 struct imap_list *cur;
718 char *s = *sp, *p;
719 int n, bytes;
721 for (;;) {
722 while (isspace((unsigned char)*s))
723 s++;
724 if (level && *s == ')') {
725 s++;
726 break;
728 *curp = cur = xmalloc(sizeof(*cur));
729 curp = &cur->next;
730 cur->val = NULL; /* for clean bail */
731 if (*s == '(') {
732 /* sublist */
733 s++;
734 cur->val = LIST;
735 if (parse_imap_list_l(imap, &s, &cur->child, level + 1))
736 goto bail;
737 } else if (imap && *s == '{') {
738 /* literal */
739 bytes = cur->len = strtol(s + 1, &s, 10);
740 if (*s != '}')
741 goto bail;
743 s = cur->val = xmalloc(cur->len);
745 /* dump whats left over in the input buffer */
746 n = imap->buf.bytes - imap->buf.offset;
748 if (n > bytes)
749 /* the entire message fit in the buffer */
750 n = bytes;
752 memcpy(s, imap->buf.buf + imap->buf.offset, n);
753 s += n;
754 bytes -= n;
756 /* mark that we used part of the buffer */
757 imap->buf.offset += n;
759 /* now read the rest of the message */
760 while (bytes > 0) {
761 if ((n = socket_read(&imap->buf.sock, s, bytes)) <= 0)
762 goto bail;
763 s += n;
764 bytes -= n;
767 if (buffer_gets(&imap->buf, &s))
768 goto bail;
769 } else if (*s == '"') {
770 /* quoted string */
771 s++;
772 p = s;
773 for (; *s != '"'; s++)
774 if (!*s)
775 goto bail;
776 cur->len = s - p;
777 s++;
778 cur->val = xmemdupz(p, cur->len);
779 } else {
780 /* atom */
781 p = s;
782 for (; *s && !isspace((unsigned char)*s); s++)
783 if (level && *s == ')')
784 break;
785 cur->len = s - p;
786 if (cur->len == 3 && !memcmp("NIL", p, 3))
787 cur->val = NIL;
788 else
789 cur->val = xmemdupz(p, cur->len);
792 if (!level)
793 break;
794 if (!*s)
795 goto bail;
797 *sp = s;
798 *curp = NULL;
799 return 0;
801 bail:
802 *curp = NULL;
803 return -1;
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))
811 return head;
812 free_list(head);
813 return NULL;
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)
823 char *arg;
824 unsigned i;
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,
835 char *s)
837 struct imap *imap = ctx->imap;
838 char *arg, *p;
840 if (*s != '[')
841 return RESP_OK; /* no response code */
842 s++;
843 if (!(p = strchr(s, ']'))) {
844 fprintf(stderr, "IMAP error: malformed response code\n");
845 return RESP_BAD;
847 *p++ = 0;
848 arg = next_arg(&s);
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");
852 return RESP_BAD;
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");
857 return RESP_BAD;
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
863 * to the user
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");
871 return RESP_BAD;
874 return RESP_OK;
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;
884 for (;;) {
885 if (buffer_gets(&imap->buf, &cmd))
886 return RESP_BAD;
888 arg = next_arg(&cmd);
889 if (*arg == '*') {
890 arg = next_arg(&cmd);
891 if (!arg) {
892 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
893 return RESP_BAD;
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)
903 return resp;
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);
911 } else {
912 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
913 return RESP_BAD;
915 } else if (!imap->in_progress) {
916 fprintf(stderr, "IMAP error: unexpected reply: %s %s\n", arg, cmd ? cmd : "");
917 return RESP_BAD;
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));
923 if (cmdp->cb.data) {
924 n = socket_write(&imap->buf.sock, cmdp->cb.data, cmdp->cb.dlen);
925 free(cmdp->cb.data);
926 cmdp->cb.data = NULL;
927 if (n != (int)cmdp->cb.dlen)
928 return RESP_BAD;
929 } else if (cmdp->cb.cont) {
930 if (cmdp->cb.cont(ctx, cmdp, cmd))
931 return RESP_BAD;
932 } else {
933 fprintf(stderr, "IMAP error: unexpected command continuation request\n");
934 return RESP_BAD;
936 if (socket_write(&imap->buf.sock, "\r\n", 2) != 2)
937 return RESP_BAD;
938 if (!cmdp->cb.cont)
939 imap->literal_pending = 0;
940 if (!tcmd)
941 return DRV_OK;
942 } else {
943 tag = atoi(arg);
944 for (pcmdp = &imap->in_progress; (cmdp = *pcmdp); pcmdp = &cmdp->next)
945 if (cmdp->tag == tag)
946 goto gottag;
947 fprintf(stderr, "IMAP error: unexpected tag %s\n", arg);
948 return RESP_BAD;
949 gottag:
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))
957 resp = DRV_OK;
958 else {
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)) {
963 resp = RESP_BAD;
964 goto normal;
966 /* not waiting here violates the spec, but a server that does not
967 grok this nonetheless violates it too. */
968 cmdp->cb.create = 0;
969 if (!(ncmdp = issue_imap_cmd(ctx, &cmdp->cb, "%s", cmdp->cmd))) {
970 resp = RESP_BAD;
971 goto normal;
973 free(cmdp->cmd);
974 free(cmdp);
975 if (!tcmd)
976 return 0; /* ignored */
977 if (cmdp == tcmd)
978 tcmd = ncmdp;
979 continue;
981 resp = RESP_NO;
982 } else /*if (!strcmp("BAD", arg))*/
983 resp = RESP_BAD;
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)
990 resp = resp2;
991 normal:
992 if (cmdp->cb.done)
993 cmdp->cb.done(ctx, cmdp, resp);
994 free(cmdp->cb.data);
995 free(cmdp->cmd);
996 free(cmdp);
997 if (!tcmd || tcmd == cmdp)
998 return resp;
1001 /* not reached */
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);
1015 free(imap);
1018 static void imap_close_store(struct store *ctx)
1020 imap_close_server((struct imap_store *)ctx);
1021 free_generic_messages(ctx->msgs);
1022 free(ctx);
1025 #ifndef NO_OPENSSL
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;
1040 HMAC_CTX hmac;
1041 unsigned char hash[16];
1042 char hex[33];
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);
1060 hex[32] = 0;
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;
1080 #else
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.");
1088 #endif
1090 static int auth_cram_md5(struct imap_store *ctx, struct imap_cmd *cmd, const char *prompt)
1092 int ret;
1093 char *response;
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");
1101 free(response);
1103 return 0;
1106 static struct store *imap_open_store(struct imap_server_conf *srvc)
1108 struct imap_store *ctx;
1109 struct imap *imap;
1110 char *arg, *rsp;
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 */
1121 if (srvc->tunnel) {
1122 const char *argv[] = { srvc->tunnel, NULL };
1123 struct child_process tunnel = {NULL};
1125 imap_info("Starting tunnel '%s'... ", srvc->tunnel);
1127 tunnel.argv = argv;
1128 tunnel.use_shell = 1;
1129 tunnel.in = -1;
1130 tunnel.out = -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;
1137 imap_info("ok\n");
1138 } else {
1139 #ifndef NO_IPV6
1140 struct addrinfo hints, *ai0, *ai;
1141 int gai;
1142 char portstr[6];
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);
1152 if (gai) {
1153 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai));
1154 goto bail;
1156 imap_info("ok\n");
1158 for (ai0 = ai; ai; ai = ai->ai_next) {
1159 char addr[NI_MAXHOST];
1161 s = socket(ai->ai_family, ai->ai_socktype,
1162 ai->ai_protocol);
1163 if (s < 0)
1164 continue;
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) {
1171 close(s);
1172 s = -1;
1173 perror("connect");
1174 continue;
1177 break;
1179 freeaddrinfo(ai0);
1180 #else /* NO_IPV6 */
1181 struct hostent *he;
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);
1190 if (!he) {
1191 perror("gethostbyname");
1192 goto bail;
1194 imap_info("ok\n");
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))) {
1202 close(s);
1203 s = -1;
1204 perror("connect");
1206 #endif
1207 if (s < 0) {
1208 fputs("Error: unable to connect to server.\n", stderr);
1209 goto bail;
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)) {
1217 close(s);
1218 goto bail;
1220 imap_info("ok\n");
1223 /* read the greeting string */
1224 if (buffer_gets(&imap->buf, &rsp)) {
1225 fprintf(stderr, "IMAP error: no greeting response\n");
1226 goto bail;
1228 arg = next_arg(&rsp);
1229 if (!arg || *arg != '*' || (arg = next_arg(&rsp)) == NULL) {
1230 fprintf(stderr, "IMAP error: invalid greeting response\n");
1231 goto bail;
1233 preauth = 0;
1234 if (!strcmp("PREAUTH", arg))
1235 preauth = 1;
1236 else if (strcmp("OK", arg) != 0) {
1237 fprintf(stderr, "IMAP error: unknown greeting response\n");
1238 goto bail;
1240 parse_response_code(ctx, NULL, rsp);
1241 if (!imap->caps && imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1242 goto bail;
1244 if (!preauth) {
1245 #ifndef NO_OPENSSL
1246 if (!srvc->use_ssl && CAP(STARTTLS)) {
1247 if (imap_exec(ctx, NULL, "STARTTLS") != RESP_OK)
1248 goto bail;
1249 if (ssl_socket_connect(&imap->buf.sock, 1,
1250 srvc->ssl_verify))
1251 goto bail;
1252 /* capabilities may have changed, so get the new capabilities */
1253 if (imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1254 goto bail;
1256 #endif
1257 imap_info("Logging in...\n");
1258 if (!srvc->user) {
1259 fprintf(stderr, "Skipping server %s, no user\n", srvc->host);
1260 goto bail;
1262 if (!srvc->pass) {
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);
1267 if (!*arg) {
1268 fprintf(stderr, "Skipping account %s@%s, no password\n", srvc->user, srvc->host);
1269 goto bail;
1272 * getpass() returns a pointer to a static buffer. make a copy
1273 * for long term storage.
1275 srvc->pass = xstrdup(arg);
1277 if (CAP(NOLOGIN)) {
1278 fprintf(stderr, "Skipping account %s@%s, server forbids LOGIN\n", srvc->user, srvc->host);
1279 goto bail;
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);
1290 goto bail;
1292 /* CRAM-MD5 */
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");
1298 goto bail;
1300 } else {
1301 fprintf(stderr, "Unknown authentication method:%s\n", srvc->host);
1302 goto bail;
1304 } else {
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");
1310 goto bail;
1313 } /* !preauth */
1315 ctx->prefix = "";
1316 ctx->trashnc = 1;
1317 return (struct store *)ctx;
1319 bail:
1320 imap_close_store(&ctx->gen);
1321 return NULL;
1324 static int imap_make_flags(int flags, char *buf)
1326 const char *s;
1327 unsigned i, d;
1329 for (i = d = 0; i < ARRAY_SIZE(Flags); i++)
1330 if (flags & (1 << i)) {
1331 buf[d++] = ' ';
1332 buf[d++] = '\\';
1333 for (s = Flags[i]; *s; s++)
1334 buf[d++] = *s;
1336 buf[0] = '(';
1337 buf[d++] = ')';
1338 return d;
1341 static void lf_to_crlf(struct msg_data *msg)
1343 char *new;
1344 int i, j, lfnum = 0;
1346 if (msg->data[0] == '\n')
1347 lfnum++;
1348 for (i = 1; i < msg->len; i++) {
1349 if (msg->data[i - 1] != '\r' && msg->data[i] == '\n')
1350 lfnum++;
1353 new = xmalloc(msg->len + lfnum);
1354 if (msg->data[0] == '\n') {
1355 new[0] = '\r';
1356 new[1] = '\n';
1357 i = 1;
1358 j = 2;
1359 } else {
1360 new[0] = msg->data[0];
1361 i = 1;
1362 j = 1;
1364 for ( ; i < msg->len; i++) {
1365 if (msg->data[i] != '\n') {
1366 new[j++] = msg->data[i];
1367 continue;
1369 if (msg->data[i - 1] != '\r')
1370 new[j++] = '\r';
1371 /* otherwise it already had CR before */
1372 new[j++] = '\n';
1374 msg->len += lfnum;
1375 free(msg->data);
1376 msg->data = new;
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;
1385 int ret, d;
1386 char flagstr[128];
1388 lf_to_crlf(data);
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);
1395 d = 0;
1396 if (data->flags) {
1397 d = imap_make_flags(data->flags, flagstr);
1398 flagstr[d++] = ' ';
1400 flagstr[d] = 0;
1402 box = gctx->name;
1403 prefix = !strcmp(box, "INBOX") ? "" : ctx->prefix;
1404 cb.create = 0;
1405 ret = imap_exec_m(ctx, &cb, "APPEND \"%s%s\" %s", prefix, box, flagstr);
1406 imap->caps = imap->rcaps;
1407 if (ret != DRV_OK)
1408 return ret;
1409 gctx->count++;
1411 return DRV_OK;
1414 static void encode_html_chars(struct strbuf *p)
1416 int i;
1417 for (i = 0; i < p->len; i++) {
1418 if (p->buf[i] == '&')
1419 strbuf_splice(p, i, 1, "&amp;", 5);
1420 if (p->buf[i] == '<')
1421 strbuf_splice(p, i, 1, "&lt;", 4);
1422 if (p->buf[i] == '>')
1423 strbuf_splice(p, i, 1, "&gt;", 4);
1424 if (p->buf[i] == '"')
1425 strbuf_splice(p, i, 1, "&quot;", 6);
1428 static void wrap_in_html(struct msg_data *msg)
1430 struct strbuf buf = STRBUF_INIT;
1431 struct strbuf **lines;
1432 struct strbuf **p;
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);
1447 added_header = 1;
1448 continue;
1451 else
1452 encode_html_chars(*p);
1453 strbuf_addbuf(&buf, *p);
1455 strbuf_addstr(&buf, pre_close);
1456 strbuf_list_free(lines);
1457 msg->len = buf.len;
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));
1469 do {
1470 if (strbuf_fread(&buf, CHUNKSIZE, f) <= 0)
1471 break;
1472 } while (!feof(f));
1474 msg->len = buf.len;
1475 msg->data = strbuf_detach(&buf, NULL);
1476 return msg->len;
1479 static int count_messages(struct msg_data *msg)
1481 int count = 0;
1482 char *p = msg->data;
1484 while (1) {
1485 if (!prefixcmp(p, "From ")) {
1486 p = strstr(p+5, "\nFrom: ");
1487 if (!p) break;
1488 p = strstr(p+7, "\nDate: ");
1489 if (!p) break;
1490 p = strstr(p+7, "\nSubject: ");
1491 if (!p) break;
1492 p += 10;
1493 count++;
1495 p = strstr(p+5, "\nFrom ");
1496 if (!p)
1497 break;
1498 p++;
1500 return count;
1503 static int split_msg(struct msg_data *all_msgs, struct msg_data *msg, int *ofs)
1505 char *p, *data;
1507 memset(msg, 0, sizeof *msg);
1508 if (*ofs >= all_msgs->len)
1509 return 0;
1511 data = &all_msgs->data[*ofs];
1512 msg->len = all_msgs->len - *ofs;
1514 if (msg->len < 5 || prefixcmp(data, "From "))
1515 return 0;
1517 p = strchr(data, '\n');
1518 if (p) {
1519 p = &p[1];
1520 msg->len -= p-data;
1521 *ofs += p-data;
1522 data = p;
1525 p = strstr(data, "\nFrom ");
1526 if (p)
1527 msg->len = &p[1] - data;
1529 msg->data = xmemdupz(data, msg->len);
1530 *ofs += msg->len;
1531 return 1;
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))
1541 return 0;
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);
1550 else if (!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:"))
1557 val += 5;
1558 else if (!prefixcmp(val, "imaps:")) {
1559 val += 6;
1560 server.use_ssl = 1;
1562 if (!prefixcmp(val, "//"))
1563 val += 2;
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);
1576 return 0;
1579 int main(int argc, char **argv)
1581 struct msg_data all_msgs, msg;
1582 struct store *ctx = NULL;
1583 int ofs = 0;
1584 int r;
1585 int total, n = 0;
1586 int nongit_ok;
1588 git_extract_argv0_path(argv[0]);
1590 git_setup_gettext();
1592 if (argc != 1)
1593 usage(imap_send_usage);
1595 setup_git_directory_gently(&nongit_ok);
1596 git_config(git_imap_config, NULL);
1598 if (!server.port)
1599 server.port = server.use_ssl ? 993 : 143;
1601 if (!imap_folder) {
1602 fprintf(stderr, "no imap store specified\n");
1603 return 1;
1605 if (!server.host) {
1606 if (!server.tunnel) {
1607 fprintf(stderr, "no imap host specified\n");
1608 return 1;
1610 server.host = "tunnel";
1613 /* read the messages */
1614 if (!read_message(stdin, &all_msgs)) {
1615 fprintf(stderr, "nothing to send\n");
1616 return 1;
1619 total = count_messages(&all_msgs);
1620 if (!total) {
1621 fprintf(stderr, "no messages to send\n");
1622 return 1;
1625 /* write it to the imap server */
1626 ctx = imap_open_store(&server);
1627 if (!ctx) {
1628 fprintf(stderr, "failed to open store\n");
1629 return 1;
1632 fprintf(stderr, "sending %d message%s\n", total, (total != 1) ? "s" : "");
1633 ctx->name = imap_folder;
1634 while (1) {
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))
1638 break;
1639 if (server.use_html)
1640 wrap_in_html(&msg);
1641 r = imap_store_msg(ctx, &msg);
1642 if (r != DRV_OK)
1643 break;
1644 n++;
1646 fprintf(stderr, "\n");
1648 imap_close_store(ctx);
1650 return 0;