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