imap-send.con commit Use strbufs to in read_message (imap-send.c), custom buffer--. (635d043)
   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 "strbuf.h"
  27
  28typedef struct store_conf {
  29        char *name;
  30        const char *path; /* should this be here? its interpretation is driver-specific */
  31        char *map_inbox;
  32        char *trash;
  33        unsigned max_size; /* off_t is overkill */
  34        unsigned trash_remote_new:1, trash_only_new:1;
  35} store_conf_t;
  36
  37typedef struct string_list {
  38        struct string_list *next;
  39        char string[1];
  40} string_list_t;
  41
  42typedef struct channel_conf {
  43        struct channel_conf *next;
  44        char *name;
  45        store_conf_t *master, *slave;
  46        char *master_name, *slave_name;
  47        char *sync_state;
  48        string_list_t *patterns;
  49        int mops, sops;
  50        unsigned max_messages; /* for slave only */
  51} channel_conf_t;
  52
  53typedef struct group_conf {
  54        struct group_conf *next;
  55        char *name;
  56        string_list_t *channels;
  57} group_conf_t;
  58
  59/* For message->status */
  60#define M_RECENT       (1<<0) /* unsyncable flag; maildir_* depend on this being 1<<0 */
  61#define M_DEAD         (1<<1) /* expunged */
  62#define M_FLAGS        (1<<2) /* flags fetched */
  63
  64typedef struct message {
  65        struct message *next;
  66        /* string_list_t *keywords; */
  67        size_t size; /* zero implies "not fetched" */
  68        int uid;
  69        unsigned char flags, status;
  70} message_t;
  71
  72typedef struct store {
  73        store_conf_t *conf; /* foreign */
  74
  75        /* currently open mailbox */
  76        const char *name; /* foreign! maybe preset? */
  77        char *path; /* own */
  78        message_t *msgs; /* own */
  79        int uidvalidity;
  80        unsigned char opts; /* maybe preset? */
  81        /* note that the following do _not_ reflect stats from msgs, but mailbox totals */
  82        int count; /* # of messages */
  83        int recent; /* # of recent messages - don't trust this beyond the initial read */
  84} store_t;
  85
  86typedef struct {
  87        char *data;
  88        int len;
  89        unsigned char flags;
  90        unsigned int crlf:1;
  91} msg_data_t;
  92
  93#define DRV_OK          0
  94#define DRV_MSG_BAD     -1
  95#define DRV_BOX_BAD     -2
  96#define DRV_STORE_BAD   -3
  97
  98static int Verbose, Quiet;
  99
 100static void imap_info( const char *, ... );
 101static void imap_warn( const char *, ... );
 102
 103static char *next_arg( char ** );
 104
 105static void free_generic_messages( message_t * );
 106
 107static int nfsnprintf( char *buf, int blen, const char *fmt, ... );
 108
 109
 110static void arc4_init( void );
 111static unsigned char arc4_getbyte( void );
 112
 113typedef struct imap_server_conf {
 114        char *name;
 115        char *tunnel;
 116        char *host;
 117        int port;
 118        char *user;
 119        char *pass;
 120} imap_server_conf_t;
 121
 122typedef struct imap_store_conf {
 123        store_conf_t gen;
 124        imap_server_conf_t *server;
 125        unsigned use_namespace:1;
 126} imap_store_conf_t;
 127
 128#define NIL     (void*)0x1
 129#define LIST    (void*)0x2
 130
 131typedef struct _list {
 132        struct _list *next, *child;
 133        char *val;
 134        int len;
 135} list_t;
 136
 137typedef struct {
 138        int fd;
 139} Socket_t;
 140
 141typedef struct {
 142        Socket_t sock;
 143        int bytes;
 144        int offset;
 145        char buf[1024];
 146} buffer_t;
 147
 148struct imap_cmd;
 149
 150typedef struct imap {
 151        int uidnext; /* from SELECT responses */
 152        list_t *ns_personal, *ns_other, *ns_shared; /* NAMESPACE info */
 153        unsigned caps, rcaps; /* CAPABILITY results */
 154        /* command queue */
 155        int nexttag, num_in_progress, literal_pending;
 156        struct imap_cmd *in_progress, **in_progress_append;
 157        buffer_t buf; /* this is BIG, so put it last */
 158} imap_t;
 159
 160typedef struct imap_store {
 161        store_t gen;
 162        int uidvalidity;
 163        imap_t *imap;
 164        const char *prefix;
 165        unsigned /*currentnc:1,*/ trashnc:1;
 166} imap_store_t;
 167
 168struct imap_cmd_cb {
 169        int (*cont)( imap_store_t *ctx, struct imap_cmd *cmd, const char *prompt );
 170        void (*done)( imap_store_t *ctx, struct imap_cmd *cmd, int response);
 171        void *ctx;
 172        char *data;
 173        int dlen;
 174        int uid;
 175        unsigned create:1, trycreate:1;
 176};
 177
 178struct imap_cmd {
 179        struct imap_cmd *next;
 180        struct imap_cmd_cb cb;
 181        char *cmd;
 182        int tag;
 183};
 184
 185#define CAP(cap) (imap->caps & (1 << (cap)))
 186
 187enum CAPABILITY {
 188        NOLOGIN = 0,
 189        UIDPLUS,
 190        LITERALPLUS,
 191        NAMESPACE,
 192};
 193
 194static const char *cap_list[] = {
 195        "LOGINDISABLED",
 196        "UIDPLUS",
 197        "LITERAL+",
 198        "NAMESPACE",
 199};
 200
 201#define RESP_OK    0
 202#define RESP_NO    1
 203#define RESP_BAD   2
 204
 205static int get_cmd_result( imap_store_t *ctx, struct imap_cmd *tcmd );
 206
 207
 208static const char *Flags[] = {
 209        "Draft",
 210        "Flagged",
 211        "Answered",
 212        "Seen",
 213        "Deleted",
 214};
 215
 216static void
 217socket_perror( const char *func, Socket_t *sock, int ret )
 218{
 219        if (ret < 0)
 220                perror( func );
 221        else
 222                fprintf( stderr, "%s: unexpected EOF\n", func );
 223}
 224
 225static int
 226socket_read( Socket_t *sock, char *buf, int len )
 227{
 228        ssize_t n = xread( sock->fd, buf, len );
 229        if (n <= 0) {
 230                socket_perror( "read", sock, n );
 231                close( sock->fd );
 232                sock->fd = -1;
 233        }
 234        return n;
 235}
 236
 237static int
 238socket_write( Socket_t *sock, const char *buf, int len )
 239{
 240        int n = write_in_full( sock->fd, buf, len );
 241        if (n != len) {
 242                socket_perror( "write", sock, n );
 243                close( sock->fd );
 244                sock->fd = -1;
 245        }
 246        return n;
 247}
 248
 249/* simple line buffering */
 250static int
 251buffer_gets( buffer_t * b, char **s )
 252{
 253        int n;
 254        int start = b->offset;
 255
 256        *s = b->buf + start;
 257
 258        for (;;) {
 259                /* make sure we have enough data to read the \r\n sequence */
 260                if (b->offset + 1 >= b->bytes) {
 261                        if (start) {
 262                                /* shift down used bytes */
 263                                *s = b->buf;
 264
 265                                assert( start <= b->bytes );
 266                                n = b->bytes - start;
 267
 268                                if (n)
 269                                        memmove(b->buf, b->buf + start, n);
 270                                b->offset -= start;
 271                                b->bytes = n;
 272                                start = 0;
 273                        }
 274
 275                        n = socket_read( &b->sock, b->buf + b->bytes,
 276                                         sizeof(b->buf) - b->bytes );
 277
 278                        if (n <= 0)
 279                                return -1;
 280
 281                        b->bytes += n;
 282                }
 283
 284                if (b->buf[b->offset] == '\r') {
 285                        assert( b->offset + 1 < b->bytes );
 286                        if (b->buf[b->offset + 1] == '\n') {
 287                                b->buf[b->offset] = 0;  /* terminate the string */
 288                                b->offset += 2; /* next line */
 289                                if (Verbose)
 290                                        puts( *s );
 291                                return 0;
 292                        }
 293                }
 294
 295                b->offset++;
 296        }
 297        /* not reached */
 298}
 299
 300static void
 301imap_info( const char *msg, ... )
 302{
 303        va_list va;
 304
 305        if (!Quiet) {
 306                va_start( va, msg );
 307                vprintf( msg, va );
 308                va_end( va );
 309                fflush( stdout );
 310        }
 311}
 312
 313static void
 314imap_warn( const char *msg, ... )
 315{
 316        va_list va;
 317
 318        if (Quiet < 2) {
 319                va_start( va, msg );
 320                vfprintf( stderr, msg, va );
 321                va_end( va );
 322        }
 323}
 324
 325static char *
 326next_arg( char **s )
 327{
 328        char *ret;
 329
 330        if (!s || !*s)
 331                return NULL;
 332        while (isspace( (unsigned char) **s ))
 333                (*s)++;
 334        if (!**s) {
 335                *s = NULL;
 336                return NULL;
 337        }
 338        if (**s == '"') {
 339                ++*s;
 340                ret = *s;
 341                *s = strchr( *s, '"' );
 342        } else {
 343                ret = *s;
 344                while (**s && !isspace( (unsigned char) **s ))
 345                        (*s)++;
 346        }
 347        if (*s) {
 348                if (**s)
 349                        *(*s)++ = 0;
 350                if (!**s)
 351                        *s = NULL;
 352        }
 353        return ret;
 354}
 355
 356static void
 357free_generic_messages( message_t *msgs )
 358{
 359        message_t *tmsg;
 360
 361        for (; msgs; msgs = tmsg) {
 362                tmsg = msgs->next;
 363                free( msgs );
 364        }
 365}
 366
 367static int
 368nfsnprintf( char *buf, int blen, const char *fmt, ... )
 369{
 370        int ret;
 371        va_list va;
 372
 373        va_start( va, fmt );
 374        if (blen <= 0 || (unsigned)(ret = vsnprintf( buf, blen, fmt, va )) >= (unsigned)blen)
 375                die( "Fatal: buffer too small. Please report a bug.\n");
 376        va_end( va );
 377        return ret;
 378}
 379
 380static struct {
 381        unsigned char i, j, s[256];
 382} rs;
 383
 384static void
 385arc4_init( void )
 386{
 387        int i, fd;
 388        unsigned char j, si, dat[128];
 389
 390        if ((fd = open( "/dev/urandom", O_RDONLY )) < 0 && (fd = open( "/dev/random", O_RDONLY )) < 0) {
 391                fprintf( stderr, "Fatal: no random number source available.\n" );
 392                exit( 3 );
 393        }
 394        if (read_in_full( fd, dat, 128 ) != 128) {
 395                fprintf( stderr, "Fatal: cannot read random number source.\n" );
 396                exit( 3 );
 397        }
 398        close( fd );
 399
 400        for (i = 0; i < 256; i++)
 401                rs.s[i] = i;
 402        for (i = j = 0; i < 256; i++) {
 403                si = rs.s[i];
 404                j += si + dat[i & 127];
 405                rs.s[i] = rs.s[j];
 406                rs.s[j] = si;
 407        }
 408        rs.i = rs.j = 0;
 409
 410        for (i = 0; i < 256; i++)
 411                arc4_getbyte();
 412}
 413
 414static unsigned char
 415arc4_getbyte( void )
 416{
 417        unsigned char si, sj;
 418
 419        rs.i++;
 420        si = rs.s[rs.i];
 421        rs.j += si;
 422        sj = rs.s[rs.j];
 423        rs.s[rs.i] = sj;
 424        rs.s[rs.j] = si;
 425        return rs.s[(si + sj) & 0xff];
 426}
 427
 428static struct imap_cmd *
 429v_issue_imap_cmd( imap_store_t *ctx, struct imap_cmd_cb *cb,
 430                  const char *fmt, va_list ap )
 431{
 432        imap_t *imap = ctx->imap;
 433        struct imap_cmd *cmd;
 434        int n, bufl;
 435        char buf[1024];
 436
 437        cmd = xmalloc( sizeof(struct imap_cmd) );
 438        nfvasprintf( &cmd->cmd, fmt, ap );
 439        cmd->tag = ++imap->nexttag;
 440
 441        if (cb)
 442                cmd->cb = *cb;
 443        else
 444                memset( &cmd->cb, 0, sizeof(cmd->cb) );
 445
 446        while (imap->literal_pending)
 447                get_cmd_result( ctx, NULL );
 448
 449        bufl = nfsnprintf( buf, sizeof(buf), cmd->cb.data ? CAP(LITERALPLUS) ?
 450                           "%d %s{%d+}\r\n" : "%d %s{%d}\r\n" : "%d %s\r\n",
 451                           cmd->tag, cmd->cmd, cmd->cb.dlen );
 452        if (Verbose) {
 453                if (imap->num_in_progress)
 454                        printf( "(%d in progress) ", imap->num_in_progress );
 455                if (memcmp( cmd->cmd, "LOGIN", 5 ))
 456                        printf( ">>> %s", buf );
 457                else
 458                        printf( ">>> %d LOGIN <user> <pass>\n", cmd->tag );
 459        }
 460        if (socket_write( &imap->buf.sock, buf, bufl ) != bufl) {
 461                free( cmd->cmd );
 462                free( cmd );
 463                if (cb && cb->data)
 464                        free( cb->data );
 465                return NULL;
 466        }
 467        if (cmd->cb.data) {
 468                if (CAP(LITERALPLUS)) {
 469                        n = socket_write( &imap->buf.sock, cmd->cb.data, cmd->cb.dlen );
 470                        free( cmd->cb.data );
 471                        if (n != cmd->cb.dlen ||
 472                            (n = socket_write( &imap->buf.sock, "\r\n", 2 )) != 2)
 473                        {
 474                                free( cmd->cmd );
 475                                free( cmd );
 476                                return NULL;
 477                        }
 478                        cmd->cb.data = NULL;
 479                } else
 480                        imap->literal_pending = 1;
 481        } else if (cmd->cb.cont)
 482                imap->literal_pending = 1;
 483        cmd->next = NULL;
 484        *imap->in_progress_append = cmd;
 485        imap->in_progress_append = &cmd->next;
 486        imap->num_in_progress++;
 487        return cmd;
 488}
 489
 490static struct imap_cmd *
 491issue_imap_cmd( imap_store_t *ctx, struct imap_cmd_cb *cb, const char *fmt, ... )
 492{
 493        struct imap_cmd *ret;
 494        va_list ap;
 495
 496        va_start( ap, fmt );
 497        ret = v_issue_imap_cmd( ctx, cb, fmt, ap );
 498        va_end( ap );
 499        return ret;
 500}
 501
 502static int
 503imap_exec( imap_store_t *ctx, struct imap_cmd_cb *cb, const char *fmt, ... )
 504{
 505        va_list ap;
 506        struct imap_cmd *cmdp;
 507
 508        va_start( ap, fmt );
 509        cmdp = v_issue_imap_cmd( ctx, cb, fmt, ap );
 510        va_end( ap );
 511        if (!cmdp)
 512                return RESP_BAD;
 513
 514        return get_cmd_result( ctx, cmdp );
 515}
 516
 517static int
 518imap_exec_m( imap_store_t *ctx, struct imap_cmd_cb *cb, const char *fmt, ... )
 519{
 520        va_list ap;
 521        struct imap_cmd *cmdp;
 522
 523        va_start( ap, fmt );
 524        cmdp = v_issue_imap_cmd( ctx, cb, fmt, ap );
 525        va_end( ap );
 526        if (!cmdp)
 527                return DRV_STORE_BAD;
 528
 529        switch (get_cmd_result( ctx, cmdp )) {
 530        case RESP_BAD: return DRV_STORE_BAD;
 531        case RESP_NO: return DRV_MSG_BAD;
 532        default: return DRV_OK;
 533        }
 534}
 535
 536static int
 537is_atom( list_t *list )
 538{
 539        return list && list->val && list->val != NIL && list->val != LIST;
 540}
 541
 542static int
 543is_list( list_t *list )
 544{
 545        return list && list->val == LIST;
 546}
 547
 548static void
 549free_list( list_t *list )
 550{
 551        list_t *tmp;
 552
 553        for (; list; list = tmp) {
 554                tmp = list->next;
 555                if (is_list( list ))
 556                        free_list( list->child );
 557                else if (is_atom( list ))
 558                        free( list->val );
 559                free( list );
 560        }
 561}
 562
 563static int
 564parse_imap_list_l( imap_t *imap, char **sp, list_t **curp, int level )
 565{
 566        list_t *cur;
 567        char *s = *sp, *p;
 568        int n, bytes;
 569
 570        for (;;) {
 571                while (isspace( (unsigned char)*s ))
 572                        s++;
 573                if (level && *s == ')') {
 574                        s++;
 575                        break;
 576                }
 577                *curp = cur = xmalloc( sizeof(*cur) );
 578                curp = &cur->next;
 579                cur->val = NULL; /* for clean bail */
 580                if (*s == '(') {
 581                        /* sublist */
 582                        s++;
 583                        cur->val = LIST;
 584                        if (parse_imap_list_l( imap, &s, &cur->child, level + 1 ))
 585                                goto bail;
 586                } else if (imap && *s == '{') {
 587                        /* literal */
 588                        bytes = cur->len = strtol( s + 1, &s, 10 );
 589                        if (*s != '}')
 590                                goto bail;
 591
 592                        s = cur->val = xmalloc( cur->len );
 593
 594                        /* dump whats left over in the input buffer */
 595                        n = imap->buf.bytes - imap->buf.offset;
 596
 597                        if (n > bytes)
 598                                /* the entire message fit in the buffer */
 599                                n = bytes;
 600
 601                        memcpy( s, imap->buf.buf + imap->buf.offset, n );
 602                        s += n;
 603                        bytes -= n;
 604
 605                        /* mark that we used part of the buffer */
 606                        imap->buf.offset += n;
 607
 608                        /* now read the rest of the message */
 609                        while (bytes > 0) {
 610                                if ((n = socket_read (&imap->buf.sock, s, bytes)) <= 0)
 611                                        goto bail;
 612                                s += n;
 613                                bytes -= n;
 614                        }
 615
 616                        if (buffer_gets( &imap->buf, &s ))
 617                                goto bail;
 618                } else if (*s == '"') {
 619                        /* quoted string */
 620                        s++;
 621                        p = s;
 622                        for (; *s != '"'; s++)
 623                                if (!*s)
 624                                        goto bail;
 625                        cur->len = s - p;
 626                        s++;
 627                        cur->val = xmalloc( cur->len + 1 );
 628                        memcpy( cur->val, p, cur->len );
 629                        cur->val[cur->len] = 0;
 630                } else {
 631                        /* atom */
 632                        p = s;
 633                        for (; *s && !isspace( (unsigned char)*s ); s++)
 634                                if (level && *s == ')')
 635                                        break;
 636                        cur->len = s - p;
 637                        if (cur->len == 3 && !memcmp ("NIL", p, 3))
 638                                cur->val = NIL;
 639                        else {
 640                                cur->val = xmalloc( cur->len + 1 );
 641                                memcpy( cur->val, p, cur->len );
 642                                cur->val[cur->len] = 0;
 643                        }
 644                }
 645
 646                if (!level)
 647                        break;
 648                if (!*s)
 649                        goto bail;
 650        }
 651        *sp = s;
 652        *curp = NULL;
 653        return 0;
 654
 655  bail:
 656        *curp = NULL;
 657        return -1;
 658}
 659
 660static list_t *
 661parse_imap_list( imap_t *imap, char **sp )
 662{
 663        list_t *head;
 664
 665        if (!parse_imap_list_l( imap, sp, &head, 0 ))
 666                return head;
 667        free_list( head );
 668        return NULL;
 669}
 670
 671static list_t *
 672parse_list( char **sp )
 673{
 674        return parse_imap_list( NULL, sp );
 675}
 676
 677static void
 678parse_capability( imap_t *imap, char *cmd )
 679{
 680        char *arg;
 681        unsigned i;
 682
 683        imap->caps = 0x80000000;
 684        while ((arg = next_arg( &cmd )))
 685                for (i = 0; i < ARRAY_SIZE(cap_list); i++)
 686                        if (!strcmp( cap_list[i], arg ))
 687                                imap->caps |= 1 << i;
 688        imap->rcaps = imap->caps;
 689}
 690
 691static int
 692parse_response_code( imap_store_t *ctx, struct imap_cmd_cb *cb, char *s )
 693{
 694        imap_t *imap = ctx->imap;
 695        char *arg, *p;
 696
 697        if (*s != '[')
 698                return RESP_OK;         /* no response code */
 699        s++;
 700        if (!(p = strchr( s, ']' ))) {
 701                fprintf( stderr, "IMAP error: malformed response code\n" );
 702                return RESP_BAD;
 703        }
 704        *p++ = 0;
 705        arg = next_arg( &s );
 706        if (!strcmp( "UIDVALIDITY", arg )) {
 707                if (!(arg = next_arg( &s )) || !(ctx->gen.uidvalidity = atoi( arg ))) {
 708                        fprintf( stderr, "IMAP error: malformed UIDVALIDITY status\n" );
 709                        return RESP_BAD;
 710                }
 711        } else if (!strcmp( "UIDNEXT", arg )) {
 712                if (!(arg = next_arg( &s )) || !(imap->uidnext = atoi( arg ))) {
 713                        fprintf( stderr, "IMAP error: malformed NEXTUID status\n" );
 714                        return RESP_BAD;
 715                }
 716        } else if (!strcmp( "CAPABILITY", arg )) {
 717                parse_capability( imap, s );
 718        } else if (!strcmp( "ALERT", arg )) {
 719                /* RFC2060 says that these messages MUST be displayed
 720                 * to the user
 721                 */
 722                for (; isspace( (unsigned char)*p ); p++);
 723                fprintf( stderr, "*** IMAP ALERT *** %s\n", p );
 724        } else if (cb && cb->ctx && !strcmp( "APPENDUID", arg )) {
 725                if (!(arg = next_arg( &s )) || !(ctx->gen.uidvalidity = atoi( arg )) ||
 726                    !(arg = next_arg( &s )) || !(*(int *)cb->ctx = atoi( arg )))
 727                {
 728                        fprintf( stderr, "IMAP error: malformed APPENDUID status\n" );
 729                        return RESP_BAD;
 730                }
 731        }
 732        return RESP_OK;
 733}
 734
 735static int
 736get_cmd_result( imap_store_t *ctx, struct imap_cmd *tcmd )
 737{
 738        imap_t *imap = ctx->imap;
 739        struct imap_cmd *cmdp, **pcmdp, *ncmdp;
 740        char *cmd, *arg, *arg1, *p;
 741        int n, resp, resp2, tag;
 742
 743        for (;;) {
 744                if (buffer_gets( &imap->buf, &cmd ))
 745                        return RESP_BAD;
 746
 747                arg = next_arg( &cmd );
 748                if (*arg == '*') {
 749                        arg = next_arg( &cmd );
 750                        if (!arg) {
 751                                fprintf( stderr, "IMAP error: unable to parse untagged response\n" );
 752                                return RESP_BAD;
 753                        }
 754
 755                        if (!strcmp( "NAMESPACE", arg )) {
 756                                imap->ns_personal = parse_list( &cmd );
 757                                imap->ns_other = parse_list( &cmd );
 758                                imap->ns_shared = parse_list( &cmd );
 759                        } else if (!strcmp( "OK", arg ) || !strcmp( "BAD", arg ) ||
 760                                   !strcmp( "NO", arg ) || !strcmp( "BYE", arg )) {
 761                                if ((resp = parse_response_code( ctx, NULL, cmd )) != RESP_OK)
 762                                        return resp;
 763                        } else if (!strcmp( "CAPABILITY", arg ))
 764                                parse_capability( imap, cmd );
 765                        else if ((arg1 = next_arg( &cmd ))) {
 766                                if (!strcmp( "EXISTS", arg1 ))
 767                                        ctx->gen.count = atoi( arg );
 768                                else if (!strcmp( "RECENT", arg1 ))
 769                                        ctx->gen.recent = atoi( arg );
 770                        } else {
 771                                fprintf( stderr, "IMAP error: unable to parse untagged response\n" );
 772                                return RESP_BAD;
 773                        }
 774                } else if (!imap->in_progress) {
 775                        fprintf( stderr, "IMAP error: unexpected reply: %s %s\n", arg, cmd ? cmd : "" );
 776                        return RESP_BAD;
 777                } else if (*arg == '+') {
 778                        /* This can happen only with the last command underway, as
 779                           it enforces a round-trip. */
 780                        cmdp = (struct imap_cmd *)((char *)imap->in_progress_append -
 781                               offsetof(struct imap_cmd, next));
 782                        if (cmdp->cb.data) {
 783                                n = socket_write( &imap->buf.sock, cmdp->cb.data, cmdp->cb.dlen );
 784                                free( cmdp->cb.data );
 785                                cmdp->cb.data = NULL;
 786                                if (n != (int)cmdp->cb.dlen)
 787                                        return RESP_BAD;
 788                        } else if (cmdp->cb.cont) {
 789                                if (cmdp->cb.cont( ctx, cmdp, cmd ))
 790                                        return RESP_BAD;
 791                        } else {
 792                                fprintf( stderr, "IMAP error: unexpected command continuation request\n" );
 793                                return RESP_BAD;
 794                        }
 795                        if (socket_write( &imap->buf.sock, "\r\n", 2 ) != 2)
 796                                return RESP_BAD;
 797                        if (!cmdp->cb.cont)
 798                                imap->literal_pending = 0;
 799                        if (!tcmd)
 800                                return DRV_OK;
 801                } else {
 802                        tag = atoi( arg );
 803                        for (pcmdp = &imap->in_progress; (cmdp = *pcmdp); pcmdp = &cmdp->next)
 804                                if (cmdp->tag == tag)
 805                                        goto gottag;
 806                        fprintf( stderr, "IMAP error: unexpected tag %s\n", arg );
 807                        return RESP_BAD;
 808                  gottag:
 809                        if (!(*pcmdp = cmdp->next))
 810                                imap->in_progress_append = pcmdp;
 811                        imap->num_in_progress--;
 812                        if (cmdp->cb.cont || cmdp->cb.data)
 813                                imap->literal_pending = 0;
 814                        arg = next_arg( &cmd );
 815                        if (!strcmp( "OK", arg ))
 816                                resp = DRV_OK;
 817                        else {
 818                                if (!strcmp( "NO", arg )) {
 819                                        if (cmdp->cb.create && cmd && (cmdp->cb.trycreate || !memcmp( cmd, "[TRYCREATE]", 11 ))) { /* SELECT, APPEND or UID COPY */
 820                                                p = strchr( cmdp->cmd, '"' );
 821                                                if (!issue_imap_cmd( ctx, NULL, "CREATE \"%.*s\"", strchr( p + 1, '"' ) - p + 1, p )) {
 822                                                        resp = RESP_BAD;
 823                                                        goto normal;
 824                                                }
 825                                                /* not waiting here violates the spec, but a server that does not
 826                                                   grok this nonetheless violates it too. */
 827                                                cmdp->cb.create = 0;
 828                                                if (!(ncmdp = issue_imap_cmd( ctx, &cmdp->cb, "%s", cmdp->cmd ))) {
 829                                                        resp = RESP_BAD;
 830                                                        goto normal;
 831                                                }
 832                                                free( cmdp->cmd );
 833                                                free( cmdp );
 834                                                if (!tcmd)
 835                                                        return 0;       /* ignored */
 836                                                if (cmdp == tcmd)
 837                                                        tcmd = ncmdp;
 838                                                continue;
 839                                        }
 840                                        resp = RESP_NO;
 841                                } else /*if (!strcmp( "BAD", arg ))*/
 842                                        resp = RESP_BAD;
 843                                fprintf( stderr, "IMAP command '%s' returned response (%s) - %s\n",
 844                                         memcmp (cmdp->cmd, "LOGIN", 5) ?
 845                                                        cmdp->cmd : "LOGIN <user> <pass>",
 846                                                        arg, cmd ? cmd : "");
 847                        }
 848                        if ((resp2 = parse_response_code( ctx, &cmdp->cb, cmd )) > resp)
 849                                resp = resp2;
 850                  normal:
 851                        if (cmdp->cb.done)
 852                                cmdp->cb.done( ctx, cmdp, resp );
 853                        if (cmdp->cb.data)
 854                                free( cmdp->cb.data );
 855                        free( cmdp->cmd );
 856                        free( cmdp );
 857                        if (!tcmd || tcmd == cmdp)
 858                                return resp;
 859                }
 860        }
 861        /* not reached */
 862}
 863
 864static void
 865imap_close_server( imap_store_t *ictx )
 866{
 867        imap_t *imap = ictx->imap;
 868
 869        if (imap->buf.sock.fd != -1) {
 870                imap_exec( ictx, NULL, "LOGOUT" );
 871                close( imap->buf.sock.fd );
 872        }
 873        free_list( imap->ns_personal );
 874        free_list( imap->ns_other );
 875        free_list( imap->ns_shared );
 876        free( imap );
 877}
 878
 879static void
 880imap_close_store( store_t *ctx )
 881{
 882        imap_close_server( (imap_store_t *)ctx );
 883        free_generic_messages( ctx->msgs );
 884        free( ctx );
 885}
 886
 887static store_t *
 888imap_open_store( imap_server_conf_t *srvc )
 889{
 890        imap_store_t *ctx;
 891        imap_t *imap;
 892        char *arg, *rsp;
 893        struct hostent *he;
 894        struct sockaddr_in addr;
 895        int s, a[2], preauth;
 896        pid_t pid;
 897
 898        ctx = xcalloc( sizeof(*ctx), 1 );
 899
 900        ctx->imap = imap = xcalloc( sizeof(*imap), 1 );
 901        imap->buf.sock.fd = -1;
 902        imap->in_progress_append = &imap->in_progress;
 903
 904        /* open connection to IMAP server */
 905
 906        if (srvc->tunnel) {
 907                imap_info( "Starting tunnel '%s'... ", srvc->tunnel );
 908
 909                if (socketpair( PF_UNIX, SOCK_STREAM, 0, a )) {
 910                        perror( "socketpair" );
 911                        exit( 1 );
 912                }
 913
 914                pid = fork();
 915                if (pid < 0)
 916                        _exit( 127 );
 917                if (!pid) {
 918                        if (dup2( a[0], 0 ) == -1 || dup2( a[0], 1 ) == -1)
 919                                _exit( 127 );
 920                        close( a[0] );
 921                        close( a[1] );
 922                        execl( "/bin/sh", "sh", "-c", srvc->tunnel, NULL );
 923                        _exit( 127 );
 924                }
 925
 926                close (a[0]);
 927
 928                imap->buf.sock.fd = a[1];
 929
 930                imap_info( "ok\n" );
 931        } else {
 932                memset( &addr, 0, sizeof(addr) );
 933                addr.sin_port = htons( srvc->port );
 934                addr.sin_family = AF_INET;
 935
 936                imap_info( "Resolving %s... ", srvc->host );
 937                he = gethostbyname( srvc->host );
 938                if (!he) {
 939                        perror( "gethostbyname" );
 940                        goto bail;
 941                }
 942                imap_info( "ok\n" );
 943
 944                addr.sin_addr.s_addr = *((int *) he->h_addr_list[0]);
 945
 946                s = socket( PF_INET, SOCK_STREAM, 0 );
 947
 948                imap_info( "Connecting to %s:%hu... ", inet_ntoa( addr.sin_addr ), ntohs( addr.sin_port ) );
 949                if (connect( s, (struct sockaddr *)&addr, sizeof(addr) )) {
 950                        close( s );
 951                        perror( "connect" );
 952                        goto bail;
 953                }
 954                imap_info( "ok\n" );
 955
 956                imap->buf.sock.fd = s;
 957
 958        }
 959
 960        /* read the greeting string */
 961        if (buffer_gets( &imap->buf, &rsp )) {
 962                fprintf( stderr, "IMAP error: no greeting response\n" );
 963                goto bail;
 964        }
 965        arg = next_arg( &rsp );
 966        if (!arg || *arg != '*' || (arg = next_arg( &rsp )) == NULL) {
 967                fprintf( stderr, "IMAP error: invalid greeting response\n" );
 968                goto bail;
 969        }
 970        preauth = 0;
 971        if (!strcmp( "PREAUTH", arg ))
 972                preauth = 1;
 973        else if (strcmp( "OK", arg ) != 0) {
 974                fprintf( stderr, "IMAP error: unknown greeting response\n" );
 975                goto bail;
 976        }
 977        parse_response_code( ctx, NULL, rsp );
 978        if (!imap->caps && imap_exec( ctx, NULL, "CAPABILITY" ) != RESP_OK)
 979                goto bail;
 980
 981        if (!preauth) {
 982
 983                imap_info ("Logging in...\n");
 984                if (!srvc->user) {
 985                        fprintf( stderr, "Skipping server %s, no user\n", srvc->host );
 986                        goto bail;
 987                }
 988                if (!srvc->pass) {
 989                        char prompt[80];
 990                        sprintf( prompt, "Password (%s@%s): ", srvc->user, srvc->host );
 991                        arg = getpass( prompt );
 992                        if (!arg) {
 993                                perror( "getpass" );
 994                                exit( 1 );
 995                        }
 996                        if (!*arg) {
 997                                fprintf( stderr, "Skipping account %s@%s, no password\n", srvc->user, srvc->host );
 998                                goto bail;
 999                        }
1000                        /*
1001                         * getpass() returns a pointer to a static buffer.  make a copy
1002                         * for long term storage.
1003                         */
1004                        srvc->pass = xstrdup( arg );
1005                }
1006                if (CAP(NOLOGIN)) {
1007                        fprintf( stderr, "Skipping account %s@%s, server forbids LOGIN\n", srvc->user, srvc->host );
1008                        goto bail;
1009                }
1010                imap_warn( "*** IMAP Warning *** Password is being sent in the clear\n" );
1011                if (imap_exec( ctx, NULL, "LOGIN \"%s\" \"%s\"", srvc->user, srvc->pass ) != RESP_OK) {
1012                        fprintf( stderr, "IMAP error: LOGIN failed\n" );
1013                        goto bail;
1014                }
1015        } /* !preauth */
1016
1017        ctx->prefix = "";
1018        ctx->trashnc = 1;
1019        return (store_t *)ctx;
1020
1021  bail:
1022        imap_close_store( &ctx->gen );
1023        return NULL;
1024}
1025
1026static int
1027imap_make_flags( int flags, char *buf )
1028{
1029        const char *s;
1030        unsigned i, d;
1031
1032        for (i = d = 0; i < ARRAY_SIZE(Flags); i++)
1033                if (flags & (1 << i)) {
1034                        buf[d++] = ' ';
1035                        buf[d++] = '\\';
1036                        for (s = Flags[i]; *s; s++)
1037                                buf[d++] = *s;
1038                }
1039        buf[0] = '(';
1040        buf[d++] = ')';
1041        return d;
1042}
1043
1044#define TUIDL 8
1045
1046static int
1047imap_store_msg( store_t *gctx, msg_data_t *data, int *uid )
1048{
1049        imap_store_t *ctx = (imap_store_t *)gctx;
1050        imap_t *imap = ctx->imap;
1051        struct imap_cmd_cb cb;
1052        char *fmap, *buf;
1053        const char *prefix, *box;
1054        int ret, i, j, d, len, extra, nocr;
1055        int start, sbreak = 0, ebreak = 0;
1056        char flagstr[128], tuid[TUIDL * 2 + 1];
1057
1058        memset( &cb, 0, sizeof(cb) );
1059
1060        fmap = data->data;
1061        len = data->len;
1062        nocr = !data->crlf;
1063        extra = 0, i = 0;
1064        if (!CAP(UIDPLUS) && uid) {
1065          nloop:
1066                start = i;
1067                while (i < len)
1068                        if (fmap[i++] == '\n') {
1069                                extra += nocr;
1070                                if (i - 2 + nocr == start) {
1071                                        sbreak = ebreak = i - 2 + nocr;
1072                                        goto mktid;
1073                                }
1074                                if (!memcmp( fmap + start, "X-TUID: ", 8 )) {
1075                                        extra -= (ebreak = i) - (sbreak = start) + nocr;
1076                                        goto mktid;
1077                                }
1078                                goto nloop;
1079                        }
1080                /* invalid message */
1081                free( fmap );
1082                return DRV_MSG_BAD;
1083         mktid:
1084                for (j = 0; j < TUIDL; j++)
1085                        sprintf( tuid + j * 2, "%02x", arc4_getbyte() );
1086                extra += 8 + TUIDL * 2 + 2;
1087        }
1088        if (nocr)
1089                for (; i < len; i++)
1090                        if (fmap[i] == '\n')
1091                                extra++;
1092
1093        cb.dlen = len + extra;
1094        buf = cb.data = xmalloc( cb.dlen );
1095        i = 0;
1096        if (!CAP(UIDPLUS) && uid) {
1097                if (nocr) {
1098                        for (; i < sbreak; i++)
1099                                if (fmap[i] == '\n') {
1100                                        *buf++ = '\r';
1101                                        *buf++ = '\n';
1102                                } else
1103                                        *buf++ = fmap[i];
1104                } else {
1105                        memcpy( buf, fmap, sbreak );
1106                        buf += sbreak;
1107                }
1108                memcpy( buf, "X-TUID: ", 8 );
1109                buf += 8;
1110                memcpy( buf, tuid, TUIDL * 2 );
1111                buf += TUIDL * 2;
1112                *buf++ = '\r';
1113                *buf++ = '\n';
1114                i = ebreak;
1115        }
1116        if (nocr) {
1117                for (; i < len; i++)
1118                        if (fmap[i] == '\n') {
1119                                *buf++ = '\r';
1120                                *buf++ = '\n';
1121                        } else
1122                                *buf++ = fmap[i];
1123        } else
1124                memcpy( buf, fmap + i, len - i );
1125
1126        free( fmap );
1127
1128        d = 0;
1129        if (data->flags) {
1130                d = imap_make_flags( data->flags, flagstr );
1131                flagstr[d++] = ' ';
1132        }
1133        flagstr[d] = 0;
1134
1135        if (!uid) {
1136                box = gctx->conf->trash;
1137                prefix = ctx->prefix;
1138                cb.create = 1;
1139                if (ctx->trashnc)
1140                        imap->caps = imap->rcaps & ~(1 << LITERALPLUS);
1141        } else {
1142                box = gctx->name;
1143                prefix = !strcmp( box, "INBOX" ) ? "" : ctx->prefix;
1144                cb.create = 0;
1145        }
1146        cb.ctx = uid;
1147        ret = imap_exec_m( ctx, &cb, "APPEND \"%s%s\" %s", prefix, box, flagstr );
1148        imap->caps = imap->rcaps;
1149        if (ret != DRV_OK)
1150                return ret;
1151        if (!uid)
1152                ctx->trashnc = 0;
1153        else
1154                gctx->count++;
1155
1156        return DRV_OK;
1157}
1158
1159#define CHUNKSIZE 0x1000
1160
1161static int
1162read_message( FILE *f, msg_data_t *msg )
1163{
1164        struct strbuf buf;
1165
1166        memset(msg, 0, sizeof(*msg));
1167        strbuf_init(&buf, 0);
1168
1169        do {
1170                if (strbuf_fread(&buf, CHUNKSIZE, f) <= 0)
1171                        break;
1172        } while (!feof(f));
1173
1174        msg->len  = buf.len;
1175        msg->data = strbuf_detach(&buf);
1176        return msg->len;
1177}
1178
1179static int
1180count_messages( msg_data_t *msg )
1181{
1182        int count = 0;
1183        char *p = msg->data;
1184
1185        while (1) {
1186                if (!prefixcmp(p, "From ")) {
1187                        count++;
1188                        p += 5;
1189                }
1190                p = strstr( p+5, "\nFrom ");
1191                if (!p)
1192                        break;
1193                p++;
1194        }
1195        return count;
1196}
1197
1198static int
1199split_msg( msg_data_t *all_msgs, msg_data_t *msg, int *ofs )
1200{
1201        char *p, *data;
1202
1203        memset( msg, 0, sizeof *msg );
1204        if (*ofs >= all_msgs->len)
1205                return 0;
1206
1207        data = &all_msgs->data[ *ofs ];
1208        msg->len = all_msgs->len - *ofs;
1209
1210        if (msg->len < 5 || prefixcmp(data, "From "))
1211                return 0;
1212
1213        p = strchr( data, '\n' );
1214        if (p) {
1215                p = &p[1];
1216                msg->len -= p-data;
1217                *ofs += p-data;
1218                data = p;
1219        }
1220
1221        p = strstr( data, "\nFrom " );
1222        if (p)
1223                msg->len = &p[1] - data;
1224
1225        msg->data = xmalloc( msg->len + 1 );
1226        if (!msg->data)
1227                return 0;
1228
1229        memcpy( msg->data, data, msg->len );
1230        msg->data[ msg->len ] = 0;
1231
1232        *ofs += msg->len;
1233        return 1;
1234}
1235
1236static imap_server_conf_t server =
1237{
1238        NULL,   /* name */
1239        NULL,   /* tunnel */
1240        NULL,   /* host */
1241        0,      /* port */
1242        NULL,   /* user */
1243        NULL,   /* pass */
1244};
1245
1246static char *imap_folder;
1247
1248static int
1249git_imap_config(const char *key, const char *val)
1250{
1251        char imap_key[] = "imap.";
1252
1253        if (strncmp( key, imap_key, sizeof imap_key - 1 ))
1254                return 0;
1255        key += sizeof imap_key - 1;
1256
1257        if (!strcmp( "folder", key )) {
1258                imap_folder = xstrdup( val );
1259        } else if (!strcmp( "host", key )) {
1260                {
1261                        if (!prefixcmp(val, "imap:"))
1262                                val += 5;
1263                        if (!server.port)
1264                                server.port = 143;
1265                }
1266                if (!prefixcmp(val, "//"))
1267                        val += 2;
1268                server.host = xstrdup( val );
1269        }
1270        else if (!strcmp( "user", key ))
1271                server.user = xstrdup( val );
1272        else if (!strcmp( "pass", key ))
1273                server.pass = xstrdup( val );
1274        else if (!strcmp( "port", key ))
1275                server.port = git_config_int( key, val );
1276        else if (!strcmp( "tunnel", key ))
1277                server.tunnel = xstrdup( val );
1278        return 0;
1279}
1280
1281int
1282main(int argc, char **argv)
1283{
1284        msg_data_t all_msgs, msg;
1285        store_t *ctx = NULL;
1286        int uid = 0;
1287        int ofs = 0;
1288        int r;
1289        int total, n = 0;
1290
1291        /* init the random number generator */
1292        arc4_init();
1293
1294        git_config( git_imap_config );
1295
1296        if (!imap_folder) {
1297                fprintf( stderr, "no imap store specified\n" );
1298                return 1;
1299        }
1300
1301        /* read the messages */
1302        if (!read_message( stdin, &all_msgs )) {
1303                fprintf(stderr,"nothing to send\n");
1304                return 1;
1305        }
1306
1307        total = count_messages( &all_msgs );
1308        if (!total) {
1309                fprintf(stderr,"no messages to send\n");
1310                return 1;
1311        }
1312
1313        /* write it to the imap server */
1314        ctx = imap_open_store( &server );
1315        if (!ctx) {
1316                fprintf( stderr,"failed to open store\n");
1317                return 1;
1318        }
1319
1320        fprintf( stderr, "sending %d message%s\n", total, (total!=1)?"s":"" );
1321        ctx->name = imap_folder;
1322        while (1) {
1323                unsigned percent = n * 100 / total;
1324                fprintf( stderr, "%4u%% (%d/%d) done\r", percent, n, total );
1325                if (!split_msg( &all_msgs, &msg, &ofs ))
1326                        break;
1327                r = imap_store_msg( ctx, &msg, &uid );
1328                if (r != DRV_OK) break;
1329                n++;
1330        }
1331        fprintf( stderr,"\n" );
1332
1333        imap_close_store( ctx );
1334
1335        return 0;
1336}