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