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