Merge branch 'ma/test-libcurl-prereq' into maint-2.46
[git/gitster.git] / imap-send.c
blob01404e5047c83167275a02c36836e730d3db8e20
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, see <https://www.gnu.org/licenses/>.
24 #include "git-compat-util.h"
25 #include "config.h"
26 #include "credential.h"
27 #include "gettext.h"
28 #include "run-command.h"
29 #include "parse-options.h"
30 #include "setup.h"
31 #include "strbuf.h"
32 #if defined(NO_OPENSSL) && !defined(HAVE_OPENSSL_CSPRNG)
33 typedef void *SSL;
34 #endif
35 #ifdef USE_CURL_FOR_IMAP_SEND
36 #include "http.h"
37 #endif
39 #if defined(USE_CURL_FOR_IMAP_SEND)
40 /* Always default to curl if it's available. */
41 #define USE_CURL_DEFAULT 1
42 #else
43 /* We don't have curl, so continue to use the historical implementation */
44 #define USE_CURL_DEFAULT 0
45 #endif
47 static int verbosity;
48 static int use_curl = USE_CURL_DEFAULT;
50 static const char * const imap_send_usage[] = { "git imap-send [-v] [-q] [--[no-]curl] < <mbox>", NULL };
52 static struct option imap_send_options[] = {
53 OPT__VERBOSITY(&verbosity),
54 OPT_BOOL(0, "curl", &use_curl, "use libcurl to communicate with the IMAP server"),
55 OPT_END()
58 #undef DRV_OK
59 #define DRV_OK 0
60 #define DRV_MSG_BAD -1
61 #define DRV_BOX_BAD -2
62 #define DRV_STORE_BAD -3
64 __attribute__((format (printf, 1, 2)))
65 static void imap_info(const char *, ...);
66 __attribute__((format (printf, 1, 2)))
67 static void imap_warn(const char *, ...);
69 static char *next_arg(char **);
71 struct imap_server_conf {
72 char *tunnel;
73 char *host;
74 int port;
75 char *folder;
76 char *user;
77 char *pass;
78 int use_ssl;
79 int ssl_verify;
80 int use_html;
81 char *auth_method;
84 struct imap_socket {
85 int fd[2];
86 SSL *ssl;
89 struct imap_buffer {
90 struct imap_socket sock;
91 int bytes;
92 int offset;
93 char buf[1024];
96 struct imap_cmd;
98 struct imap {
99 int uidnext; /* from SELECT responses */
100 unsigned caps, rcaps; /* CAPABILITY results */
101 /* command queue */
102 int nexttag, num_in_progress, literal_pending;
103 struct imap_cmd *in_progress, **in_progress_append;
104 struct imap_buffer buf; /* this is BIG, so put it last */
107 struct imap_store {
108 const struct imap_server_conf *cfg;
109 /* currently open mailbox */
110 const char *name; /* foreign! maybe preset? */
111 int uidvalidity;
112 struct imap *imap;
113 const char *prefix;
116 struct imap_cmd_cb {
117 int (*cont)(struct imap_store *ctx, const char *prompt);
118 void *ctx;
119 char *data;
120 int dlen;
123 struct imap_cmd {
124 struct imap_cmd *next;
125 struct imap_cmd_cb cb;
126 char *cmd;
127 int tag;
130 #define CAP(cap) (imap->caps & (1 << (cap)))
132 enum CAPABILITY {
133 NOLOGIN = 0,
134 UIDPLUS,
135 LITERALPLUS,
136 NAMESPACE,
137 STARTTLS,
138 AUTH_CRAM_MD5
141 static const char *cap_list[] = {
142 "LOGINDISABLED",
143 "UIDPLUS",
144 "LITERAL+",
145 "NAMESPACE",
146 "STARTTLS",
147 "AUTH=CRAM-MD5",
150 #define RESP_OK 0
151 #define RESP_NO 1
152 #define RESP_BAD 2
154 static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd);
157 #ifndef NO_OPENSSL
158 static void ssl_socket_perror(const char *func)
160 fprintf(stderr, "%s: %s\n", func, ERR_error_string(ERR_get_error(), NULL));
162 #endif
164 static void socket_perror(const char *func, struct imap_socket *sock, int ret)
166 #ifndef NO_OPENSSL
167 if (sock->ssl) {
168 int sslerr = SSL_get_error(sock->ssl, ret);
169 switch (sslerr) {
170 case SSL_ERROR_NONE:
171 break;
172 case SSL_ERROR_SYSCALL:
173 perror("SSL_connect");
174 break;
175 default:
176 ssl_socket_perror("SSL_connect");
177 break;
179 } else
180 #endif
182 if (ret < 0)
183 perror(func);
184 else
185 fprintf(stderr, "%s: unexpected EOF\n", func);
187 /* mark as used to appease -Wunused-parameter with NO_OPENSSL */
188 (void)sock;
191 #ifdef NO_OPENSSL
192 static int ssl_socket_connect(struct imap_socket *sock UNUSED,
193 const struct imap_server_conf *cfg,
194 int use_tls_only UNUSED)
196 fprintf(stderr, "SSL requested but SSL support not compiled in\n");
197 return -1;
200 #else
202 static int host_matches(const char *host, const char *pattern)
204 if (pattern[0] == '*' && pattern[1] == '.') {
205 pattern += 2;
206 if (!(host = strchr(host, '.')))
207 return 0;
208 host++;
211 return *host && *pattern && !strcasecmp(host, pattern);
214 static int verify_hostname(X509 *cert, const char *hostname)
216 int len;
217 X509_NAME *subj;
218 char cname[1000];
219 int i, found;
220 STACK_OF(GENERAL_NAME) *subj_alt_names;
222 /* try the DNS subjectAltNames */
223 found = 0;
224 if ((subj_alt_names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL))) {
225 int num_subj_alt_names = sk_GENERAL_NAME_num(subj_alt_names);
226 for (i = 0; !found && i < num_subj_alt_names; i++) {
227 GENERAL_NAME *subj_alt_name = sk_GENERAL_NAME_value(subj_alt_names, i);
228 if (subj_alt_name->type == GEN_DNS &&
229 strlen((const char *)subj_alt_name->d.ia5->data) == (size_t)subj_alt_name->d.ia5->length &&
230 host_matches(hostname, (const char *)(subj_alt_name->d.ia5->data)))
231 found = 1;
233 sk_GENERAL_NAME_pop_free(subj_alt_names, GENERAL_NAME_free);
235 if (found)
236 return 0;
238 /* try the common name */
239 if (!(subj = X509_get_subject_name(cert)))
240 return error("cannot get certificate subject");
241 if ((len = X509_NAME_get_text_by_NID(subj, NID_commonName, cname, sizeof(cname))) < 0)
242 return error("cannot get certificate common name");
243 if (strlen(cname) == (size_t)len && host_matches(hostname, cname))
244 return 0;
245 return error("certificate owner '%s' does not match hostname '%s'",
246 cname, hostname);
249 static int ssl_socket_connect(struct imap_socket *sock,
250 const struct imap_server_conf *cfg,
251 int use_tls_only)
253 #if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
254 const SSL_METHOD *meth;
255 #else
256 SSL_METHOD *meth;
257 #endif
258 SSL_CTX *ctx;
259 int ret;
260 X509 *cert;
262 SSL_library_init();
263 SSL_load_error_strings();
265 meth = SSLv23_method();
266 if (!meth) {
267 ssl_socket_perror("SSLv23_method");
268 return -1;
271 ctx = SSL_CTX_new(meth);
272 if (!ctx) {
273 ssl_socket_perror("SSL_CTX_new");
274 return -1;
277 if (use_tls_only)
278 SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
280 if (cfg->ssl_verify)
281 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
283 if (!SSL_CTX_set_default_verify_paths(ctx)) {
284 ssl_socket_perror("SSL_CTX_set_default_verify_paths");
285 return -1;
287 sock->ssl = SSL_new(ctx);
288 if (!sock->ssl) {
289 ssl_socket_perror("SSL_new");
290 return -1;
292 if (!SSL_set_rfd(sock->ssl, sock->fd[0])) {
293 ssl_socket_perror("SSL_set_rfd");
294 return -1;
296 if (!SSL_set_wfd(sock->ssl, sock->fd[1])) {
297 ssl_socket_perror("SSL_set_wfd");
298 return -1;
301 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
303 * SNI (RFC4366)
304 * OpenSSL does not document this function, but the implementation
305 * returns 1 on success, 0 on failure after calling SSLerr().
307 ret = SSL_set_tlsext_host_name(sock->ssl, cfg->host);
308 if (ret != 1)
309 warning("SSL_set_tlsext_host_name(%s) failed.", cfg->host);
310 #endif
312 ret = SSL_connect(sock->ssl);
313 if (ret <= 0) {
314 socket_perror("SSL_connect", sock, ret);
315 return -1;
318 if (cfg->ssl_verify) {
319 /* make sure the hostname matches that of the certificate */
320 cert = SSL_get_peer_certificate(sock->ssl);
321 if (!cert)
322 return error("unable to get peer certificate.");
323 if (verify_hostname(cert, cfg->host) < 0)
324 return -1;
327 return 0;
329 #endif
331 static int socket_read(struct imap_socket *sock, char *buf, int len)
333 ssize_t n;
334 #ifndef NO_OPENSSL
335 if (sock->ssl)
336 n = SSL_read(sock->ssl, buf, len);
337 else
338 #endif
339 n = xread(sock->fd[0], buf, len);
340 if (n <= 0) {
341 socket_perror("read", sock, n);
342 close(sock->fd[0]);
343 close(sock->fd[1]);
344 sock->fd[0] = sock->fd[1] = -1;
346 return n;
349 static int socket_write(struct imap_socket *sock, const char *buf, int len)
351 int n;
352 #ifndef NO_OPENSSL
353 if (sock->ssl)
354 n = SSL_write(sock->ssl, buf, len);
355 else
356 #endif
357 n = write_in_full(sock->fd[1], buf, len);
358 if (n != len) {
359 socket_perror("write", sock, n);
360 close(sock->fd[0]);
361 close(sock->fd[1]);
362 sock->fd[0] = sock->fd[1] = -1;
364 return n;
367 static void socket_shutdown(struct imap_socket *sock)
369 #ifndef NO_OPENSSL
370 if (sock->ssl) {
371 SSL_shutdown(sock->ssl);
372 SSL_free(sock->ssl);
374 #endif
375 close(sock->fd[0]);
376 close(sock->fd[1]);
379 /* simple line buffering */
380 static int buffer_gets(struct imap_buffer *b, char **s)
382 int n;
383 int start = b->offset;
385 *s = b->buf + start;
387 for (;;) {
388 /* make sure we have enough data to read the \r\n sequence */
389 if (b->offset + 1 >= b->bytes) {
390 if (start) {
391 /* shift down used bytes */
392 *s = b->buf;
394 assert(start <= b->bytes);
395 n = b->bytes - start;
397 if (n)
398 memmove(b->buf, b->buf + start, n);
399 b->offset -= start;
400 b->bytes = n;
401 start = 0;
404 n = socket_read(&b->sock, b->buf + b->bytes,
405 sizeof(b->buf) - b->bytes);
407 if (n <= 0)
408 return -1;
410 b->bytes += n;
413 if (b->buf[b->offset] == '\r') {
414 assert(b->offset + 1 < b->bytes);
415 if (b->buf[b->offset + 1] == '\n') {
416 b->buf[b->offset] = 0; /* terminate the string */
417 b->offset += 2; /* next line */
418 if (0 < verbosity)
419 puts(*s);
420 return 0;
424 b->offset++;
426 /* not reached */
429 __attribute__((format (printf, 1, 2)))
430 static void imap_info(const char *msg, ...)
432 va_list va;
434 if (0 <= verbosity) {
435 va_start(va, msg);
436 vprintf(msg, va);
437 va_end(va);
438 fflush(stdout);
442 __attribute__((format (printf, 1, 2)))
443 static void imap_warn(const char *msg, ...)
445 va_list va;
447 if (-2 < verbosity) {
448 va_start(va, msg);
449 vfprintf(stderr, msg, va);
450 va_end(va);
454 static char *next_arg(char **s)
456 char *ret;
458 if (!s || !*s)
459 return NULL;
460 while (isspace((unsigned char) **s))
461 (*s)++;
462 if (!**s) {
463 *s = NULL;
464 return NULL;
466 if (**s == '"') {
467 ++*s;
468 ret = *s;
469 *s = strchr(*s, '"');
470 } else {
471 ret = *s;
472 while (**s && !isspace((unsigned char) **s))
473 (*s)++;
475 if (*s) {
476 if (**s)
477 *(*s)++ = 0;
478 if (!**s)
479 *s = NULL;
481 return ret;
484 static struct imap_cmd *issue_imap_cmd(struct imap_store *ctx,
485 struct imap_cmd_cb *cb,
486 const char *fmt, va_list ap)
488 struct imap *imap = ctx->imap;
489 struct imap_cmd *cmd;
490 int n;
491 struct strbuf buf = STRBUF_INIT;
493 cmd = xmalloc(sizeof(struct imap_cmd));
494 cmd->cmd = xstrvfmt(fmt, ap);
495 cmd->tag = ++imap->nexttag;
497 if (cb)
498 cmd->cb = *cb;
499 else
500 memset(&cmd->cb, 0, sizeof(cmd->cb));
502 while (imap->literal_pending)
503 get_cmd_result(ctx, NULL);
505 if (!cmd->cb.data)
506 strbuf_addf(&buf, "%d %s\r\n", cmd->tag, cmd->cmd);
507 else
508 strbuf_addf(&buf, "%d %s{%d%s}\r\n", cmd->tag, cmd->cmd,
509 cmd->cb.dlen, CAP(LITERALPLUS) ? "+" : "");
510 if (buf.len > INT_MAX)
511 die("imap command overflow!");
513 if (0 < verbosity) {
514 if (imap->num_in_progress)
515 printf("(%d in progress) ", imap->num_in_progress);
516 if (!starts_with(cmd->cmd, "LOGIN"))
517 printf(">>> %s", buf.buf);
518 else
519 printf(">>> %d LOGIN <user> <pass>\n", cmd->tag);
521 if (socket_write(&imap->buf.sock, buf.buf, buf.len) != buf.len) {
522 free(cmd->cmd);
523 free(cmd);
524 if (cb)
525 free(cb->data);
526 strbuf_release(&buf);
527 return NULL;
529 strbuf_release(&buf);
530 if (cmd->cb.data) {
531 if (CAP(LITERALPLUS)) {
532 n = socket_write(&imap->buf.sock, cmd->cb.data, cmd->cb.dlen);
533 free(cmd->cb.data);
534 if (n != cmd->cb.dlen ||
535 socket_write(&imap->buf.sock, "\r\n", 2) != 2) {
536 free(cmd->cmd);
537 free(cmd);
538 return NULL;
540 cmd->cb.data = NULL;
541 } else
542 imap->literal_pending = 1;
543 } else if (cmd->cb.cont)
544 imap->literal_pending = 1;
545 cmd->next = NULL;
546 *imap->in_progress_append = cmd;
547 imap->in_progress_append = &cmd->next;
548 imap->num_in_progress++;
549 return cmd;
552 __attribute__((format (printf, 3, 4)))
553 static int imap_exec(struct imap_store *ctx, struct imap_cmd_cb *cb,
554 const char *fmt, ...)
556 va_list ap;
557 struct imap_cmd *cmdp;
559 va_start(ap, fmt);
560 cmdp = issue_imap_cmd(ctx, cb, fmt, ap);
561 va_end(ap);
562 if (!cmdp)
563 return RESP_BAD;
565 return get_cmd_result(ctx, cmdp);
568 __attribute__((format (printf, 3, 4)))
569 static int imap_exec_m(struct imap_store *ctx, struct imap_cmd_cb *cb,
570 const char *fmt, ...)
572 va_list ap;
573 struct imap_cmd *cmdp;
575 va_start(ap, fmt);
576 cmdp = issue_imap_cmd(ctx, cb, fmt, ap);
577 va_end(ap);
578 if (!cmdp)
579 return DRV_STORE_BAD;
581 switch (get_cmd_result(ctx, cmdp)) {
582 case RESP_BAD: return DRV_STORE_BAD;
583 case RESP_NO: return DRV_MSG_BAD;
584 default: return DRV_OK;
588 static int skip_imap_list_l(char **sp, int level)
590 char *s = *sp;
592 for (;;) {
593 while (isspace((unsigned char)*s))
594 s++;
595 if (level && *s == ')') {
596 s++;
597 break;
599 if (*s == '(') {
600 /* sublist */
601 s++;
602 if (skip_imap_list_l(&s, level + 1))
603 goto bail;
604 } else if (*s == '"') {
605 /* quoted string */
606 s++;
607 for (; *s != '"'; s++)
608 if (!*s)
609 goto bail;
610 s++;
611 } else {
612 /* atom */
613 for (; *s && !isspace((unsigned char)*s); s++)
614 if (level && *s == ')')
615 break;
618 if (!level)
619 break;
620 if (!*s)
621 goto bail;
623 *sp = s;
624 return 0;
626 bail:
627 return -1;
630 static void skip_list(char **sp)
632 skip_imap_list_l(sp, 0);
635 static void parse_capability(struct imap *imap, char *cmd)
637 char *arg;
638 unsigned i;
640 imap->caps = 0x80000000;
641 while ((arg = next_arg(&cmd)))
642 for (i = 0; i < ARRAY_SIZE(cap_list); i++)
643 if (!strcmp(cap_list[i], arg))
644 imap->caps |= 1 << i;
645 imap->rcaps = imap->caps;
648 static int parse_response_code(struct imap_store *ctx, struct imap_cmd_cb *cb,
649 char *s)
651 struct imap *imap = ctx->imap;
652 char *arg, *p;
654 if (!s || *s != '[')
655 return RESP_OK; /* no response code */
656 s++;
657 if (!(p = strchr(s, ']'))) {
658 fprintf(stderr, "IMAP error: malformed response code\n");
659 return RESP_BAD;
661 *p++ = 0;
662 arg = next_arg(&s);
663 if (!arg) {
664 fprintf(stderr, "IMAP error: empty response code\n");
665 return RESP_BAD;
667 if (!strcmp("UIDVALIDITY", arg)) {
668 if (!(arg = next_arg(&s)) || !(ctx->uidvalidity = atoi(arg))) {
669 fprintf(stderr, "IMAP error: malformed UIDVALIDITY status\n");
670 return RESP_BAD;
672 } else if (!strcmp("UIDNEXT", arg)) {
673 if (!(arg = next_arg(&s)) || !(imap->uidnext = atoi(arg))) {
674 fprintf(stderr, "IMAP error: malformed NEXTUID status\n");
675 return RESP_BAD;
677 } else if (!strcmp("CAPABILITY", arg)) {
678 parse_capability(imap, s);
679 } else if (!strcmp("ALERT", arg)) {
680 /* RFC2060 says that these messages MUST be displayed
681 * to the user
683 for (; isspace((unsigned char)*p); p++);
684 fprintf(stderr, "*** IMAP ALERT *** %s\n", p);
685 } else if (cb && cb->ctx && !strcmp("APPENDUID", arg)) {
686 if (!(arg = next_arg(&s)) || !(ctx->uidvalidity = atoi(arg)) ||
687 !(arg = next_arg(&s)) || !(*(int *)cb->ctx = atoi(arg))) {
688 fprintf(stderr, "IMAP error: malformed APPENDUID status\n");
689 return RESP_BAD;
692 return RESP_OK;
695 static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd)
697 struct imap *imap = ctx->imap;
698 struct imap_cmd *cmdp, **pcmdp;
699 char *cmd;
700 const char *arg, *arg1;
701 int n, resp, resp2, tag;
703 for (;;) {
704 if (buffer_gets(&imap->buf, &cmd))
705 return RESP_BAD;
707 arg = next_arg(&cmd);
708 if (!arg) {
709 fprintf(stderr, "IMAP error: empty response\n");
710 return RESP_BAD;
712 if (*arg == '*') {
713 arg = next_arg(&cmd);
714 if (!arg) {
715 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
716 return RESP_BAD;
719 if (!strcmp("NAMESPACE", arg)) {
720 /* rfc2342 NAMESPACE response. */
721 skip_list(&cmd); /* Personal mailboxes */
722 skip_list(&cmd); /* Others' mailboxes */
723 skip_list(&cmd); /* Shared mailboxes */
724 } else if (!strcmp("OK", arg) || !strcmp("BAD", arg) ||
725 !strcmp("NO", arg) || !strcmp("BYE", arg)) {
726 if ((resp = parse_response_code(ctx, NULL, cmd)) != RESP_OK)
727 return resp;
728 } else if (!strcmp("CAPABILITY", arg)) {
729 parse_capability(imap, cmd);
730 } else if ((arg1 = next_arg(&cmd))) {
731 ; /*
732 * Unhandled response-data with at least two words.
733 * Ignore it.
735 * NEEDSWORK: Previously this case handled '<num> EXISTS'
736 * and '<num> RECENT' but as a probably-unintended side
737 * effect it ignores other unrecognized two-word
738 * responses. imap-send doesn't ever try to read
739 * messages or mailboxes these days, so consider
740 * eliminating this case.
742 } else {
743 fprintf(stderr, "IMAP error: unable to parse untagged response\n");
744 return RESP_BAD;
746 } else if (!imap->in_progress) {
747 fprintf(stderr, "IMAP error: unexpected reply: %s %s\n", arg, cmd ? cmd : "");
748 return RESP_BAD;
749 } else if (*arg == '+') {
750 /* This can happen only with the last command underway, as
751 it enforces a round-trip. */
752 cmdp = (struct imap_cmd *)((char *)imap->in_progress_append -
753 offsetof(struct imap_cmd, next));
754 if (cmdp->cb.data) {
755 n = socket_write(&imap->buf.sock, cmdp->cb.data, cmdp->cb.dlen);
756 FREE_AND_NULL(cmdp->cb.data);
757 if (n != (int)cmdp->cb.dlen)
758 return RESP_BAD;
759 } else if (cmdp->cb.cont) {
760 if (cmdp->cb.cont(ctx, cmd))
761 return RESP_BAD;
762 } else {
763 fprintf(stderr, "IMAP error: unexpected command continuation request\n");
764 return RESP_BAD;
766 if (socket_write(&imap->buf.sock, "\r\n", 2) != 2)
767 return RESP_BAD;
768 if (!cmdp->cb.cont)
769 imap->literal_pending = 0;
770 if (!tcmd)
771 return DRV_OK;
772 } else {
773 tag = atoi(arg);
774 for (pcmdp = &imap->in_progress; (cmdp = *pcmdp); pcmdp = &cmdp->next)
775 if (cmdp->tag == tag)
776 goto gottag;
777 fprintf(stderr, "IMAP error: unexpected tag %s\n", arg);
778 return RESP_BAD;
779 gottag:
780 if (!(*pcmdp = cmdp->next))
781 imap->in_progress_append = pcmdp;
782 imap->num_in_progress--;
783 if (cmdp->cb.cont || cmdp->cb.data)
784 imap->literal_pending = 0;
785 arg = next_arg(&cmd);
786 if (!arg)
787 arg = "";
788 if (!strcmp("OK", arg))
789 resp = DRV_OK;
790 else {
791 if (!strcmp("NO", arg))
792 resp = RESP_NO;
793 else /*if (!strcmp("BAD", arg))*/
794 resp = RESP_BAD;
795 fprintf(stderr, "IMAP command '%s' returned response (%s) - %s\n",
796 !starts_with(cmdp->cmd, "LOGIN") ?
797 cmdp->cmd : "LOGIN <user> <pass>",
798 arg, cmd ? cmd : "");
800 if ((resp2 = parse_response_code(ctx, &cmdp->cb, cmd)) > resp)
801 resp = resp2;
802 free(cmdp->cb.data);
803 free(cmdp->cmd);
804 free(cmdp);
805 if (!tcmd || tcmd == cmdp)
806 return resp;
809 /* not reached */
812 static void imap_close_server(struct imap_store *ictx)
814 struct imap *imap = ictx->imap;
816 if (imap->buf.sock.fd[0] != -1) {
817 imap_exec(ictx, NULL, "LOGOUT");
818 socket_shutdown(&imap->buf.sock);
820 free(imap);
823 static void imap_close_store(struct imap_store *ctx)
825 imap_close_server(ctx);
826 free(ctx);
829 #ifndef NO_OPENSSL
832 * hexchar() and cram() functions are based on the code from the isync
833 * project (https://isync.sourceforge.io/).
835 static char hexchar(unsigned int b)
837 return b < 10 ? '0' + b : 'a' + (b - 10);
840 #define ENCODED_SIZE(n) (4 * DIV_ROUND_UP((n), 3))
841 static char *cram(const char *challenge_64, const char *user, const char *pass)
843 int i, resp_len, encoded_len, decoded_len;
844 unsigned char hash[16];
845 char hex[33];
846 char *response, *response_64, *challenge;
849 * length of challenge_64 (i.e. base-64 encoded string) is a good
850 * enough upper bound for challenge (decoded result).
852 encoded_len = strlen(challenge_64);
853 challenge = xmalloc(encoded_len);
854 decoded_len = EVP_DecodeBlock((unsigned char *)challenge,
855 (unsigned char *)challenge_64, encoded_len);
856 if (decoded_len < 0)
857 die("invalid challenge %s", challenge_64);
858 if (!HMAC(EVP_md5(), pass, strlen(pass), (unsigned char *)challenge, decoded_len, hash, NULL))
859 die("HMAC error");
861 hex[32] = 0;
862 for (i = 0; i < 16; i++) {
863 hex[2 * i] = hexchar((hash[i] >> 4) & 0xf);
864 hex[2 * i + 1] = hexchar(hash[i] & 0xf);
867 /* response: "<user> <digest in hex>" */
868 response = xstrfmt("%s %s", user, hex);
869 resp_len = strlen(response);
871 response_64 = xmallocz(ENCODED_SIZE(resp_len));
872 encoded_len = EVP_EncodeBlock((unsigned char *)response_64,
873 (unsigned char *)response, resp_len);
874 if (encoded_len < 0)
875 die("EVP_EncodeBlock error");
876 return (char *)response_64;
879 #else
881 static char *cram(const char *challenge_64 UNUSED,
882 const char *user UNUSED,
883 const char *pass UNUSED)
885 die("If you want to use CRAM-MD5 authenticate method, "
886 "you have to build git-imap-send with OpenSSL library.");
889 #endif
891 static int auth_cram_md5(struct imap_store *ctx, const char *prompt)
893 int ret;
894 char *response;
896 response = cram(prompt, ctx->cfg->user, ctx->cfg->pass);
898 ret = socket_write(&ctx->imap->buf.sock, response, strlen(response));
899 if (ret != strlen(response))
900 return error("IMAP error: sending response failed");
902 free(response);
904 return 0;
907 static void server_fill_credential(struct imap_server_conf *srvc, struct credential *cred)
909 if (srvc->user && srvc->pass)
910 return;
912 cred->protocol = xstrdup(srvc->use_ssl ? "imaps" : "imap");
913 cred->host = xstrdup(srvc->host);
915 cred->username = xstrdup_or_null(srvc->user);
916 cred->password = xstrdup_or_null(srvc->pass);
918 credential_fill(cred, 1);
920 if (!srvc->user)
921 srvc->user = xstrdup(cred->username);
922 if (!srvc->pass)
923 srvc->pass = xstrdup(cred->password);
926 static struct imap_store *imap_open_store(struct imap_server_conf *srvc, const char *folder)
928 struct credential cred = CREDENTIAL_INIT;
929 struct imap_store *ctx;
930 struct imap *imap;
931 char *arg, *rsp;
932 int s = -1, preauth;
934 CALLOC_ARRAY(ctx, 1);
936 ctx->cfg = srvc;
937 ctx->imap = CALLOC_ARRAY(imap, 1);
938 imap->buf.sock.fd[0] = imap->buf.sock.fd[1] = -1;
939 imap->in_progress_append = &imap->in_progress;
941 /* open connection to IMAP server */
943 if (srvc->tunnel) {
944 struct child_process tunnel = CHILD_PROCESS_INIT;
946 imap_info("Starting tunnel '%s'... ", srvc->tunnel);
948 strvec_push(&tunnel.args, srvc->tunnel);
949 tunnel.use_shell = 1;
950 tunnel.in = -1;
951 tunnel.out = -1;
952 if (start_command(&tunnel))
953 die("cannot start proxy %s", srvc->tunnel);
955 imap->buf.sock.fd[0] = tunnel.out;
956 imap->buf.sock.fd[1] = tunnel.in;
958 imap_info("ok\n");
959 } else {
960 #ifndef NO_IPV6
961 struct addrinfo hints, *ai0, *ai;
962 int gai;
963 char portstr[6];
965 xsnprintf(portstr, sizeof(portstr), "%d", srvc->port);
967 memset(&hints, 0, sizeof(hints));
968 hints.ai_socktype = SOCK_STREAM;
969 hints.ai_protocol = IPPROTO_TCP;
971 imap_info("Resolving %s... ", srvc->host);
972 gai = getaddrinfo(srvc->host, portstr, &hints, &ai);
973 if (gai) {
974 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai));
975 goto bail;
977 imap_info("ok\n");
979 for (ai0 = ai; ai; ai = ai->ai_next) {
980 char addr[NI_MAXHOST];
982 s = socket(ai->ai_family, ai->ai_socktype,
983 ai->ai_protocol);
984 if (s < 0)
985 continue;
987 getnameinfo(ai->ai_addr, ai->ai_addrlen, addr,
988 sizeof(addr), NULL, 0, NI_NUMERICHOST);
989 imap_info("Connecting to [%s]:%s... ", addr, portstr);
991 if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0) {
992 close(s);
993 s = -1;
994 perror("connect");
995 continue;
998 break;
1000 freeaddrinfo(ai0);
1001 #else /* NO_IPV6 */
1002 struct hostent *he;
1003 struct sockaddr_in addr;
1005 memset(&addr, 0, sizeof(addr));
1006 addr.sin_port = htons(srvc->port);
1007 addr.sin_family = AF_INET;
1009 imap_info("Resolving %s... ", srvc->host);
1010 he = gethostbyname(srvc->host);
1011 if (!he) {
1012 perror("gethostbyname");
1013 goto bail;
1015 imap_info("ok\n");
1017 addr.sin_addr.s_addr = *((int *) he->h_addr_list[0]);
1019 s = socket(PF_INET, SOCK_STREAM, 0);
1021 imap_info("Connecting to %s:%hu... ", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
1022 if (connect(s, (struct sockaddr *)&addr, sizeof(addr))) {
1023 close(s);
1024 s = -1;
1025 perror("connect");
1027 #endif
1028 if (s < 0) {
1029 fputs("Error: unable to connect to server.\n", stderr);
1030 goto bail;
1033 imap->buf.sock.fd[0] = s;
1034 imap->buf.sock.fd[1] = dup(s);
1036 if (srvc->use_ssl &&
1037 ssl_socket_connect(&imap->buf.sock, srvc, 0)) {
1038 close(s);
1039 goto bail;
1041 imap_info("ok\n");
1044 /* read the greeting string */
1045 if (buffer_gets(&imap->buf, &rsp)) {
1046 fprintf(stderr, "IMAP error: no greeting response\n");
1047 goto bail;
1049 arg = next_arg(&rsp);
1050 if (!arg || *arg != '*' || (arg = next_arg(&rsp)) == NULL) {
1051 fprintf(stderr, "IMAP error: invalid greeting response\n");
1052 goto bail;
1054 preauth = 0;
1055 if (!strcmp("PREAUTH", arg))
1056 preauth = 1;
1057 else if (strcmp("OK", arg) != 0) {
1058 fprintf(stderr, "IMAP error: unknown greeting response\n");
1059 goto bail;
1061 parse_response_code(ctx, NULL, rsp);
1062 if (!imap->caps && imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1063 goto bail;
1065 if (!preauth) {
1066 #ifndef NO_OPENSSL
1067 if (!srvc->use_ssl && CAP(STARTTLS)) {
1068 if (imap_exec(ctx, NULL, "STARTTLS") != RESP_OK)
1069 goto bail;
1070 if (ssl_socket_connect(&imap->buf.sock, srvc, 1))
1071 goto bail;
1072 /* capabilities may have changed, so get the new capabilities */
1073 if (imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1074 goto bail;
1076 #endif
1077 imap_info("Logging in...\n");
1078 server_fill_credential(srvc, &cred);
1080 if (srvc->auth_method) {
1081 struct imap_cmd_cb cb;
1083 if (!strcmp(srvc->auth_method, "CRAM-MD5")) {
1084 if (!CAP(AUTH_CRAM_MD5)) {
1085 fprintf(stderr, "You specified "
1086 "CRAM-MD5 as authentication method, "
1087 "but %s doesn't support it.\n", srvc->host);
1088 goto bail;
1090 /* CRAM-MD5 */
1092 memset(&cb, 0, sizeof(cb));
1093 cb.cont = auth_cram_md5;
1094 if (imap_exec(ctx, &cb, "AUTHENTICATE CRAM-MD5") != RESP_OK) {
1095 fprintf(stderr, "IMAP error: AUTHENTICATE CRAM-MD5 failed\n");
1096 goto bail;
1098 } else {
1099 fprintf(stderr, "Unknown authentication method:%s\n", srvc->host);
1100 goto bail;
1102 } else {
1103 if (CAP(NOLOGIN)) {
1104 fprintf(stderr, "Skipping account %s@%s, server forbids LOGIN\n",
1105 srvc->user, srvc->host);
1106 goto bail;
1108 if (!imap->buf.sock.ssl)
1109 imap_warn("*** IMAP Warning *** Password is being "
1110 "sent in the clear\n");
1111 if (imap_exec(ctx, NULL, "LOGIN \"%s\" \"%s\"", srvc->user, srvc->pass) != RESP_OK) {
1112 fprintf(stderr, "IMAP error: LOGIN failed\n");
1113 goto bail;
1116 } /* !preauth */
1118 if (cred.username)
1119 credential_approve(&cred);
1120 credential_clear(&cred);
1122 /* check the target mailbox exists */
1123 ctx->name = folder;
1124 switch (imap_exec(ctx, NULL, "EXAMINE \"%s\"", ctx->name)) {
1125 case RESP_OK:
1126 /* ok */
1127 break;
1128 case RESP_BAD:
1129 fprintf(stderr, "IMAP error: could not check mailbox\n");
1130 goto out;
1131 case RESP_NO:
1132 if (imap_exec(ctx, NULL, "CREATE \"%s\"", ctx->name) == RESP_OK) {
1133 imap_info("Created missing mailbox\n");
1134 } else {
1135 fprintf(stderr, "IMAP error: could not create missing mailbox\n");
1136 goto out;
1138 break;
1141 ctx->prefix = "";
1142 return ctx;
1144 bail:
1145 if (cred.username)
1146 credential_reject(&cred);
1147 credential_clear(&cred);
1149 out:
1150 imap_close_store(ctx);
1151 return NULL;
1155 * Insert CR characters as necessary in *msg to ensure that every LF
1156 * character in *msg is preceded by a CR.
1158 static void lf_to_crlf(struct strbuf *msg)
1160 char *new_msg;
1161 size_t i, j;
1162 char lastc;
1164 /* First pass: tally, in j, the size of the new_msg string: */
1165 for (i = j = 0, lastc = '\0'; i < msg->len; i++) {
1166 if (msg->buf[i] == '\n' && lastc != '\r')
1167 j++; /* a CR will need to be added here */
1168 lastc = msg->buf[i];
1169 j++;
1172 new_msg = xmallocz(j);
1175 * Second pass: write the new_msg string. Note that this loop is
1176 * otherwise identical to the first pass.
1178 for (i = j = 0, lastc = '\0'; i < msg->len; i++) {
1179 if (msg->buf[i] == '\n' && lastc != '\r')
1180 new_msg[j++] = '\r';
1181 lastc = new_msg[j++] = msg->buf[i];
1183 strbuf_attach(msg, new_msg, j, j + 1);
1187 * Store msg to IMAP. Also detach and free the data from msg->data,
1188 * leaving msg->data empty.
1190 static int imap_store_msg(struct imap_store *ctx, struct strbuf *msg)
1192 struct imap *imap = ctx->imap;
1193 struct imap_cmd_cb cb;
1194 const char *prefix, *box;
1195 int ret;
1197 lf_to_crlf(msg);
1198 memset(&cb, 0, sizeof(cb));
1200 cb.dlen = msg->len;
1201 cb.data = strbuf_detach(msg, NULL);
1203 box = ctx->name;
1204 prefix = !strcmp(box, "INBOX") ? "" : ctx->prefix;
1205 ret = imap_exec_m(ctx, &cb, "APPEND \"%s%s\" ", prefix, box);
1206 imap->caps = imap->rcaps;
1207 if (ret != DRV_OK)
1208 return ret;
1210 return DRV_OK;
1213 static void wrap_in_html(struct strbuf *msg)
1215 struct strbuf buf = STRBUF_INIT;
1216 static const char *content_type = "Content-Type: text/html;\n";
1217 static const char *pre_open = "<pre>\n";
1218 static const char *pre_close = "</pre>\n";
1219 const char *body = strstr(msg->buf, "\n\n");
1221 if (!body)
1222 return; /* Headers but no body; no wrapping needed */
1224 body += 2;
1226 strbuf_add(&buf, msg->buf, body - msg->buf - 1);
1227 strbuf_addstr(&buf, content_type);
1228 strbuf_addch(&buf, '\n');
1229 strbuf_addstr(&buf, pre_open);
1230 strbuf_addstr_xml_quoted(&buf, body);
1231 strbuf_addstr(&buf, pre_close);
1233 strbuf_release(msg);
1234 *msg = buf;
1237 static int count_messages(struct strbuf *all_msgs)
1239 int count = 0;
1240 char *p = all_msgs->buf;
1242 while (1) {
1243 if (starts_with(p, "From ")) {
1244 p = strstr(p+5, "\nFrom: ");
1245 if (!p) break;
1246 p = strstr(p+7, "\nDate: ");
1247 if (!p) break;
1248 p = strstr(p+7, "\nSubject: ");
1249 if (!p) break;
1250 p += 10;
1251 count++;
1253 p = strstr(p+5, "\nFrom ");
1254 if (!p)
1255 break;
1256 p++;
1258 return count;
1262 * Copy the next message from all_msgs, starting at offset *ofs, to
1263 * msg. Update *ofs to the start of the following message. Return
1264 * true iff a message was successfully copied.
1266 static int split_msg(struct strbuf *all_msgs, struct strbuf *msg, int *ofs)
1268 char *p, *data;
1269 size_t len;
1271 if (*ofs >= all_msgs->len)
1272 return 0;
1274 data = &all_msgs->buf[*ofs];
1275 len = all_msgs->len - *ofs;
1277 if (len < 5 || !starts_with(data, "From "))
1278 return 0;
1280 p = strchr(data, '\n');
1281 if (p) {
1282 p++;
1283 len -= p - data;
1284 *ofs += p - data;
1285 data = p;
1288 p = strstr(data, "\nFrom ");
1289 if (p)
1290 len = &p[1] - data;
1292 strbuf_add(msg, data, len);
1293 *ofs += len;
1294 return 1;
1297 static int git_imap_config(const char *var, const char *val,
1298 const struct config_context *ctx, void *cb)
1300 struct imap_server_conf *cfg = cb;
1302 if (!strcmp("imap.sslverify", var)) {
1303 cfg->ssl_verify = git_config_bool(var, val);
1304 } else if (!strcmp("imap.preformattedhtml", var)) {
1305 cfg->use_html = git_config_bool(var, val);
1306 } else if (!strcmp("imap.folder", var)) {
1307 FREE_AND_NULL(cfg->folder);
1308 return git_config_string(&cfg->folder, var, val);
1309 } else if (!strcmp("imap.user", var)) {
1310 FREE_AND_NULL(cfg->folder);
1311 return git_config_string(&cfg->user, var, val);
1312 } else if (!strcmp("imap.pass", var)) {
1313 FREE_AND_NULL(cfg->folder);
1314 return git_config_string(&cfg->pass, var, val);
1315 } else if (!strcmp("imap.tunnel", var)) {
1316 FREE_AND_NULL(cfg->folder);
1317 return git_config_string(&cfg->tunnel, var, val);
1318 } else if (!strcmp("imap.authmethod", var)) {
1319 FREE_AND_NULL(cfg->folder);
1320 return git_config_string(&cfg->auth_method, var, val);
1321 } else if (!strcmp("imap.port", var)) {
1322 cfg->port = git_config_int(var, val, ctx->kvi);
1323 } else if (!strcmp("imap.host", var)) {
1324 if (!val) {
1325 return config_error_nonbool(var);
1326 } else {
1327 if (starts_with(val, "imap:"))
1328 val += 5;
1329 else if (starts_with(val, "imaps:")) {
1330 val += 6;
1331 cfg->use_ssl = 1;
1333 if (starts_with(val, "//"))
1334 val += 2;
1335 cfg->host = xstrdup(val);
1337 } else {
1338 return git_default_config(var, val, ctx, cb);
1341 return 0;
1344 static int append_msgs_to_imap(struct imap_server_conf *server,
1345 struct strbuf* all_msgs, int total)
1347 struct strbuf msg = STRBUF_INIT;
1348 struct imap_store *ctx = NULL;
1349 int ofs = 0;
1350 int r;
1351 int n = 0;
1353 ctx = imap_open_store(server, server->folder);
1354 if (!ctx) {
1355 fprintf(stderr, "failed to open store\n");
1356 return 1;
1358 ctx->name = server->folder;
1360 fprintf(stderr, "sending %d message%s\n", total, (total != 1) ? "s" : "");
1361 while (1) {
1362 unsigned percent = n * 100 / total;
1364 fprintf(stderr, "%4u%% (%d/%d) done\r", percent, n, total);
1366 if (!split_msg(all_msgs, &msg, &ofs))
1367 break;
1368 if (server->use_html)
1369 wrap_in_html(&msg);
1370 r = imap_store_msg(ctx, &msg);
1371 if (r != DRV_OK)
1372 break;
1373 n++;
1375 fprintf(stderr, "\n");
1377 imap_close_store(ctx);
1379 return 0;
1382 #ifdef USE_CURL_FOR_IMAP_SEND
1383 static CURL *setup_curl(struct imap_server_conf *srvc, struct credential *cred)
1385 CURL *curl;
1386 struct strbuf path = STRBUF_INIT;
1387 char *uri_encoded_folder;
1389 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
1390 die("curl_global_init failed");
1392 curl = curl_easy_init();
1394 if (!curl)
1395 die("curl_easy_init failed");
1397 server_fill_credential(srvc, cred);
1398 curl_easy_setopt(curl, CURLOPT_USERNAME, srvc->user);
1399 curl_easy_setopt(curl, CURLOPT_PASSWORD, srvc->pass);
1401 strbuf_addstr(&path, srvc->use_ssl ? "imaps://" : "imap://");
1402 strbuf_addstr(&path, srvc->host);
1403 if (!path.len || path.buf[path.len - 1] != '/')
1404 strbuf_addch(&path, '/');
1406 uri_encoded_folder = curl_easy_escape(curl, srvc->folder, 0);
1407 if (!uri_encoded_folder)
1408 die("failed to encode server folder");
1409 strbuf_addstr(&path, uri_encoded_folder);
1410 curl_free(uri_encoded_folder);
1412 curl_easy_setopt(curl, CURLOPT_URL, path.buf);
1413 strbuf_release(&path);
1414 curl_easy_setopt(curl, CURLOPT_PORT, srvc->port);
1416 if (srvc->auth_method) {
1417 #ifndef GIT_CURL_HAVE_CURLOPT_LOGIN_OPTIONS
1418 warning("No LOGIN_OPTIONS support in this cURL version");
1419 #else
1420 struct strbuf auth = STRBUF_INIT;
1421 strbuf_addstr(&auth, "AUTH=");
1422 strbuf_addstr(&auth, srvc->auth_method);
1423 curl_easy_setopt(curl, CURLOPT_LOGIN_OPTIONS, auth.buf);
1424 strbuf_release(&auth);
1425 #endif
1428 if (!srvc->use_ssl)
1429 curl_easy_setopt(curl, CURLOPT_USE_SSL, (long)CURLUSESSL_TRY);
1431 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, srvc->ssl_verify);
1432 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, srvc->ssl_verify);
1434 curl_easy_setopt(curl, CURLOPT_READFUNCTION, fread_buffer);
1436 curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
1438 if (0 < verbosity || getenv("GIT_CURL_VERBOSE"))
1439 http_trace_curl_no_data();
1440 setup_curl_trace(curl);
1442 return curl;
1445 static int curl_append_msgs_to_imap(struct imap_server_conf *server,
1446 struct strbuf* all_msgs, int total)
1448 int ofs = 0;
1449 int n = 0;
1450 struct buffer msgbuf = { STRBUF_INIT, 0 };
1451 CURL *curl;
1452 CURLcode res = CURLE_OK;
1453 struct credential cred = CREDENTIAL_INIT;
1455 curl = setup_curl(server, &cred);
1456 curl_easy_setopt(curl, CURLOPT_READDATA, &msgbuf);
1458 fprintf(stderr, "sending %d message%s\n", total, (total != 1) ? "s" : "");
1459 while (1) {
1460 unsigned percent = n * 100 / total;
1461 int prev_len;
1463 fprintf(stderr, "%4u%% (%d/%d) done\r", percent, n, total);
1465 prev_len = msgbuf.buf.len;
1466 if (!split_msg(all_msgs, &msgbuf.buf, &ofs))
1467 break;
1468 if (server->use_html)
1469 wrap_in_html(&msgbuf.buf);
1470 lf_to_crlf(&msgbuf.buf);
1472 curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE,
1473 (curl_off_t)(msgbuf.buf.len-prev_len));
1475 res = curl_easy_perform(curl);
1477 if(res != CURLE_OK) {
1478 fprintf(stderr, "curl_easy_perform() failed: %s\n",
1479 curl_easy_strerror(res));
1480 break;
1483 n++;
1485 fprintf(stderr, "\n");
1487 curl_easy_cleanup(curl);
1488 curl_global_cleanup();
1490 if (cred.username) {
1491 if (res == CURLE_OK)
1492 credential_approve(&cred);
1493 else if (res == CURLE_LOGIN_DENIED)
1494 credential_reject(&cred);
1497 credential_clear(&cred);
1499 return res != CURLE_OK;
1501 #endif
1503 int cmd_main(int argc, const char **argv)
1505 struct imap_server_conf server = {
1506 .ssl_verify = 1,
1508 struct strbuf all_msgs = STRBUF_INIT;
1509 int total;
1510 int nongit_ok;
1511 int ret;
1513 setup_git_directory_gently(&nongit_ok);
1514 git_config(git_imap_config, &server);
1516 argc = parse_options(argc, (const char **)argv, "", imap_send_options, imap_send_usage, 0);
1518 if (argc)
1519 usage_with_options(imap_send_usage, imap_send_options);
1521 #ifndef USE_CURL_FOR_IMAP_SEND
1522 if (use_curl) {
1523 warning("--curl not supported in this build");
1524 use_curl = 0;
1526 #elif defined(NO_OPENSSL)
1527 if (!use_curl) {
1528 warning("--no-curl not supported in this build");
1529 use_curl = 1;
1531 #endif
1533 if (!server.port)
1534 server.port = server.use_ssl ? 993 : 143;
1536 if (!server.folder) {
1537 fprintf(stderr, "no imap store specified\n");
1538 ret = 1;
1539 goto out;
1541 if (!server.host) {
1542 if (!server.tunnel) {
1543 fprintf(stderr, "no imap host specified\n");
1544 ret = 1;
1545 goto out;
1547 server.host = xstrdup("tunnel");
1550 /* read the messages */
1551 if (strbuf_read(&all_msgs, 0, 0) < 0) {
1552 error_errno(_("could not read from stdin"));
1553 ret = 1;
1554 goto out;
1557 if (all_msgs.len == 0) {
1558 fprintf(stderr, "nothing to send\n");
1559 ret = 1;
1560 goto out;
1563 total = count_messages(&all_msgs);
1564 if (!total) {
1565 fprintf(stderr, "no messages to send\n");
1566 ret = 1;
1567 goto out;
1570 /* write it to the imap server */
1572 if (server.tunnel)
1573 ret = append_msgs_to_imap(&server, &all_msgs, total);
1574 #ifdef USE_CURL_FOR_IMAP_SEND
1575 else if (use_curl)
1576 ret = curl_append_msgs_to_imap(&server, &all_msgs, total);
1577 #endif
1578 else
1579 ret = append_msgs_to_imap(&server, &all_msgs, total);
1581 out:
1582 free(server.tunnel);
1583 free(server.host);
1584 free(server.folder);
1585 free(server.user);
1586 free(server.pass);
1587 free(server.auth_method);
1588 strbuf_release(&all_msgs);
1589 return ret;