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