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