Code

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