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