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