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