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