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