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