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