imap-send.con commit git-pull doc: fix grammo ("conflicts" is plural) (38ef8a7)
   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        ret = SSL_connect(sock->ssl);
 374        if (ret <= 0) {
 375                socket_perror("SSL_connect", sock, ret);
 376                return -1;
 377        }
 378
 379        if (verify) {
 380                /* make sure the hostname matches that of the certificate */
 381                cert = SSL_get_peer_certificate(sock->ssl);
 382                if (!cert)
 383                        return error("unable to get peer certificate.");
 384                if (verify_hostname(cert, server.host) < 0)
 385                        return -1;
 386        }
 387
 388        return 0;
 389}
 390#endif
 391
 392static int socket_read(struct imap_socket *sock, char *buf, int len)
 393{
 394        ssize_t n;
 395#ifndef NO_OPENSSL
 396        if (sock->ssl)
 397                n = SSL_read(sock->ssl, buf, len);
 398        else
 399#endif
 400                n = xread(sock->fd[0], buf, len);
 401        if (n <= 0) {
 402                socket_perror("read", sock, n);
 403                close(sock->fd[0]);
 404                close(sock->fd[1]);
 405                sock->fd[0] = sock->fd[1] = -1;
 406        }
 407        return n;
 408}
 409
 410static int socket_write(struct imap_socket *sock, const char *buf, int len)
 411{
 412        int n;
 413#ifndef NO_OPENSSL
 414        if (sock->ssl)
 415                n = SSL_write(sock->ssl, buf, len);
 416        else
 417#endif
 418                n = write_in_full(sock->fd[1], buf, len);
 419        if (n != len) {
 420                socket_perror("write", sock, n);
 421                close(sock->fd[0]);
 422                close(sock->fd[1]);
 423                sock->fd[0] = sock->fd[1] = -1;
 424        }
 425        return n;
 426}
 427
 428static void socket_shutdown(struct imap_socket *sock)
 429{
 430#ifndef NO_OPENSSL
 431        if (sock->ssl) {
 432                SSL_shutdown(sock->ssl);
 433                SSL_free(sock->ssl);
 434        }
 435#endif
 436        close(sock->fd[0]);
 437        close(sock->fd[1]);
 438}
 439
 440/* simple line buffering */
 441static int buffer_gets(struct imap_buffer *b, char **s)
 442{
 443        int n;
 444        int start = b->offset;
 445
 446        *s = b->buf + start;
 447
 448        for (;;) {
 449                /* make sure we have enough data to read the \r\n sequence */
 450                if (b->offset + 1 >= b->bytes) {
 451                        if (start) {
 452                                /* shift down used bytes */
 453                                *s = b->buf;
 454
 455                                assert(start <= b->bytes);
 456                                n = b->bytes - start;
 457
 458                                if (n)
 459                                        memmove(b->buf, b->buf + start, n);
 460                                b->offset -= start;
 461                                b->bytes = n;
 462                                start = 0;
 463                        }
 464
 465                        n = socket_read(&b->sock, b->buf + b->bytes,
 466                                         sizeof(b->buf) - b->bytes);
 467
 468                        if (n <= 0)
 469                                return -1;
 470
 471                        b->bytes += n;
 472                }
 473
 474                if (b->buf[b->offset] == '\r') {
 475                        assert(b->offset + 1 < b->bytes);
 476                        if (b->buf[b->offset + 1] == '\n') {
 477                                b->buf[b->offset] = 0;  /* terminate the string */
 478                                b->offset += 2; /* next line */
 479                                if (Verbose)
 480                                        puts(*s);
 481                                return 0;
 482                        }
 483                }
 484
 485                b->offset++;
 486        }
 487        /* not reached */
 488}
 489
 490static void imap_info(const char *msg, ...)
 491{
 492        va_list va;
 493
 494        if (!Quiet) {
 495                va_start(va, msg);
 496                vprintf(msg, va);
 497                va_end(va);
 498                fflush(stdout);
 499        }
 500}
 501
 502static void imap_warn(const char *msg, ...)
 503{
 504        va_list va;
 505
 506        if (Quiet < 2) {
 507                va_start(va, msg);
 508                vfprintf(stderr, msg, va);
 509                va_end(va);
 510        }
 511}
 512
 513static char *next_arg(char **s)
 514{
 515        char *ret;
 516
 517        if (!s || !*s)
 518                return NULL;
 519        while (isspace((unsigned char) **s))
 520                (*s)++;
 521        if (!**s) {
 522                *s = NULL;
 523                return NULL;
 524        }
 525        if (**s == '"') {
 526                ++*s;
 527                ret = *s;
 528                *s = strchr(*s, '"');
 529        } else {
 530                ret = *s;
 531                while (**s && !isspace((unsigned char) **s))
 532                        (*s)++;
 533        }
 534        if (*s) {
 535                if (**s)
 536                        *(*s)++ = 0;
 537                if (!**s)
 538                        *s = NULL;
 539        }
 540        return ret;
 541}
 542
 543static void free_generic_messages(struct message *msgs)
 544{
 545        struct message *tmsg;
 546
 547        for (; msgs; msgs = tmsg) {
 548                tmsg = msgs->next;
 549                free(msgs);
 550        }
 551}
 552
 553static int nfsnprintf(char *buf, int blen, const char *fmt, ...)
 554{
 555        int ret;
 556        va_list va;
 557
 558        va_start(va, fmt);
 559        if (blen <= 0 || (unsigned)(ret = vsnprintf(buf, blen, fmt, va)) >= (unsigned)blen)
 560                die("Fatal: buffer too small. Please report a bug.");
 561        va_end(va);
 562        return ret;
 563}
 564
 565static struct imap_cmd *v_issue_imap_cmd(struct imap_store *ctx,
 566                                         struct imap_cmd_cb *cb,
 567                                         const char *fmt, va_list ap)
 568{
 569        struct imap *imap = ctx->imap;
 570        struct imap_cmd *cmd;
 571        int n, bufl;
 572        char buf[1024];
 573
 574        cmd = xmalloc(sizeof(struct imap_cmd));
 575        nfvasprintf(&cmd->cmd, fmt, ap);
 576        cmd->tag = ++imap->nexttag;
 577
 578        if (cb)
 579                cmd->cb = *cb;
 580        else
 581                memset(&cmd->cb, 0, sizeof(cmd->cb));
 582
 583        while (imap->literal_pending)
 584                get_cmd_result(ctx, NULL);
 585
 586        if (!cmd->cb.data)
 587                bufl = nfsnprintf(buf, sizeof(buf), "%d %s\r\n", cmd->tag, cmd->cmd);
 588        else
 589                bufl = nfsnprintf(buf, sizeof(buf), "%d %s{%d%s}\r\n",
 590                                  cmd->tag, cmd->cmd, cmd->cb.dlen,
 591                                  CAP(LITERALPLUS) ? "+" : "");
 592
 593        if (Verbose) {
 594                if (imap->num_in_progress)
 595                        printf("(%d in progress) ", imap->num_in_progress);
 596                if (memcmp(cmd->cmd, "LOGIN", 5))
 597                        printf(">>> %s", buf);
 598                else
 599                        printf(">>> %d LOGIN <user> <pass>\n", cmd->tag);
 600        }
 601        if (socket_write(&imap->buf.sock, buf, bufl) != bufl) {
 602                free(cmd->cmd);
 603                free(cmd);
 604                if (cb)
 605                        free(cb->data);
 606                return NULL;
 607        }
 608        if (cmd->cb.data) {
 609                if (CAP(LITERALPLUS)) {
 610                        n = socket_write(&imap->buf.sock, cmd->cb.data, cmd->cb.dlen);
 611                        free(cmd->cb.data);
 612                        if (n != cmd->cb.dlen ||
 613                            socket_write(&imap->buf.sock, "\r\n", 2) != 2) {
 614                                free(cmd->cmd);
 615                                free(cmd);
 616                                return NULL;
 617                        }
 618                        cmd->cb.data = NULL;
 619                } else
 620                        imap->literal_pending = 1;
 621        } else if (cmd->cb.cont)
 622                imap->literal_pending = 1;
 623        cmd->next = NULL;
 624        *imap->in_progress_append = cmd;
 625        imap->in_progress_append = &cmd->next;
 626        imap->num_in_progress++;
 627        return cmd;
 628}
 629
 630__attribute__((format (printf, 3, 4)))
 631static struct imap_cmd *issue_imap_cmd(struct imap_store *ctx,
 632                                       struct imap_cmd_cb *cb,
 633                                       const char *fmt, ...)
 634{
 635        struct imap_cmd *ret;
 636        va_list ap;
 637
 638        va_start(ap, fmt);
 639        ret = v_issue_imap_cmd(ctx, cb, fmt, ap);
 640        va_end(ap);
 641        return ret;
 642}
 643
 644__attribute__((format (printf, 3, 4)))
 645static int imap_exec(struct imap_store *ctx, struct imap_cmd_cb *cb,
 646                     const char *fmt, ...)
 647{
 648        va_list ap;
 649        struct imap_cmd *cmdp;
 650
 651        va_start(ap, fmt);
 652        cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
 653        va_end(ap);
 654        if (!cmdp)
 655                return RESP_BAD;
 656
 657        return get_cmd_result(ctx, cmdp);
 658}
 659
 660__attribute__((format (printf, 3, 4)))
 661static int imap_exec_m(struct imap_store *ctx, struct imap_cmd_cb *cb,
 662                       const char *fmt, ...)
 663{
 664        va_list ap;
 665        struct imap_cmd *cmdp;
 666
 667        va_start(ap, fmt);
 668        cmdp = v_issue_imap_cmd(ctx, cb, fmt, ap);
 669        va_end(ap);
 670        if (!cmdp)
 671                return DRV_STORE_BAD;
 672
 673        switch (get_cmd_result(ctx, cmdp)) {
 674        case RESP_BAD: return DRV_STORE_BAD;
 675        case RESP_NO: return DRV_MSG_BAD;
 676        default: return DRV_OK;
 677        }
 678}
 679
 680static int is_atom(struct imap_list *list)
 681{
 682        return list && list->val && list->val != NIL && list->val != LIST;
 683}
 684
 685static int is_list(struct imap_list *list)
 686{
 687        return list && list->val == LIST;
 688}
 689
 690static void free_list(struct imap_list *list)
 691{
 692        struct imap_list *tmp;
 693
 694        for (; list; list = tmp) {
 695                tmp = list->next;
 696                if (is_list(list))
 697                        free_list(list->child);
 698                else if (is_atom(list))
 699                        free(list->val);
 700                free(list);
 701        }
 702}
 703
 704static int parse_imap_list_l(struct imap *imap, char **sp, struct imap_list **curp, int level)
 705{
 706        struct imap_list *cur;
 707        char *s = *sp, *p;
 708        int n, bytes;
 709
 710        for (;;) {
 711                while (isspace((unsigned char)*s))
 712                        s++;
 713                if (level && *s == ')') {
 714                        s++;
 715                        break;
 716                }
 717                *curp = cur = xmalloc(sizeof(*cur));
 718                curp = &cur->next;
 719                cur->val = NULL; /* for clean bail */
 720                if (*s == '(') {
 721                        /* sublist */
 722                        s++;
 723                        cur->val = LIST;
 724                        if (parse_imap_list_l(imap, &s, &cur->child, level + 1))
 725                                goto bail;
 726                } else if (imap && *s == '{') {
 727                        /* literal */
 728                        bytes = cur->len = strtol(s + 1, &s, 10);
 729                        if (*s != '}')
 730                                goto bail;
 731
 732                        s = cur->val = xmalloc(cur->len);
 733
 734                        /* dump whats left over in the input buffer */
 735                        n = imap->buf.bytes - imap->buf.offset;
 736
 737                        if (n > bytes)
 738                                /* the entire message fit in the buffer */
 739                                n = bytes;
 740
 741                        memcpy(s, imap->buf.buf + imap->buf.offset, n);
 742                        s += n;
 743                        bytes -= n;
 744
 745                        /* mark that we used part of the buffer */
 746                        imap->buf.offset += n;
 747
 748                        /* now read the rest of the message */
 749                        while (bytes > 0) {
 750                                if ((n = socket_read(&imap->buf.sock, s, bytes)) <= 0)
 751                                        goto bail;
 752                                s += n;
 753                                bytes -= n;
 754                        }
 755
 756                        if (buffer_gets(&imap->buf, &s))
 757                                goto bail;
 758                } else if (*s == '"') {
 759                        /* quoted string */
 760                        s++;
 761                        p = s;
 762                        for (; *s != '"'; s++)
 763                                if (!*s)
 764                                        goto bail;
 765                        cur->len = s - p;
 766                        s++;
 767                        cur->val = xmemdupz(p, cur->len);
 768                } else {
 769                        /* atom */
 770                        p = s;
 771                        for (; *s && !isspace((unsigned char)*s); s++)
 772                                if (level && *s == ')')
 773                                        break;
 774                        cur->len = s - p;
 775                        if (cur->len == 3 && !memcmp("NIL", p, 3))
 776                                cur->val = NIL;
 777                        else
 778                                cur->val = xmemdupz(p, cur->len);
 779                }
 780
 781                if (!level)
 782                        break;
 783                if (!*s)
 784                        goto bail;
 785        }
 786        *sp = s;
 787        *curp = NULL;
 788        return 0;
 789
 790bail:
 791        *curp = NULL;
 792        return -1;
 793}
 794
 795static struct imap_list *parse_imap_list(struct imap *imap, char **sp)
 796{
 797        struct imap_list *head;
 798
 799        if (!parse_imap_list_l(imap, sp, &head, 0))
 800                return head;
 801        free_list(head);
 802        return NULL;
 803}
 804
 805static struct imap_list *parse_list(char **sp)
 806{
 807        return parse_imap_list(NULL, sp);
 808}
 809
 810static void parse_capability(struct imap *imap, char *cmd)
 811{
 812        char *arg;
 813        unsigned i;
 814
 815        imap->caps = 0x80000000;
 816        while ((arg = next_arg(&cmd)))
 817                for (i = 0; i < ARRAY_SIZE(cap_list); i++)
 818                        if (!strcmp(cap_list[i], arg))
 819                                imap->caps |= 1 << i;
 820        imap->rcaps = imap->caps;
 821}
 822
 823static int parse_response_code(struct imap_store *ctx, struct imap_cmd_cb *cb,
 824                               char *s)
 825{
 826        struct imap *imap = ctx->imap;
 827        char *arg, *p;
 828
 829        if (*s != '[')
 830                return RESP_OK;         /* no response code */
 831        s++;
 832        if (!(p = strchr(s, ']'))) {
 833                fprintf(stderr, "IMAP error: malformed response code\n");
 834                return RESP_BAD;
 835        }
 836        *p++ = 0;
 837        arg = next_arg(&s);
 838        if (!strcmp("UIDVALIDITY", arg)) {
 839                if (!(arg = next_arg(&s)) || !(ctx->gen.uidvalidity = atoi(arg))) {
 840                        fprintf(stderr, "IMAP error: malformed UIDVALIDITY status\n");
 841                        return RESP_BAD;
 842                }
 843        } else if (!strcmp("UIDNEXT", arg)) {
 844                if (!(arg = next_arg(&s)) || !(imap->uidnext = atoi(arg))) {
 845                        fprintf(stderr, "IMAP error: malformed NEXTUID status\n");
 846                        return RESP_BAD;
 847                }
 848        } else if (!strcmp("CAPABILITY", arg)) {
 849                parse_capability(imap, s);
 850        } else if (!strcmp("ALERT", arg)) {
 851                /* RFC2060 says that these messages MUST be displayed
 852                 * to the user
 853                 */
 854                for (; isspace((unsigned char)*p); p++);
 855                fprintf(stderr, "*** IMAP ALERT *** %s\n", p);
 856        } else if (cb && cb->ctx && !strcmp("APPENDUID", arg)) {
 857                if (!(arg = next_arg(&s)) || !(ctx->gen.uidvalidity = atoi(arg)) ||
 858                    !(arg = next_arg(&s)) || !(*(int *)cb->ctx = atoi(arg))) {
 859                        fprintf(stderr, "IMAP error: malformed APPENDUID status\n");
 860                        return RESP_BAD;
 861                }
 862        }
 863        return RESP_OK;
 864}
 865
 866static int get_cmd_result(struct imap_store *ctx, struct imap_cmd *tcmd)
 867{
 868        struct imap *imap = ctx->imap;
 869        struct imap_cmd *cmdp, **pcmdp, *ncmdp;
 870        char *cmd, *arg, *arg1, *p;
 871        int n, resp, resp2, tag;
 872
 873        for (;;) {
 874                if (buffer_gets(&imap->buf, &cmd))
 875                        return RESP_BAD;
 876
 877                arg = next_arg(&cmd);
 878                if (*arg == '*') {
 879                        arg = next_arg(&cmd);
 880                        if (!arg) {
 881                                fprintf(stderr, "IMAP error: unable to parse untagged response\n");
 882                                return RESP_BAD;
 883                        }
 884
 885                        if (!strcmp("NAMESPACE", arg)) {
 886                                imap->ns_personal = parse_list(&cmd);
 887                                imap->ns_other = parse_list(&cmd);
 888                                imap->ns_shared = parse_list(&cmd);
 889                        } else if (!strcmp("OK", arg) || !strcmp("BAD", arg) ||
 890                                   !strcmp("NO", arg) || !strcmp("BYE", arg)) {
 891                                if ((resp = parse_response_code(ctx, NULL, cmd)) != RESP_OK)
 892                                        return resp;
 893                        } else if (!strcmp("CAPABILITY", arg))
 894                                parse_capability(imap, cmd);
 895                        else if ((arg1 = next_arg(&cmd))) {
 896                                if (!strcmp("EXISTS", arg1))
 897                                        ctx->gen.count = atoi(arg);
 898                                else if (!strcmp("RECENT", arg1))
 899                                        ctx->gen.recent = atoi(arg);
 900                        } else {
 901                                fprintf(stderr, "IMAP error: unable to parse untagged response\n");
 902                                return RESP_BAD;
 903                        }
 904                } else if (!imap->in_progress) {
 905                        fprintf(stderr, "IMAP error: unexpected reply: %s %s\n", arg, cmd ? cmd : "");
 906                        return RESP_BAD;
 907                } else if (*arg == '+') {
 908                        /* This can happen only with the last command underway, as
 909                           it enforces a round-trip. */
 910                        cmdp = (struct imap_cmd *)((char *)imap->in_progress_append -
 911                               offsetof(struct imap_cmd, next));
 912                        if (cmdp->cb.data) {
 913                                n = socket_write(&imap->buf.sock, cmdp->cb.data, cmdp->cb.dlen);
 914                                free(cmdp->cb.data);
 915                                cmdp->cb.data = NULL;
 916                                if (n != (int)cmdp->cb.dlen)
 917                                        return RESP_BAD;
 918                        } else if (cmdp->cb.cont) {
 919                                if (cmdp->cb.cont(ctx, cmdp, cmd))
 920                                        return RESP_BAD;
 921                        } else {
 922                                fprintf(stderr, "IMAP error: unexpected command continuation request\n");
 923                                return RESP_BAD;
 924                        }
 925                        if (socket_write(&imap->buf.sock, "\r\n", 2) != 2)
 926                                return RESP_BAD;
 927                        if (!cmdp->cb.cont)
 928                                imap->literal_pending = 0;
 929                        if (!tcmd)
 930                                return DRV_OK;
 931                } else {
 932                        tag = atoi(arg);
 933                        for (pcmdp = &imap->in_progress; (cmdp = *pcmdp); pcmdp = &cmdp->next)
 934                                if (cmdp->tag == tag)
 935                                        goto gottag;
 936                        fprintf(stderr, "IMAP error: unexpected tag %s\n", arg);
 937                        return RESP_BAD;
 938                gottag:
 939                        if (!(*pcmdp = cmdp->next))
 940                                imap->in_progress_append = pcmdp;
 941                        imap->num_in_progress--;
 942                        if (cmdp->cb.cont || cmdp->cb.data)
 943                                imap->literal_pending = 0;
 944                        arg = next_arg(&cmd);
 945                        if (!strcmp("OK", arg))
 946                                resp = DRV_OK;
 947                        else {
 948                                if (!strcmp("NO", arg)) {
 949                                        if (cmdp->cb.create && cmd && (cmdp->cb.trycreate || !memcmp(cmd, "[TRYCREATE]", 11))) { /* SELECT, APPEND or UID COPY */
 950                                                p = strchr(cmdp->cmd, '"');
 951                                                if (!issue_imap_cmd(ctx, NULL, "CREATE \"%.*s\"", (int)(strchr(p + 1, '"') - p + 1), p)) {
 952                                                        resp = RESP_BAD;
 953                                                        goto normal;
 954                                                }
 955                                                /* not waiting here violates the spec, but a server that does not
 956                                                   grok this nonetheless violates it too. */
 957                                                cmdp->cb.create = 0;
 958                                                if (!(ncmdp = issue_imap_cmd(ctx, &cmdp->cb, "%s", cmdp->cmd))) {
 959                                                        resp = RESP_BAD;
 960                                                        goto normal;
 961                                                }
 962                                                free(cmdp->cmd);
 963                                                free(cmdp);
 964                                                if (!tcmd)
 965                                                        return 0;       /* ignored */
 966                                                if (cmdp == tcmd)
 967                                                        tcmd = ncmdp;
 968                                                continue;
 969                                        }
 970                                        resp = RESP_NO;
 971                                } else /*if (!strcmp("BAD", arg))*/
 972                                        resp = RESP_BAD;
 973                                fprintf(stderr, "IMAP command '%s' returned response (%s) - %s\n",
 974                                         memcmp(cmdp->cmd, "LOGIN", 5) ?
 975                                                        cmdp->cmd : "LOGIN <user> <pass>",
 976                                                        arg, cmd ? cmd : "");
 977                        }
 978                        if ((resp2 = parse_response_code(ctx, &cmdp->cb, cmd)) > resp)
 979                                resp = resp2;
 980                normal:
 981                        if (cmdp->cb.done)
 982                                cmdp->cb.done(ctx, cmdp, resp);
 983                        free(cmdp->cb.data);
 984                        free(cmdp->cmd);
 985                        free(cmdp);
 986                        if (!tcmd || tcmd == cmdp)
 987                                return resp;
 988                }
 989        }
 990        /* not reached */
 991}
 992
 993static void imap_close_server(struct imap_store *ictx)
 994{
 995        struct imap *imap = ictx->imap;
 996
 997        if (imap->buf.sock.fd[0] != -1) {
 998                imap_exec(ictx, NULL, "LOGOUT");
 999                socket_shutdown(&imap->buf.sock);
1000        }
1001        free_list(imap->ns_personal);
1002        free_list(imap->ns_other);
1003        free_list(imap->ns_shared);
1004        free(imap);
1005}
1006
1007static void imap_close_store(struct store *ctx)
1008{
1009        imap_close_server((struct imap_store *)ctx);
1010        free_generic_messages(ctx->msgs);
1011        free(ctx);
1012}
1013
1014#ifndef NO_OPENSSL
1015
1016/*
1017 * hexchar() and cram() functions are based on the code from the isync
1018 * project (http://isync.sf.net/).
1019 */
1020static char hexchar(unsigned int b)
1021{
1022        return b < 10 ? '0' + b : 'a' + (b - 10);
1023}
1024
1025#define ENCODED_SIZE(n) (4*((n+2)/3))
1026static char *cram(const char *challenge_64, const char *user, const char *pass)
1027{
1028        int i, resp_len, encoded_len, decoded_len;
1029        HMAC_CTX hmac;
1030        unsigned char hash[16];
1031        char hex[33];
1032        char *response, *response_64, *challenge;
1033
1034        /*
1035         * length of challenge_64 (i.e. base-64 encoded string) is a good
1036         * enough upper bound for challenge (decoded result).
1037         */
1038        encoded_len = strlen(challenge_64);
1039        challenge = xmalloc(encoded_len);
1040        decoded_len = EVP_DecodeBlock((unsigned char *)challenge,
1041                                      (unsigned char *)challenge_64, encoded_len);
1042        if (decoded_len < 0)
1043                die("invalid challenge %s", challenge_64);
1044        HMAC_Init(&hmac, (unsigned char *)pass, strlen(pass), EVP_md5());
1045        HMAC_Update(&hmac, (unsigned char *)challenge, decoded_len);
1046        HMAC_Final(&hmac, hash, NULL);
1047        HMAC_CTX_cleanup(&hmac);
1048
1049        hex[32] = 0;
1050        for (i = 0; i < 16; i++) {
1051                hex[2 * i] = hexchar((hash[i] >> 4) & 0xf);
1052                hex[2 * i + 1] = hexchar(hash[i] & 0xf);
1053        }
1054
1055        /* response: "<user> <digest in hex>" */
1056        resp_len = strlen(user) + 1 + strlen(hex) + 1;
1057        response = xmalloc(resp_len);
1058        sprintf(response, "%s %s", user, hex);
1059
1060        response_64 = xmalloc(ENCODED_SIZE(resp_len) + 1);
1061        encoded_len = EVP_EncodeBlock((unsigned char *)response_64,
1062                                      (unsigned char *)response, resp_len);
1063        if (encoded_len < 0)
1064                die("EVP_EncodeBlock error");
1065        response_64[encoded_len] = '\0';
1066        return (char *)response_64;
1067}
1068
1069#else
1070
1071static char *cram(const char *challenge_64, const char *user, const char *pass)
1072{
1073        die("If you want to use CRAM-MD5 authenticate method, "
1074            "you have to build git-imap-send with OpenSSL library.");
1075}
1076
1077#endif
1078
1079static int auth_cram_md5(struct imap_store *ctx, struct imap_cmd *cmd, const char *prompt)
1080{
1081        int ret;
1082        char *response;
1083
1084        response = cram(prompt, server.user, server.pass);
1085
1086        ret = socket_write(&ctx->imap->buf.sock, response, strlen(response));
1087        if (ret != strlen(response))
1088                return error("IMAP error: sending response failed");
1089
1090        free(response);
1091
1092        return 0;
1093}
1094
1095static struct store *imap_open_store(struct imap_server_conf *srvc)
1096{
1097        struct imap_store *ctx;
1098        struct imap *imap;
1099        char *arg, *rsp;
1100        int s = -1, preauth;
1101
1102        ctx = xcalloc(sizeof(*ctx), 1);
1103
1104        ctx->imap = imap = xcalloc(sizeof(*imap), 1);
1105        imap->buf.sock.fd[0] = imap->buf.sock.fd[1] = -1;
1106        imap->in_progress_append = &imap->in_progress;
1107
1108        /* open connection to IMAP server */
1109
1110        if (srvc->tunnel) {
1111                const char *argv[] = { srvc->tunnel, NULL };
1112                struct child_process tunnel = {NULL};
1113
1114                imap_info("Starting tunnel '%s'... ", srvc->tunnel);
1115
1116                tunnel.argv = argv;
1117                tunnel.use_shell = 1;
1118                tunnel.in = -1;
1119                tunnel.out = -1;
1120                if (start_command(&tunnel))
1121                        die("cannot start proxy %s", argv[0]);
1122
1123                imap->buf.sock.fd[0] = tunnel.out;
1124                imap->buf.sock.fd[1] = tunnel.in;
1125
1126                imap_info("ok\n");
1127        } else {
1128#ifndef NO_IPV6
1129                struct addrinfo hints, *ai0, *ai;
1130                int gai;
1131                char portstr[6];
1132
1133                snprintf(portstr, sizeof(portstr), "%d", srvc->port);
1134
1135                memset(&hints, 0, sizeof(hints));
1136                hints.ai_socktype = SOCK_STREAM;
1137                hints.ai_protocol = IPPROTO_TCP;
1138
1139                imap_info("Resolving %s... ", srvc->host);
1140                gai = getaddrinfo(srvc->host, portstr, &hints, &ai);
1141                if (gai) {
1142                        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai));
1143                        goto bail;
1144                }
1145                imap_info("ok\n");
1146
1147                for (ai0 = ai; ai; ai = ai->ai_next) {
1148                        char addr[NI_MAXHOST];
1149
1150                        s = socket(ai->ai_family, ai->ai_socktype,
1151                                   ai->ai_protocol);
1152                        if (s < 0)
1153                                continue;
1154
1155                        getnameinfo(ai->ai_addr, ai->ai_addrlen, addr,
1156                                    sizeof(addr), NULL, 0, NI_NUMERICHOST);
1157                        imap_info("Connecting to [%s]:%s... ", addr, portstr);
1158
1159                        if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0) {
1160                                close(s);
1161                                s = -1;
1162                                perror("connect");
1163                                continue;
1164                        }
1165
1166                        break;
1167                }
1168                freeaddrinfo(ai0);
1169#else /* NO_IPV6 */
1170                struct hostent *he;
1171                struct sockaddr_in addr;
1172
1173                memset(&addr, 0, sizeof(addr));
1174                addr.sin_port = htons(srvc->port);
1175                addr.sin_family = AF_INET;
1176
1177                imap_info("Resolving %s... ", srvc->host);
1178                he = gethostbyname(srvc->host);
1179                if (!he) {
1180                        perror("gethostbyname");
1181                        goto bail;
1182                }
1183                imap_info("ok\n");
1184
1185                addr.sin_addr.s_addr = *((int *) he->h_addr_list[0]);
1186
1187                s = socket(PF_INET, SOCK_STREAM, 0);
1188
1189                imap_info("Connecting to %s:%hu... ", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
1190                if (connect(s, (struct sockaddr *)&addr, sizeof(addr))) {
1191                        close(s);
1192                        s = -1;
1193                        perror("connect");
1194                }
1195#endif
1196                if (s < 0) {
1197                        fputs("Error: unable to connect to server.\n", stderr);
1198                        goto bail;
1199                }
1200
1201                imap->buf.sock.fd[0] = s;
1202                imap->buf.sock.fd[1] = dup(s);
1203
1204                if (srvc->use_ssl &&
1205                    ssl_socket_connect(&imap->buf.sock, 0, srvc->ssl_verify)) {
1206                        close(s);
1207                        goto bail;
1208                }
1209                imap_info("ok\n");
1210        }
1211
1212        /* read the greeting string */
1213        if (buffer_gets(&imap->buf, &rsp)) {
1214                fprintf(stderr, "IMAP error: no greeting response\n");
1215                goto bail;
1216        }
1217        arg = next_arg(&rsp);
1218        if (!arg || *arg != '*' || (arg = next_arg(&rsp)) == NULL) {
1219                fprintf(stderr, "IMAP error: invalid greeting response\n");
1220                goto bail;
1221        }
1222        preauth = 0;
1223        if (!strcmp("PREAUTH", arg))
1224                preauth = 1;
1225        else if (strcmp("OK", arg) != 0) {
1226                fprintf(stderr, "IMAP error: unknown greeting response\n");
1227                goto bail;
1228        }
1229        parse_response_code(ctx, NULL, rsp);
1230        if (!imap->caps && imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1231                goto bail;
1232
1233        if (!preauth) {
1234#ifndef NO_OPENSSL
1235                if (!srvc->use_ssl && CAP(STARTTLS)) {
1236                        if (imap_exec(ctx, NULL, "STARTTLS") != RESP_OK)
1237                                goto bail;
1238                        if (ssl_socket_connect(&imap->buf.sock, 1,
1239                                               srvc->ssl_verify))
1240                                goto bail;
1241                        /* capabilities may have changed, so get the new capabilities */
1242                        if (imap_exec(ctx, NULL, "CAPABILITY") != RESP_OK)
1243                                goto bail;
1244                }
1245#endif
1246                imap_info("Logging in...\n");
1247                if (!srvc->user) {
1248                        fprintf(stderr, "Skipping server %s, no user\n", srvc->host);
1249                        goto bail;
1250                }
1251                if (!srvc->pass) {
1252                        struct strbuf prompt = STRBUF_INIT;
1253                        strbuf_addf(&prompt, "Password (%s@%s): ", srvc->user, srvc->host);
1254                        arg = git_getpass(prompt.buf);
1255                        strbuf_release(&prompt);
1256                        if (!*arg) {
1257                                fprintf(stderr, "Skipping account %s@%s, no password\n", srvc->user, srvc->host);
1258                                goto bail;
1259                        }
1260                        /*
1261                         * getpass() returns a pointer to a static buffer.  make a copy
1262                         * for long term storage.
1263                         */
1264                        srvc->pass = xstrdup(arg);
1265                }
1266                if (CAP(NOLOGIN)) {
1267                        fprintf(stderr, "Skipping account %s@%s, server forbids LOGIN\n", srvc->user, srvc->host);
1268                        goto bail;
1269                }
1270
1271                if (srvc->auth_method) {
1272                        struct imap_cmd_cb cb;
1273
1274                        if (!strcmp(srvc->auth_method, "CRAM-MD5")) {
1275                                if (!CAP(AUTH_CRAM_MD5)) {
1276                                        fprintf(stderr, "You specified"
1277                                                "CRAM-MD5 as authentication method, "
1278                                                "but %s doesn't support it.\n", srvc->host);
1279                                        goto bail;
1280                                }
1281                                /* CRAM-MD5 */
1282
1283                                memset(&cb, 0, sizeof(cb));
1284                                cb.cont = auth_cram_md5;
1285                                if (imap_exec(ctx, &cb, "AUTHENTICATE CRAM-MD5") != RESP_OK) {
1286                                        fprintf(stderr, "IMAP error: AUTHENTICATE CRAM-MD5 failed\n");
1287                                        goto bail;
1288                                }
1289                        } else {
1290                                fprintf(stderr, "Unknown authentication method:%s\n", srvc->host);
1291                                goto bail;
1292                        }
1293                } else {
1294                        if (!imap->buf.sock.ssl)
1295                                imap_warn("*** IMAP Warning *** Password is being "
1296                                          "sent in the clear\n");
1297                        if (imap_exec(ctx, NULL, "LOGIN \"%s\" \"%s\"", srvc->user, srvc->pass) != RESP_OK) {
1298                                fprintf(stderr, "IMAP error: LOGIN failed\n");
1299                                goto bail;
1300                        }
1301                }
1302        } /* !preauth */
1303
1304        ctx->prefix = "";
1305        ctx->trashnc = 1;
1306        return (struct store *)ctx;
1307
1308bail:
1309        imap_close_store(&ctx->gen);
1310        return NULL;
1311}
1312
1313static int imap_make_flags(int flags, char *buf)
1314{
1315        const char *s;
1316        unsigned i, d;
1317
1318        for (i = d = 0; i < ARRAY_SIZE(Flags); i++)
1319                if (flags & (1 << i)) {
1320                        buf[d++] = ' ';
1321                        buf[d++] = '\\';
1322                        for (s = Flags[i]; *s; s++)
1323                                buf[d++] = *s;
1324                }
1325        buf[0] = '(';
1326        buf[d++] = ')';
1327        return d;
1328}
1329
1330static void lf_to_crlf(struct msg_data *msg)
1331{
1332        char *new;
1333        int i, j, lfnum = 0;
1334
1335        if (msg->data[0] == '\n')
1336                lfnum++;
1337        for (i = 1; i < msg->len; i++) {
1338                if (msg->data[i - 1] != '\r' && msg->data[i] == '\n')
1339                        lfnum++;
1340        }
1341
1342        new = xmalloc(msg->len + lfnum);
1343        if (msg->data[0] == '\n') {
1344                new[0] = '\r';
1345                new[1] = '\n';
1346                i = 1;
1347                j = 2;
1348        } else {
1349                new[0] = msg->data[0];
1350                i = 1;
1351                j = 1;
1352        }
1353        for ( ; i < msg->len; i++) {
1354                if (msg->data[i] != '\n') {
1355                        new[j++] = msg->data[i];
1356                        continue;
1357                }
1358                if (msg->data[i - 1] != '\r')
1359                        new[j++] = '\r';
1360                /* otherwise it already had CR before */
1361                new[j++] = '\n';
1362        }
1363        msg->len += lfnum;
1364        free(msg->data);
1365        msg->data = new;
1366}
1367
1368static int imap_store_msg(struct store *gctx, struct msg_data *data)
1369{
1370        struct imap_store *ctx = (struct imap_store *)gctx;
1371        struct imap *imap = ctx->imap;
1372        struct imap_cmd_cb cb;
1373        const char *prefix, *box;
1374        int ret, d;
1375        char flagstr[128];
1376
1377        lf_to_crlf(data);
1378        memset(&cb, 0, sizeof(cb));
1379
1380        cb.dlen = data->len;
1381        cb.data = xmalloc(cb.dlen);
1382        memcpy(cb.data, data->data, data->len);
1383
1384        d = 0;
1385        if (data->flags) {
1386                d = imap_make_flags(data->flags, flagstr);
1387                flagstr[d++] = ' ';
1388        }
1389        flagstr[d] = 0;
1390
1391        box = gctx->name;
1392        prefix = !strcmp(box, "INBOX") ? "" : ctx->prefix;
1393        cb.create = 0;
1394        ret = imap_exec_m(ctx, &cb, "APPEND \"%s%s\" %s", prefix, box, flagstr);
1395        imap->caps = imap->rcaps;
1396        if (ret != DRV_OK)
1397                return ret;
1398        gctx->count++;
1399
1400        return DRV_OK;
1401}
1402
1403static void encode_html_chars(struct strbuf *p)
1404{
1405        int i;
1406        for (i = 0; i < p->len; i++) {
1407                if (p->buf[i] == '&')
1408                        strbuf_splice(p, i, 1, "&amp;", 5);
1409                if (p->buf[i] == '<')
1410                        strbuf_splice(p, i, 1, "&lt;", 4);
1411                if (p->buf[i] == '>')
1412                        strbuf_splice(p, i, 1, "&gt;", 4);
1413                if (p->buf[i] == '"')
1414                        strbuf_splice(p, i, 1, "&quot;", 6);
1415        }
1416}
1417static void wrap_in_html(struct msg_data *msg)
1418{
1419        struct strbuf buf = STRBUF_INIT;
1420        struct strbuf **lines;
1421        struct strbuf **p;
1422        static char *content_type = "Content-Type: text/html;\n";
1423        static char *pre_open = "<pre>\n";
1424        static char *pre_close = "</pre>\n";
1425        int added_header = 0;
1426
1427        strbuf_attach(&buf, msg->data, msg->len, msg->len);
1428        lines = strbuf_split(&buf, '\n');
1429        strbuf_release(&buf);
1430        for (p = lines; *p; p++) {
1431                if (! added_header) {
1432                        if ((*p)->len == 1 && *((*p)->buf) == '\n') {
1433                                strbuf_addstr(&buf, content_type);
1434                                strbuf_addbuf(&buf, *p);
1435                                strbuf_addstr(&buf, pre_open);
1436                                added_header = 1;
1437                                continue;
1438                        }
1439                }
1440                else
1441                        encode_html_chars(*p);
1442                strbuf_addbuf(&buf, *p);
1443        }
1444        strbuf_addstr(&buf, pre_close);
1445        strbuf_list_free(lines);
1446        msg->len  = buf.len;
1447        msg->data = strbuf_detach(&buf, NULL);
1448}
1449
1450#define CHUNKSIZE 0x1000
1451
1452static int read_message(FILE *f, struct msg_data *msg)
1453{
1454        struct strbuf buf = STRBUF_INIT;
1455
1456        memset(msg, 0, sizeof(*msg));
1457
1458        do {
1459                if (strbuf_fread(&buf, CHUNKSIZE, f) <= 0)
1460                        break;
1461        } while (!feof(f));
1462
1463        msg->len  = buf.len;
1464        msg->data = strbuf_detach(&buf, NULL);
1465        return msg->len;
1466}
1467
1468static int count_messages(struct msg_data *msg)
1469{
1470        int count = 0;
1471        char *p = msg->data;
1472
1473        while (1) {
1474                if (!prefixcmp(p, "From ")) {
1475                        p = strstr(p+5, "\nFrom: ");
1476                        if (!p) break;
1477                        p = strstr(p+7, "\nDate: ");
1478                        if (!p) break;
1479                        p = strstr(p+7, "\nSubject: ");
1480                        if (!p) break;
1481                        p += 10;
1482                        count++;
1483                }
1484                p = strstr(p+5, "\nFrom ");
1485                if (!p)
1486                        break;
1487                p++;
1488        }
1489        return count;
1490}
1491
1492static int split_msg(struct msg_data *all_msgs, struct msg_data *msg, int *ofs)
1493{
1494        char *p, *data;
1495
1496        memset(msg, 0, sizeof *msg);
1497        if (*ofs >= all_msgs->len)
1498                return 0;
1499
1500        data = &all_msgs->data[*ofs];
1501        msg->len = all_msgs->len - *ofs;
1502
1503        if (msg->len < 5 || prefixcmp(data, "From "))
1504                return 0;
1505
1506        p = strchr(data, '\n');
1507        if (p) {
1508                p = &p[1];
1509                msg->len -= p-data;
1510                *ofs += p-data;
1511                data = p;
1512        }
1513
1514        p = strstr(data, "\nFrom ");
1515        if (p)
1516                msg->len = &p[1] - data;
1517
1518        msg->data = xmemdupz(data, msg->len);
1519        *ofs += msg->len;
1520        return 1;
1521}
1522
1523static char *imap_folder;
1524
1525static int git_imap_config(const char *key, const char *val, void *cb)
1526{
1527        char imap_key[] = "imap.";
1528
1529        if (strncmp(key, imap_key, sizeof imap_key - 1))
1530                return 0;
1531
1532        key += sizeof imap_key - 1;
1533
1534        /* check booleans first, and barf on others */
1535        if (!strcmp("sslverify", key))
1536                server.ssl_verify = git_config_bool(key, val);
1537        else if (!strcmp("preformattedhtml", key))
1538                server.use_html = git_config_bool(key, val);
1539        else if (!val)
1540                return config_error_nonbool(key);
1541
1542        if (!strcmp("folder", key)) {
1543                imap_folder = xstrdup(val);
1544        } else if (!strcmp("host", key)) {
1545                if (!prefixcmp(val, "imap:"))
1546                        val += 5;
1547                else if (!prefixcmp(val, "imaps:")) {
1548                        val += 6;
1549                        server.use_ssl = 1;
1550                }
1551                if (!prefixcmp(val, "//"))
1552                        val += 2;
1553                server.host = xstrdup(val);
1554        } else if (!strcmp("user", key))
1555                server.user = xstrdup(val);
1556        else if (!strcmp("pass", key))
1557                server.pass = xstrdup(val);
1558        else if (!strcmp("port", key))
1559                server.port = git_config_int(key, val);
1560        else if (!strcmp("tunnel", key))
1561                server.tunnel = xstrdup(val);
1562        else if (!strcmp("authmethod", key))
1563                server.auth_method = xstrdup(val);
1564
1565        return 0;
1566}
1567
1568int main(int argc, char **argv)
1569{
1570        struct msg_data all_msgs, msg;
1571        struct store *ctx = NULL;
1572        int ofs = 0;
1573        int r;
1574        int total, n = 0;
1575        int nongit_ok;
1576
1577        git_extract_argv0_path(argv[0]);
1578
1579        git_setup_gettext();
1580
1581        if (argc != 1)
1582                usage(imap_send_usage);
1583
1584        setup_git_directory_gently(&nongit_ok);
1585        git_config(git_imap_config, NULL);
1586
1587        if (!server.port)
1588                server.port = server.use_ssl ? 993 : 143;
1589
1590        if (!imap_folder) {
1591                fprintf(stderr, "no imap store specified\n");
1592                return 1;
1593        }
1594        if (!server.host) {
1595                if (!server.tunnel) {
1596                        fprintf(stderr, "no imap host specified\n");
1597                        return 1;
1598                }
1599                server.host = "tunnel";
1600        }
1601
1602        /* read the messages */
1603        if (!read_message(stdin, &all_msgs)) {
1604                fprintf(stderr, "nothing to send\n");
1605                return 1;
1606        }
1607
1608        total = count_messages(&all_msgs);
1609        if (!total) {
1610                fprintf(stderr, "no messages to send\n");
1611                return 1;
1612        }
1613
1614        /* write it to the imap server */
1615        ctx = imap_open_store(&server);
1616        if (!ctx) {
1617                fprintf(stderr, "failed to open store\n");
1618                return 1;
1619        }
1620
1621        fprintf(stderr, "sending %d message%s\n", total, (total != 1) ? "s" : "");
1622        ctx->name = imap_folder;
1623        while (1) {
1624                unsigned percent = n * 100 / total;
1625                fprintf(stderr, "%4u%% (%d/%d) done\r", percent, n, total);
1626                if (!split_msg(&all_msgs, &msg, &ofs))
1627                        break;
1628                if (server.use_html)
1629                        wrap_in_html(&msg);
1630                r = imap_store_msg(ctx, &msg);
1631                if (r != DRV_OK)
1632                        break;
1633                n++;
1634        }
1635        fprintf(stderr, "\n");
1636
1637        imap_close_store(ctx);
1638
1639        return 0;
1640}