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