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