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