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