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