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