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