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