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