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