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