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