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