imap-send.con commit Windows: use BLK_SHA1 again (9bccfcd)
   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        SSL_METHOD *meth;
 276        SSL_CTX *ctx;
 277        int ret;
 278
 279        SSL_library_init();
 280        SSL_load_error_strings();
 281
 282        if (use_tls_only)
 283                meth = TLSv1_method();
 284        else
 285                meth = SSLv23_method();
 286
 287        if (!meth) {
 288                ssl_socket_perror("SSLv23_method");
 289                return -1;
 290        }
 291
 292        ctx = SSL_CTX_new(meth);
 293
 294        if (verify)
 295                SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
 296
 297        if (!SSL_CTX_set_default_verify_paths(ctx)) {
 298                ssl_socket_perror("SSL_CTX_set_default_verify_paths");
 299                return -1;
 300        }
 301        sock->ssl = SSL_new(ctx);
 302        if (!sock->ssl) {
 303                ssl_socket_perror("SSL_new");
 304                return -1;
 305        }
 306        if (!SSL_set_rfd(sock->ssl, sock->fd[0])) {
 307                ssl_socket_perror("SSL_set_rfd");
 308                return -1;
 309        }
 310        if (!SSL_set_wfd(sock->ssl, sock->fd[1])) {
 311                ssl_socket_perror("SSL_set_wfd");
 312                return -1;
 313        }
 314
 315        ret = SSL_connect(sock->ssl);
 316        if (ret <= 0) {
 317                socket_perror("SSL_connect", sock, ret);
 318                return -1;
 319        }
 320
 321        return 0;
 322#endif
 323}
 324
 325static int socket_read(struct imap_socket *sock, char *buf, int len)
 326{
 327        ssize_t n;
 328#ifndef NO_OPENSSL
 329        if (sock->ssl)
 330                n = SSL_read(sock->ssl, buf, len);
 331        else
 332#endif
 333                n = xread(sock->fd[0], buf, len);
 334        if (n <= 0) {
 335                socket_perror("read", sock, n);
 336                close(sock->fd[0]);
 337                close(sock->fd[1]);
 338                sock->fd[0] = sock->fd[1] = -1;
 339        }
 340        return n;
 341}
 342
 343static int socket_write(struct imap_socket *sock, const char *buf, int len)
 344{
 345        int n;
 346#ifndef NO_OPENSSL
 347        if (sock->ssl)
 348                n = SSL_write(sock->ssl, buf, len);
 349        else
 350#endif
 351                n = write_in_full(sock->fd[1], buf, len);
 352        if (n != len) {
 353                socket_perror("write", sock, n);
 354                close(sock->fd[0]);
 355                close(sock->fd[1]);
 356                sock->fd[0] = sock->fd[1] = -1;
 357        }
 358        return n;
 359}
 360
 361static void socket_shutdown(struct imap_socket *sock)
 362{
 363#ifndef NO_OPENSSL
 364        if (sock->ssl) {
 365                SSL_shutdown(sock->ssl);
 366                SSL_free(sock->ssl);
 367        }
 368#endif
 369        close(sock->fd[0]);
 370        close(sock->fd[1]);
 371}
 372
 373/* simple line buffering */
 374static int buffer_gets(struct imap_buffer *b, char **s)
 375{
 376        int n;
 377        int start = b->offset;
 378
 379        *s = b->buf + start;
 380
 381        for (;;) {
 382                /* make sure we have enough data to read the \r\n sequence */
 383                if (b->offset + 1 >= b->bytes) {
 384                        if (start) {
 385                                /* shift down used bytes */
 386                                *s = b->buf;
 387
 388                                assert(start <= b->bytes);
 389                                n = b->bytes - start;
 390
 391                                if (n)
 392                                        memmove(b->buf, b->buf + start, n);
 393                                b->offset -= start;
 394                                b->bytes = n;
 395                                start = 0;
 396                        }
 397
 398                        n = socket_read(&b->sock, b->buf + b->bytes,
 399                                         sizeof(b->buf) - b->bytes);
 400
 401                        if (n <= 0)
 402                                return -1;
 403
 404                        b->bytes += n;
 405                }
 406
 407                if (b->buf[b->offset] == '\r') {
 408                        assert(b->offset + 1 < b->bytes);
 409                        if (b->buf[b->offset + 1] == '\n') {
 410                                b->buf[b->offset] = 0;  /* terminate the string */
 411                                b->offset += 2; /* next line */
 412                                if (Verbose)
 413                                        puts(*s);
 414                                return 0;
 415                        }
 416                }
 417
 418                b->offset++;
 419        }
 420        /* not reached */
 421}
 422
 423static void imap_info(const char *msg, ...)
 424{
 425        va_list va;
 426
 427        if (!Quiet) {
 428                va_start(va, msg);
 429                vprintf(msg, va);
 430                va_end(va);
 431                fflush(stdout);
 432        }
 433}
 434
 435static void imap_warn(const char *msg, ...)
 436{
 437        va_list va;
 438
 439        if (Quiet < 2) {
 440                va_start(va, msg);
 441                vfprintf(stderr, msg, va);
 442                va_end(va);
 443        }
 444}
 445
 446static char *next_arg(char **s)
 447{
 448        char *ret;
 449
 450        if (!s || !*s)
 451                return NULL;
 452        while (isspace((unsigned char) **s))
 453                (*s)++;
 454        if (!**s) {
 455                *s = NULL;
 456                return NULL;
 457        }
 458        if (**s == '"') {
 459                ++*s;
 460                ret = *s;
 461                *s = strchr(*s, '"');
 462        } else {
 463                ret = *s;
 464                while (**s && !isspace((unsigned char) **s))
 465                        (*s)++;
 466        }
 467        if (*s) {
 468                if (**s)
 469                        *(*s)++ = 0;
 470                if (!**s)
 471                        *s = NULL;
 472        }
 473        return ret;
 474}
 475
 476static void free_generic_messages(struct message *msgs)
 477{
 478        struct message *tmsg;
 479
 480        for (; msgs; msgs = tmsg) {
 481                tmsg = msgs->next;
 482                free(msgs);
 483        }
 484}
 485
 486static int nfsnprintf(char *buf, int blen, const char *fmt, ...)
 487{
 488        int ret;
 489        va_list va;
 490
 491        va_start(va, fmt);
 492        if (blen <= 0 || (unsigned)(ret = vsnprintf(buf, blen, fmt, va)) >= (unsigned)blen)
 493                die("Fatal: buffer too small. Please report a bug.");
 494        va_end(va);
 495        return ret;
 496}
 497
 498static struct imap_cmd *v_issue_imap_cmd(struct imap_store *ctx,
 499                                         struct imap_cmd_cb *cb,
 500                                         const char *fmt, va_list ap)
 501{
 502        struct imap *imap = ctx->imap;
 503        struct imap_cmd *cmd;
 504        int n, bufl;
 505        char buf[1024];
 506
 507        cmd = xmalloc(sizeof(struct imap_cmd));
 508        nfvasprintf(&cmd->cmd, fmt, ap);
 509        cmd->tag = ++imap->nexttag;
 510
 511        if (cb)
 512                cmd->cb = *cb;
 513        else
 514                memset(&cmd->cb, 0, sizeof(cmd->cb));
 515
 516        while (imap->literal_pending)
 517                get_cmd_result(ctx, NULL);
 518
 519        bufl = nfsnprintf(buf, sizeof(buf), cmd->cb.data ? CAP(LITERALPLUS) ?
 520                           "%d %s{%d+}\r\n" : "%d %s{%d}\r\n" : "%d %s\r\n",
 521                           cmd->tag, cmd->cmd, cmd->cb.dlen);
 522        if (Verbose) {
 523                if (imap->num_in_progress)
 524                        printf("(%d in progress) ", imap->num_in_progress);
 525                if (memcmp(cmd->cmd, "LOGIN", 5))
 526                        printf(">>> %s", buf);
 527                else
 528                        printf(">>> %d LOGIN <user> <pass>\n", cmd->tag);
 529        }
 530        if (socket_write(&imap->buf.sock, buf, bufl) != bufl) {
 531                free(cmd->cmd);
 532                free(cmd);
 533                if (cb)
 534                        free(cb->data);
 535                return NULL;
 536        }
 537        if (cmd->cb.data) {
 538                if (CAP(LITERALPLUS)) {
 539                        n = socket_write(&imap->buf.sock, cmd->cb.data, cmd->cb.dlen);
 540                        free(cmd->cb.data);
 541                        if (n != cmd->cb.dlen ||
 542                            socket_write(&imap->buf.sock, "\r\n", 2) != 2) {
 543                                free(cmd->cmd);
 544                                free(cmd);
 545                                return NULL;
 546                        }
 547                        cmd->cb.data = NULL;
 548                } else
 549                        imap->literal_pending = 1;
 550        } else if (cmd->cb.cont)
 551                imap->literal_pending = 1;
 552        cmd->next = NULL;
 553        *imap->in_progress_append = cmd;
 554        imap->in_progress_append = &cmd->next;
 555        imap->num_in_progress++;
 556        return cmd;
 557}
 558
 559static struct imap_cmd *issue_imap_cmd(struct imap_store *ctx,
 560                                       struct imap_cmd_cb *cb,
 561                                       const char *fmt, ...)
 562{
 563        struct imap_cmd *ret;
 564        va_list ap;
 565
 566        va_start(ap, fmt);
 567        ret = v_issue_imap_cmd(ctx, cb, fmt, ap);
 568        va_end(ap);
 569        return ret;
 570}
 571
 572static int imap_exec(struct imap_store *ctx, struct imap_cmd_cb *cb,
 573                     const char *fmt, ...)
 574{
 575        va_list ap;
 576        struct imap_cmd *cmdp;
 577
 578        va_start(ap, fmt);
 579        cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
 580        va_end(ap);
 581        if (!cmdp)
 582                return RESP_BAD;
 583
 584        return get_cmd_result(ctx, cmdp);
 585}
 586
 587static int imap_exec_m(struct imap_store *ctx, struct imap_cmd_cb *cb,
 588                       const char *fmt, ...)
 589{
 590        va_list ap;
 591        struct imap_cmd *cmdp;
 592
 593        va_start(ap, fmt);
 594        cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
 595        va_end(ap);
 596        if (!cmdp)
 597                return DRV_STORE_BAD;
 598
 599        switch (get_cmd_result(ctx, cmdp)) {
 600        case RESP_BAD: return DRV_STORE_BAD;
 601        case RESP_NO: return DRV_MSG_BAD;
 602        default: return DRV_OK;
 603        }
 604}
 605
 606static int is_atom(struct imap_list *list)
 607{
 608        return list && list->val && list->val != NIL && list->val != LIST;
 609}
 610
 611static int is_list(struct imap_list *list)
 612{
 613        return list && list->val == LIST;
 614}
 615
 616static void free_list(struct imap_list *list)
 617{
 618        struct imap_list *tmp;
 619
 620        for (; list; list = tmp) {
 621                tmp = list->next;
 622                if (is_list(list))
 623                        free_list(list->child);
 624                else if (is_atom(list))
 625                        free(list->val);
 626                free(list);
 627        }
 628}
 629
 630static int parse_imap_list_l(struct imap *imap, char **sp, struct imap_list **curp, int level)
 631{
 632        struct imap_list *cur;
 633        char *s = *sp, *p;
 634        int n, bytes;
 635
 636        for (;;) {
 637                while (isspace((unsigned char)*s))
 638                        s++;
 639                if (level && *s == ')') {
 640                        s++;
 641                        break;
 642                }
 643                *curp = cur = xmalloc(sizeof(*cur));
 644                curp = &cur->next;
 645                cur->val = NULL; /* for clean bail */
 646                if (*s == '(') {
 647                        /* sublist */
 648                        s++;
 649                        cur->val = LIST;
 650                        if (parse_imap_list_l(imap, &s, &cur->child, level + 1))
 651                                goto bail;
 652                } else if (imap && *s == '{') {
 653                        /* literal */
 654                        bytes = cur->len = strtol(s + 1, &s, 10);
 655                        if (*s != '}')
 656                                goto bail;
 657
 658                        s = cur->val = xmalloc(cur->len);
 659
 660                        /* dump whats left over in the input buffer */
 661                        n = imap->buf.bytes - imap->buf.offset;
 662
 663                        if (n > bytes)
 664                                /* the entire message fit in the buffer */
 665                                n = bytes;
 666
 667                        memcpy(s, imap->buf.buf + imap->buf.offset, n);
 668                        s += n;
 669                        bytes -= n;
 670
 671                        /* mark that we used part of the buffer */
 672                        imap->buf.offset += n;
 673
 674                        /* now read the rest of the message */
 675                        while (bytes > 0) {
 676                                if ((n = socket_read(&imap->buf.sock, s, bytes)) <= 0)
 677                                        goto bail;
 678                                s += n;
 679                                bytes -= n;
 680                        }
 681
 682                        if (buffer_gets(&imap->buf, &s))
 683                                goto bail;
 684                } else if (*s == '"') {
 685                        /* quoted string */
 686                        s++;
 687                        p = s;
 688                        for (; *s != '"'; s++)
 689                                if (!*s)
 690                                        goto bail;
 691                        cur->len = s - p;
 692                        s++;
 693                        cur->val = xmemdupz(p, cur->len);
 694                } else {
 695                        /* atom */
 696                        p = s;
 697                        for (; *s && !isspace((unsigned char)*s); s++)
 698                                if (level && *s == ')')
 699                                        break;
 700                        cur->len = s - p;
 701                        if (cur->len == 3 && !memcmp("NIL", p, 3))
 702                                cur->val = NIL;
 703                        else
 704                                cur->val = xmemdupz(p, cur->len);
 705                }
 706
 707                if (!level)
 708                        break;
 709                if (!*s)
 710                        goto bail;
 711        }
 712        *sp = s;
 713        *curp = NULL;
 714        return 0;
 715
 716bail:
 717        *curp = NULL;
 718        return -1;
 719}
 720
 721static struct imap_list *parse_imap_list(struct imap *imap, char **sp)
 722{
 723        struct imap_list *head;
 724
 725        if (!parse_imap_list_l(imap, sp, &head, 0))
 726                return head;
 727        free_list(head);
 728        return NULL;
 729}
 730
 731static struct imap_list *parse_list(char **sp)
 732{
 733        return parse_imap_list(NULL, sp);
 734}
 735
 736static void parse_capability(struct imap *imap, char *cmd)
 737{
 738        char *arg;
 739        unsigned i;
 740
 741        imap->caps = 0x80000000;
 742        while ((arg = next_arg(&cmd)))
 743                for (i = 0; i < ARRAY_SIZE(cap_list); i++)
 744                        if (!strcmp(cap_list[i], arg))
 745                                imap->caps |= 1 << i;
 746        imap->rcaps = imap->caps;
 747}
 748
 749static int parse_response_code(struct imap_store *ctx, struct imap_cmd_cb *cb,
 750                               char *s)
 751{
 752        struct imap *imap = ctx->imap;
 753        char *arg, *p;
 754
 755        if (*s != '[')
 756                return RESP_OK;         /* no response code */
 757        s++;
 758        if (!(p = strchr(s, ']'))) {
 759                fprintf(stderr, "IMAP error: malformed response code\n");
 760                return RESP_BAD;
 761        }
 762        *p++ = 0;
 763        arg = next_arg(&s);
 764        if (!strcmp("UIDVALIDITY", arg)) {
 765                if (!(arg = next_arg(&s)) || !(ctx->gen.uidvalidity = atoi(arg))) {
 766                        fprintf(stderr, "IMAP error: malformed UIDVALIDITY status\n");
 767                        return RESP_BAD;
 768                }
 769        } else if (!strcmp("UIDNEXT", arg)) {
 770                if (!(arg = next_arg(&s)) || !(imap->uidnext = atoi(arg))) {
 771                        fprintf(stderr, "IMAP error: malformed NEXTUID status\n");
 772                        return RESP_BAD;
 773                }
 774        } else if (!strcmp("CAPABILITY", arg)) {
 775                parse_capability(imap, s);
 776        } else if (!strcmp("ALERT", arg)) {
 777                /* RFC2060 says that these messages MUST be displayed
 778                 * to the user
 779                 */
 780                for (; isspace((unsigned char)*p); p++);
 781                fprintf(stderr, "*** IMAP ALERT *** %s\n", p);
 782        } else if (cb && cb->ctx && !strcmp("APPENDUID", arg)) {
 783                if (!(arg = next_arg(&s)) || !(ctx->gen.uidvalidity = atoi(arg)) ||
 784                    !(arg = next_arg(&s)) || !(*(int *)cb->ctx = atoi(arg))) {
 785                        fprintf(stderr, "IMAP error: malformed APPENDUID status\n");
 786                        return RESP_BAD;
 787                }
 788        }
 789        return RESP_OK;
 790}
 791
 792static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd)
 793{
 794        struct imap *imap = ctx->imap;
 795        struct imap_cmd *cmdp, **pcmdp, *ncmdp;
 796        char *cmd, *arg, *arg1, *p;
 797        int n, resp, resp2, tag;
 798
 799        for (;;) {
 800                if (buffer_gets(&imap->buf, &cmd))
 801                        return RESP_BAD;
 802
 803                arg = next_arg(&cmd);
 804                if (*arg == '*') {
 805                        arg = next_arg(&cmd);
 806                        if (!arg) {
 807                                fprintf(stderr, "IMAP error: unable to parse untagged response\n");
 808                                return RESP_BAD;
 809                        }
 810
 811                        if (!strcmp("NAMESPACE", arg)) {
 812                                imap->ns_personal = parse_list(&cmd);
 813                                imap->ns_other = parse_list(&cmd);
 814                                imap->ns_shared = parse_list(&cmd);
 815                        } else if (!strcmp("OK", arg) || !strcmp("BAD", arg) ||
 816                                   !strcmp("NO", arg) || !strcmp("BYE", arg)) {
 817                                if ((resp = parse_response_code(ctx, NULL, cmd)) != RESP_OK)
 818                                        return resp;
 819                        } else if (!strcmp("CAPABILITY", arg))
 820                                parse_capability(imap, cmd);
 821                        else if ((arg1 = next_arg(&cmd))) {
 822                                if (!strcmp("EXISTS", arg1))
 823                                        ctx->gen.count = atoi(arg);
 824                                else if (!strcmp("RECENT", arg1))
 825                                        ctx->gen.recent = atoi(arg);
 826                        } else {
 827                                fprintf(stderr, "IMAP error: unable to parse untagged response\n");
 828                                return RESP_BAD;
 829                        }
 830                } else if (!imap->in_progress) {
 831                        fprintf(stderr, "IMAP error: unexpected reply: %s %s\n", arg, cmd ? cmd : "");
 832                        return RESP_BAD;
 833                } else if (*arg == '+') {
 834                        /* This can happen only with the last command underway, as
 835                           it enforces a round-trip. */
 836                        cmdp = (struct imap_cmd *)((char *)imap->in_progress_append -
 837                               offsetof(struct imap_cmd, next));
 838                        if (cmdp->cb.data) {
 839                                n = socket_write(&imap->buf.sock, cmdp->cb.data, cmdp->cb.dlen);
 840                                free(cmdp->cb.data);
 841                                cmdp->cb.data = NULL;
 842                                if (n != (int)cmdp->cb.dlen)
 843                                        return RESP_BAD;
 844                        } else if (cmdp->cb.cont) {
 845                                if (cmdp->cb.cont(ctx, cmdp, cmd))
 846                                        return RESP_BAD;
 847                        } else {
 848                                fprintf(stderr, "IMAP error: unexpected command continuation request\n");
 849                                return RESP_BAD;
 850                        }
 851                        if (socket_write(&imap->buf.sock, "\r\n", 2) != 2)
 852                                return RESP_BAD;
 853                        if (!cmdp->cb.cont)
 854                                imap->literal_pending = 0;
 855                        if (!tcmd)
 856                                return DRV_OK;
 857                } else {
 858                        tag = atoi(arg);
 859                        for (pcmdp = &imap->in_progress; (cmdp = *pcmdp); pcmdp = &cmdp->next)
 860                                if (cmdp->tag == tag)
 861                                        goto gottag;
 862                        fprintf(stderr, "IMAP error: unexpected tag %s\n", arg);
 863                        return RESP_BAD;
 864                gottag:
 865                        if (!(*pcmdp = cmdp->next))
 866                                imap->in_progress_append = pcmdp;
 867                        imap->num_in_progress--;
 868                        if (cmdp->cb.cont || cmdp->cb.data)
 869                                imap->literal_pending = 0;
 870                        arg = next_arg(&cmd);
 871                        if (!strcmp("OK", arg))
 872                                resp = DRV_OK;
 873                        else {
 874                                if (!strcmp("NO", arg)) {
 875                                        if (cmdp->cb.create && cmd && (cmdp->cb.trycreate || !memcmp(cmd, "[TRYCREATE]", 11))) { /* SELECT, APPEND or UID COPY */
 876                                                p = strchr(cmdp->cmd, '"');
 877                                                if (!issue_imap_cmd(ctx, NULL, "CREATE \"%.*s\"", strchr(p + 1, '"') - p + 1, p)) {
 878                                                        resp = RESP_BAD;
 879                                                        goto normal;
 880                                                }
 881                                                /* not waiting here violates the spec, but a server that does not
 882                                                   grok this nonetheless violates it too. */
 883                                                cmdp->cb.create = 0;
 884                                                if (!(ncmdp = issue_imap_cmd(ctx, &cmdp->cb, "%s", cmdp->cmd))) {
 885                                                        resp = RESP_BAD;
 886                                                        goto normal;
 887                                                }
 888                                                free(cmdp->cmd);
 889                                                free(cmdp);
 890                                                if (!tcmd)
 891                                                        return 0;       /* ignored */
 892                                                if (cmdp == tcmd)
 893                                                        tcmd = ncmdp;
 894                                                continue;
 895                                        }
 896                                        resp = RESP_NO;
 897                                } else /*if (!strcmp("BAD", arg))*/
 898                                        resp = RESP_BAD;
 899                                fprintf(stderr, "IMAP command '%s' returned response (%s) - %s\n",
 900                                         memcmp(cmdp->cmd, "LOGIN", 5) ?
 901                                                        cmdp->cmd : "LOGIN <user> <pass>",
 902                                                        arg, cmd ? cmd : "");
 903                        }
 904                        if ((resp2 = parse_response_code(ctx, &cmdp->cb, cmd)) > resp)
 905                                resp = resp2;
 906                normal:
 907                        if (cmdp->cb.done)
 908                                cmdp->cb.done(ctx, cmdp, resp);
 909                        free(cmdp->cb.data);
 910                        free(cmdp->cmd);
 911                        free(cmdp);
 912                        if (!tcmd || tcmd == cmdp)
 913                                return resp;
 914                }
 915        }
 916        /* not reached */
 917}
 918
 919static void imap_close_server(struct imap_store *ictx)
 920{
 921        struct imap *imap = ictx->imap;
 922
 923        if (imap->buf.sock.fd[0] != -1) {
 924                imap_exec(ictx, NULL, "LOGOUT");
 925                socket_shutdown(&imap->buf.sock);
 926        }
 927        free_list(imap->ns_personal);
 928        free_list(imap->ns_other);
 929        free_list(imap->ns_shared);
 930        free(imap);
 931}
 932
 933static void imap_close_store(struct store *ctx)
 934{
 935        imap_close_server((struct imap_store *)ctx);
 936        free_generic_messages(ctx->msgs);
 937        free(ctx);
 938}
 939
 940static struct store *imap_open_store(struct imap_server_conf *srvc)
 941{
 942        struct imap_store *ctx;
 943        struct imap *imap;
 944        char *arg, *rsp;
 945        int s = -1, preauth;
 946
 947        ctx = xcalloc(sizeof(*ctx), 1);
 948
 949        ctx->imap = imap = xcalloc(sizeof(*imap), 1);
 950        imap->buf.sock.fd[0] = imap->buf.sock.fd[1] = -1;
 951        imap->in_progress_append = &imap->in_progress;
 952
 953        /* open connection to IMAP server */
 954
 955        if (srvc->tunnel) {
 956                const char *argv[4];
 957                struct child_process tunnel = {0};
 958
 959                imap_info("Starting tunnel '%s'... ", srvc->tunnel);
 960
 961                argv[0] = "sh";
 962                argv[1] = "-c";
 963                argv[2] = srvc->tunnel;
 964                argv[3] = NULL;
 965
 966                tunnel.argv = argv;
 967                tunnel.in = -1;
 968                tunnel.out = -1;
 969                if (start_command(&tunnel))
 970                        die("cannot start proxy %s", argv[0]);
 971
 972                imap->buf.sock.fd[0] = tunnel.out;
 973                imap->buf.sock.fd[1] = tunnel.in;
 974
 975                imap_info("ok\n");
 976        } else {
 977#ifndef NO_IPV6
 978                struct addrinfo hints, *ai0, *ai;
 979                int gai;
 980                char portstr[6];
 981
 982                snprintf(portstr, sizeof(portstr), "%hu", srvc->port);
 983
 984                memset(&hints, 0, sizeof(hints));
 985                hints.ai_socktype = SOCK_STREAM;
 986                hints.ai_protocol = IPPROTO_TCP;
 987
 988                imap_info("Resolving %s... ", srvc->host);
 989                gai = getaddrinfo(srvc->host, portstr, &hints, &ai);
 990                if (gai) {
 991                        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai));
 992                        goto bail;
 993                }
 994                imap_info("ok\n");
 995
 996                for (ai0 = ai; ai; ai = ai->ai_next) {
 997                        char addr[NI_MAXHOST];
 998
 999                        s = socket(ai->ai_family, ai->ai_socktype,
1000                                   ai->ai_protocol);
1001                        if (s < 0)
1002                                continue;
1003
1004                        getnameinfo(ai->ai_addr, ai->ai_addrlen, addr,
1005                                    sizeof(addr), NULL, 0, NI_NUMERICHOST);
1006                        imap_info("Connecting to [%s]:%s... ", addr, portstr);
1007
1008                        if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0) {
1009                                close(s);
1010                                s = -1;
1011                                perror("connect");
1012                                continue;
1013                        }
1014
1015                        break;
1016                }
1017                freeaddrinfo(ai0);
1018#else /* NO_IPV6 */
1019                struct hostent *he;
1020                struct sockaddr_in addr;
1021
1022                memset(&addr, 0, sizeof(addr));
1023                addr.sin_port = htons(srvc->port);
1024                addr.sin_family = AF_INET;
1025
1026                imap_info("Resolving %s... ", srvc->host);
1027                he = gethostbyname(srvc->host);
1028                if (!he) {
1029                        perror("gethostbyname");
1030                        goto bail;
1031                }
1032                imap_info("ok\n");
1033
1034                addr.sin_addr.s_addr = *((int *) he->h_addr_list[0]);
1035
1036                s = socket(PF_INET, SOCK_STREAM, 0);
1037
1038                imap_info("Connecting to %s:%hu... ", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
1039                if (connect(s, (struct sockaddr *)&addr, sizeof(addr))) {
1040                        close(s);
1041                        s = -1;
1042                        perror("connect");
1043                }
1044#endif
1045                if (s < 0) {
1046                        fputs("Error: unable to connect to server.\n", stderr);
1047                        goto bail;
1048                }
1049
1050                imap->buf.sock.fd[0] = s;
1051                imap->buf.sock.fd[1] = dup(s);
1052
1053                if (srvc->use_ssl &&
1054                    ssl_socket_connect(&imap->buf.sock, 0, srvc->ssl_verify)) {
1055                        close(s);
1056                        goto bail;
1057                }
1058                imap_info("ok\n");
1059        }
1060
1061        /* read the greeting string */
1062        if (buffer_gets(&imap->buf, &rsp)) {
1063                fprintf(stderr, "IMAP error: no greeting response\n");
1064                goto bail;
1065        }
1066        arg = next_arg(&rsp);
1067        if (!arg || *arg != '*' || (arg = next_arg(&rsp)) == NULL) {
1068                fprintf(stderr, "IMAP error: invalid greeting response\n");
1069                goto bail;
1070        }
1071        preauth = 0;
1072        if (!strcmp("PREAUTH", arg))
1073                preauth = 1;
1074        else if (strcmp("OK", arg) != 0) {
1075                fprintf(stderr, "IMAP error: unknown greeting response\n");
1076                goto bail;
1077        }
1078        parse_response_code(ctx, NULL, rsp);
1079        if (!imap->caps && imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1080                goto bail;
1081
1082        if (!preauth) {
1083#ifndef NO_OPENSSL
1084                if (!srvc->use_ssl && CAP(STARTTLS)) {
1085                        if (imap_exec(ctx, 0, "STARTTLS") != RESP_OK)
1086                                goto bail;
1087                        if (ssl_socket_connect(&imap->buf.sock, 1,
1088                                               srvc->ssl_verify))
1089                                goto bail;
1090                        /* capabilities may have changed, so get the new capabilities */
1091                        if (imap_exec(ctx, 0, "CAPABILITY") != RESP_OK)
1092                                goto bail;
1093                }
1094#endif
1095                imap_info("Logging in...\n");
1096                if (!srvc->user) {
1097                        fprintf(stderr, "Skipping server %s, no user\n", srvc->host);
1098                        goto bail;
1099                }
1100                if (!srvc->pass) {
1101                        char prompt[80];
1102                        sprintf(prompt, "Password (%s@%s): ", srvc->user, srvc->host);
1103                        arg = getpass(prompt);
1104                        if (!arg) {
1105                                perror("getpass");
1106                                exit(1);
1107                        }
1108                        if (!*arg) {
1109                                fprintf(stderr, "Skipping account %s@%s, no password\n", srvc->user, srvc->host);
1110                                goto bail;
1111                        }
1112                        /*
1113                         * getpass() returns a pointer to a static buffer.  make a copy
1114                         * for long term storage.
1115                         */
1116                        srvc->pass = xstrdup(arg);
1117                }
1118                if (CAP(NOLOGIN)) {
1119                        fprintf(stderr, "Skipping account %s@%s, server forbids LOGIN\n", srvc->user, srvc->host);
1120                        goto bail;
1121                }
1122                if (!imap->buf.sock.ssl)
1123                        imap_warn("*** IMAP Warning *** Password is being "
1124                                  "sent in the clear\n");
1125                if (imap_exec(ctx, NULL, "LOGIN \"%s\" \"%s\"", srvc->user, srvc->pass) != RESP_OK) {
1126                        fprintf(stderr, "IMAP error: LOGIN failed\n");
1127                        goto bail;
1128                }
1129        } /* !preauth */
1130
1131        ctx->prefix = "";
1132        ctx->trashnc = 1;
1133        return (struct store *)ctx;
1134
1135bail:
1136        imap_close_store(&ctx->gen);
1137        return NULL;
1138}
1139
1140static int imap_make_flags(int flags, char *buf)
1141{
1142        const char *s;
1143        unsigned i, d;
1144
1145        for (i = d = 0; i < ARRAY_SIZE(Flags); i++)
1146                if (flags & (1 << i)) {
1147                        buf[d++] = ' ';
1148                        buf[d++] = '\\';
1149                        for (s = Flags[i]; *s; s++)
1150                                buf[d++] = *s;
1151                }
1152        buf[0] = '(';
1153        buf[d++] = ')';
1154        return d;
1155}
1156
1157static int imap_store_msg(struct store *gctx, struct msg_data *data)
1158{
1159        struct imap_store *ctx = (struct imap_store *)gctx;
1160        struct imap *imap = ctx->imap;
1161        struct imap_cmd_cb cb;
1162        const char *prefix, *box;
1163        int ret, d;
1164        char flagstr[128];
1165
1166        memset(&cb, 0, sizeof(cb));
1167
1168        cb.dlen = data->len;
1169        cb.data = xmalloc(cb.dlen);
1170        memcpy(cb.data, data->data, data->len);
1171
1172        d = 0;
1173        if (data->flags) {
1174                d = imap_make_flags(data->flags, flagstr);
1175                flagstr[d++] = ' ';
1176        }
1177        flagstr[d] = 0;
1178
1179        box = gctx->name;
1180        prefix = !strcmp(box, "INBOX") ? "" : ctx->prefix;
1181        cb.create = 0;
1182        ret = imap_exec_m(ctx, &cb, "APPEND \"%s%s\" %s", prefix, box, flagstr);
1183        imap->caps = imap->rcaps;
1184        if (ret != DRV_OK)
1185                return ret;
1186        gctx->count++;
1187
1188        return DRV_OK;
1189}
1190
1191static void encode_html_chars(struct strbuf *p)
1192{
1193        int i;
1194        for (i = 0; i < p->len; i++) {
1195                if (p->buf[i] == '&')
1196                        strbuf_splice(p, i, 1, "&amp;", 5);
1197                if (p->buf[i] == '<')
1198                        strbuf_splice(p, i, 1, "&lt;", 4);
1199                if (p->buf[i] == '>')
1200                        strbuf_splice(p, i, 1, "&gt;", 4);
1201                if (p->buf[i] == '"')
1202                        strbuf_splice(p, i, 1, "&quot;", 6);
1203        }
1204}
1205static void wrap_in_html(struct msg_data *msg)
1206{
1207        struct strbuf buf = STRBUF_INIT;
1208        struct strbuf **lines;
1209        struct strbuf **p;
1210        static char *content_type = "Content-Type: text/html;\n";
1211        static char *pre_open = "<pre>\n";
1212        static char *pre_close = "</pre>\n";
1213        int added_header = 0;
1214
1215        strbuf_attach(&buf, msg->data, msg->len, msg->len);
1216        lines = strbuf_split(&buf, '\n');
1217        strbuf_release(&buf);
1218        for (p = lines; *p; p++) {
1219                if (! added_header) {
1220                        if ((*p)->len == 1 && *((*p)->buf) == '\n') {
1221                                strbuf_addstr(&buf, content_type);
1222                                strbuf_addbuf(&buf, *p);
1223                                strbuf_addstr(&buf, pre_open);
1224                                added_header = 1;
1225                                continue;
1226                        }
1227                }
1228                else
1229                        encode_html_chars(*p);
1230                strbuf_addbuf(&buf, *p);
1231        }
1232        strbuf_addstr(&buf, pre_close);
1233        strbuf_list_free(lines);
1234        msg->len  = buf.len;
1235        msg->data = strbuf_detach(&buf, NULL);
1236}
1237
1238#define CHUNKSIZE 0x1000
1239
1240static int read_message(FILE *f, struct msg_data *msg)
1241{
1242        struct strbuf buf = STRBUF_INIT;
1243
1244        memset(msg, 0, sizeof(*msg));
1245
1246        do {
1247                if (strbuf_fread(&buf, CHUNKSIZE, f) <= 0)
1248                        break;
1249        } while (!feof(f));
1250
1251        msg->len  = buf.len;
1252        msg->data = strbuf_detach(&buf, NULL);
1253        return msg->len;
1254}
1255
1256static int count_messages(struct msg_data *msg)
1257{
1258        int count = 0;
1259        char *p = msg->data;
1260
1261        while (1) {
1262                if (!prefixcmp(p, "From ")) {
1263                        count++;
1264                        p += 5;
1265                }
1266                p = strstr(p+5, "\nFrom ");
1267                if (!p)
1268                        break;
1269                p++;
1270        }
1271        return count;
1272}
1273
1274static int split_msg(struct msg_data *all_msgs, struct msg_data *msg, int *ofs)
1275{
1276        char *p, *data;
1277
1278        memset(msg, 0, sizeof *msg);
1279        if (*ofs >= all_msgs->len)
1280                return 0;
1281
1282        data = &all_msgs->data[*ofs];
1283        msg->len = all_msgs->len - *ofs;
1284
1285        if (msg->len < 5 || prefixcmp(data, "From "))
1286                return 0;
1287
1288        p = strchr(data, '\n');
1289        if (p) {
1290                p = &p[1];
1291                msg->len -= p-data;
1292                *ofs += p-data;
1293                data = p;
1294        }
1295
1296        p = strstr(data, "\nFrom ");
1297        if (p)
1298                msg->len = &p[1] - data;
1299
1300        msg->data = xmemdupz(data, msg->len);
1301        *ofs += msg->len;
1302        return 1;
1303}
1304
1305static struct imap_server_conf server = {
1306        NULL,   /* name */
1307        NULL,   /* tunnel */
1308        NULL,   /* host */
1309        0,      /* port */
1310        NULL,   /* user */
1311        NULL,   /* pass */
1312        0,      /* use_ssl */
1313        1,      /* ssl_verify */
1314        0,      /* use_html */
1315};
1316
1317static char *imap_folder;
1318
1319static int git_imap_config(const char *key, const char *val, void *cb)
1320{
1321        char imap_key[] = "imap.";
1322
1323        if (strncmp(key, imap_key, sizeof imap_key - 1))
1324                return 0;
1325
1326        if (!val)
1327                return config_error_nonbool(key);
1328
1329        key += sizeof imap_key - 1;
1330
1331        if (!strcmp("folder", key)) {
1332                imap_folder = xstrdup(val);
1333        } else if (!strcmp("host", key)) {
1334                if (!prefixcmp(val, "imap:"))
1335                        val += 5;
1336                else if (!prefixcmp(val, "imaps:")) {
1337                        val += 6;
1338                        server.use_ssl = 1;
1339                }
1340                if (!prefixcmp(val, "//"))
1341                        val += 2;
1342                server.host = xstrdup(val);
1343        } else if (!strcmp("user", key))
1344                server.user = xstrdup(val);
1345        else if (!strcmp("pass", key))
1346                server.pass = xstrdup(val);
1347        else if (!strcmp("port", key))
1348                server.port = git_config_int(key, val);
1349        else if (!strcmp("tunnel", key))
1350                server.tunnel = xstrdup(val);
1351        else if (!strcmp("sslverify", key))
1352                server.ssl_verify = git_config_bool(key, val);
1353        else if (!strcmp("preformattedHTML", key))
1354                server.use_html = git_config_bool(key, val);
1355        return 0;
1356}
1357
1358int main(int argc, char **argv)
1359{
1360        struct msg_data all_msgs, msg;
1361        struct store *ctx = NULL;
1362        int ofs = 0;
1363        int r;
1364        int total, n = 0;
1365        int nongit_ok;
1366
1367        git_extract_argv0_path(argv[0]);
1368
1369        setup_git_directory_gently(&nongit_ok);
1370        git_config(git_imap_config, NULL);
1371
1372        if (!server.port)
1373                server.port = server.use_ssl ? 993 : 143;
1374
1375        if (!imap_folder) {
1376                fprintf(stderr, "no imap store specified\n");
1377                return 1;
1378        }
1379        if (!server.host) {
1380                if (!server.tunnel) {
1381                        fprintf(stderr, "no imap host specified\n");
1382                        return 1;
1383                }
1384                server.host = "tunnel";
1385        }
1386
1387        /* read the messages */
1388        if (!read_message(stdin, &all_msgs)) {
1389                fprintf(stderr, "nothing to send\n");
1390                return 1;
1391        }
1392
1393        total = count_messages(&all_msgs);
1394        if (!total) {
1395                fprintf(stderr, "no messages to send\n");
1396                return 1;
1397        }
1398
1399        /* write it to the imap server */
1400        ctx = imap_open_store(&server);
1401        if (!ctx) {
1402                fprintf(stderr, "failed to open store\n");
1403                return 1;
1404        }
1405
1406        fprintf(stderr, "sending %d message%s\n", total, (total != 1) ? "s" : "");
1407        ctx->name = imap_folder;
1408        while (1) {
1409                unsigned percent = n * 100 / total;
1410                fprintf(stderr, "%4u%% (%d/%d) done\r", percent, n, total);
1411                if (!split_msg(&all_msgs, &msg, &ofs))
1412                        break;
1413                if (server.use_html)
1414                        wrap_in_html(&msg);
1415                r = imap_store_msg(ctx, &msg);
1416                if (r != DRV_OK)
1417                        break;
1418                n++;
1419        }
1420        fprintf(stderr, "\n");
1421
1422        imap_close_store(ctx);
1423
1424        return 0;
1425}