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