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