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