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