git-commit.sh: convert run_status to a C builtin
[git/peff.git] / imap-send.c
blob362e4743740435dc0e5b08933c0e05c53b7b62af
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 #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>
34 typedef 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;
43 typedef struct string_list {
44 struct string_list *next;
45 char string[1];
46 } string_list_t;
48 typedef 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;
59 typedef struct group_conf {
60 struct group_conf *next;
61 char *name;
62 string_list_t *channels;
63 } group_conf_t;
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 */
70 typedef 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;
78 typedef struct store {
79 store_conf_t *conf; /* foreign */
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;
92 typedef struct {
93 char *data;
94 int len;
95 unsigned char flags;
96 unsigned int crlf:1;
97 } msg_data_t;
99 #define DRV_OK 0
100 #define DRV_MSG_BAD -1
101 #define DRV_BOX_BAD -2
102 #define DRV_STORE_BAD -3
104 static int Verbose, Quiet;
106 static void info( const char *, ... );
107 static void warn( const char *, ... );
109 static char *next_arg( char ** );
111 static void free_generic_messages( message_t * );
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 unsigned use_namespace:1;
132 } imap_store_conf_t;
134 #define NIL (void*)0x1
135 #define LIST (void*)0x2
137 typedef struct _list {
138 struct _list *next, *child;
139 char *val;
140 int len;
141 } list_t;
143 typedef struct {
144 int fd;
145 } Socket_t;
147 typedef struct {
148 Socket_t sock;
149 int bytes;
150 int offset;
151 char buf[1024];
152 } buffer_t;
154 struct imap_cmd;
156 typedef 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;
166 typedef 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;
174 struct 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;
184 struct imap_cmd {
185 struct imap_cmd *next;
186 struct imap_cmd_cb cb;
187 char *cmd;
188 int tag;
191 #define CAP(cap) (imap->caps & (1 << (cap)))
193 enum CAPABILITY {
194 NOLOGIN = 0,
195 UIDPLUS,
196 LITERALPLUS,
197 NAMESPACE,
200 static const char *cap_list[] = {
201 "LOGINDISABLED",
202 "UIDPLUS",
203 "LITERAL+",
204 "NAMESPACE",
207 #define RESP_OK 0
208 #define RESP_NO 1
209 #define RESP_BAD 2
211 static int get_cmd_result( imap_store_t *ctx, struct imap_cmd *tcmd );
214 static const char *Flags[] = {
215 "Draft",
216 "Flagged",
217 "Answered",
218 "Seen",
219 "Deleted",
222 static void
223 socket_perror( const char *func, Socket_t *sock, int ret )
225 if (ret < 0)
226 perror( func );
227 else
228 fprintf( stderr, "%s: unexpected EOF\n", func );
231 static int
232 socket_read( Socket_t *sock, char *buf, int len )
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;
240 return n;
243 static int
244 socket_write( Socket_t *sock, const char *buf, int len )
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;
252 return n;
255 /* simple line buffering */
256 static int
257 buffer_gets( buffer_t * b, char **s )
259 int n;
260 int start = b->offset;
262 *s = b->buf + start;
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;
271 assert( start <= b->bytes );
272 n = b->bytes - start;
274 if (n)
275 memcpy( b->buf, b->buf + start, n );
276 b->offset -= start;
277 b->bytes = n;
278 start = 0;
281 n = socket_read( &b->sock, b->buf + b->bytes,
282 sizeof(b->buf) - b->bytes );
284 if (n <= 0)
285 return -1;
287 b->bytes += n;
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;
301 b->offset++;
303 /* not reached */
306 static void
307 info( const char *msg, ... )
309 va_list va;
311 if (!Quiet) {
312 va_start( va, msg );
313 vprintf( msg, va );
314 va_end( va );
315 fflush( stdout );
319 static void
320 warn( const char *msg, ... )
322 va_list va;
324 if (Quiet < 2) {
325 va_start( va, msg );
326 vfprintf( stderr, msg, va );
327 va_end( va );
331 static char *
332 next_arg( char **s )
334 char *ret;
336 if (!s || !*s)
337 return NULL;
338 while (isspace( (unsigned char) **s ))
339 (*s)++;
340 if (!**s) {
341 *s = NULL;
342 return NULL;
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)++;
353 if (*s) {
354 if (**s)
355 *(*s)++ = 0;
356 if (!**s)
357 *s = NULL;
359 return ret;
362 static void
363 free_generic_messages( message_t *msgs )
365 message_t *tmsg;
367 for (; msgs; msgs = tmsg) {
368 tmsg = msgs->next;
369 free( msgs );
373 static int
374 nfsnprintf( char *buf, int blen, const char *fmt, ... )
376 int ret;
377 va_list va;
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;
386 static struct {
387 unsigned char i, j, s[256];
388 } rs;
390 static void
391 arc4_init( void )
393 int i, fd;
394 unsigned char j, si, dat[128];
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 );
400 if (read( fd, dat, 128 ) != 128) {
401 fprintf( stderr, "Fatal: cannot read random number source.\n" );
402 exit( 3 );
404 close( fd );
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;
414 rs.i = rs.j = 0;
416 for (i = 0; i < 256; i++)
417 arc4_getbyte();
420 static unsigned char
421 arc4_getbyte( void )
423 unsigned char si, sj;
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];
434 static struct imap_cmd *
435 v_issue_imap_cmd( imap_store_t *ctx, struct imap_cmd_cb *cb,
436 const char *fmt, va_list ap )
438 imap_t *imap = ctx->imap;
439 struct imap_cmd *cmd;
440 int n, bufl;
441 char buf[1024];
443 cmd = xmalloc( sizeof(struct imap_cmd) );
444 nfvasprintf( &cmd->cmd, fmt, ap );
445 cmd->tag = ++imap->nexttag;
447 if (cb)
448 cmd->cb = *cb;
449 else
450 memset( &cmd->cb, 0, sizeof(cmd->cb) );
452 while (imap->literal_pending)
453 get_cmd_result( ctx, NULL );
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 );
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;
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)
480 free( cmd->cmd );
481 free( cmd );
482 return NULL;
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;
496 static struct imap_cmd *
497 issue_imap_cmd( imap_store_t *ctx, struct imap_cmd_cb *cb, const char *fmt, ... )
499 struct imap_cmd *ret;
500 va_list ap;
502 va_start( ap, fmt );
503 ret = v_issue_imap_cmd( ctx, cb, fmt, ap );
504 va_end( ap );
505 return ret;
508 static int
509 imap_exec( imap_store_t *ctx, struct imap_cmd_cb *cb, const char *fmt, ... )
511 va_list ap;
512 struct imap_cmd *cmdp;
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;
520 return get_cmd_result( ctx, cmdp );
523 static int
524 imap_exec_m( imap_store_t *ctx, struct imap_cmd_cb *cb, const char *fmt, ... )
526 va_list ap;
527 struct imap_cmd *cmdp;
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;
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;
542 static int
543 is_atom( list_t *list )
545 return list && list->val && list->val != NIL && list->val != LIST;
548 static int
549 is_list( list_t *list )
551 return list && list->val == LIST;
554 static void
555 free_list( list_t *list )
557 list_t *tmp;
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 );
569 static int
570 parse_imap_list_l( imap_t *imap, char **sp, list_t **curp, int level )
572 list_t *cur;
573 char *s = *sp, *p;
574 int n, bytes;
576 for (;;) {
577 while (isspace( (unsigned char)*s ))
578 s++;
579 if (level && *s == ')') {
580 s++;
581 break;
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;
598 s = cur->val = xmalloc( cur->len );
600 /* dump whats left over in the input buffer */
601 n = imap->buf.bytes - imap->buf.offset;
603 if (n > bytes)
604 /* the entire message fit in the buffer */
605 n = bytes;
607 memcpy( s, imap->buf.buf + imap->buf.offset, n );
608 s += n;
609 bytes -= n;
611 /* mark that we used part of the buffer */
612 imap->buf.offset += n;
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;
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;
652 if (!level)
653 break;
654 if (!*s)
655 goto bail;
657 *sp = s;
658 *curp = NULL;
659 return 0;
661 bail:
662 *curp = NULL;
663 return -1;
666 static list_t *
667 parse_imap_list( imap_t *imap, char **sp )
669 list_t *head;
671 if (!parse_imap_list_l( imap, sp, &head, 0 ))
672 return head;
673 free_list( head );
674 return NULL;
677 static list_t *
678 parse_list( char **sp )
680 return parse_imap_list( NULL, sp );
683 static void
684 parse_capability( imap_t *imap, char *cmd )
686 char *arg;
687 unsigned i;
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;
697 static int
698 parse_response_code( imap_store_t *ctx, struct imap_cmd_cb *cb, char *s )
700 imap_t *imap = ctx->imap;
701 char *arg, *p;
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;
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;
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;
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
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 )))
734 fprintf( stderr, "IMAP error: malformed APPENDUID status\n" );
735 return RESP_BAD;
738 return RESP_OK;
741 static int
742 get_cmd_result( imap_store_t *ctx, struct imap_cmd *tcmd )
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;
749 for (;;) {
750 if (buffer_gets( &imap->buf, &cmd ))
751 return RESP_BAD;
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;
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;
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;
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;
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;
838 free( cmdp->cmd );
839 free( cmdp );
840 if (!tcmd)
841 return 0; /* ignored */
842 if (cmdp == tcmd)
843 tcmd = ncmdp;
844 continue;
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 : "");
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;
867 /* not reached */
870 static void
871 imap_close_server( imap_store_t *ictx )
873 imap_t *imap = ictx->imap;
875 if (imap->buf.sock.fd != -1) {
876 imap_exec( ictx, NULL, "LOGOUT" );
877 close( imap->buf.sock.fd );
879 free_list( imap->ns_personal );
880 free_list( imap->ns_other );
881 free_list( imap->ns_shared );
882 free( imap );
885 static void
886 imap_close_store( store_t *ctx )
888 imap_close_server( (imap_store_t *)ctx );
889 free_generic_messages( ctx->msgs );
890 free( ctx );
893 static store_t *
894 imap_open_store( imap_server_conf_t *srvc )
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;
904 ctx = xcalloc( sizeof(*ctx), 1 );
906 ctx->imap = imap = xcalloc( sizeof(*imap), 1 );
907 imap->buf.sock.fd = -1;
908 imap->in_progress_append = &imap->in_progress;
910 /* open connection to IMAP server */
912 if (srvc->tunnel) {
913 info( "Starting tunnel '%s'... ", srvc->tunnel );
915 if (socketpair( PF_UNIX, SOCK_STREAM, 0, a )) {
916 perror( "socketpair" );
917 exit( 1 );
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 );
932 close (a[0]);
934 imap->buf.sock.fd = a[1];
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;
942 info( "Resolving %s... ", srvc->host );
943 he = gethostbyname( srvc->host );
944 if (!he) {
945 perror( "gethostbyname" );
946 goto bail;
948 info( "ok\n" );
950 addr.sin_addr.s_addr = *((int *) he->h_addr_list[0]);
952 s = socket( PF_INET, SOCK_STREAM, 0 );
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;
960 info( "ok\n" );
962 imap->buf.sock.fd = s;
966 /* read the greeting string */
967 if (buffer_gets( &imap->buf, &rsp )) {
968 fprintf( stderr, "IMAP error: no greeting response\n" );
969 goto bail;
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;
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;
983 parse_response_code( ctx, NULL, rsp );
984 if (!imap->caps && imap_exec( ctx, NULL, "CAPABILITY" ) != RESP_OK)
985 goto bail;
987 if (!preauth) {
989 info ("Logging in...\n");
990 if (!srvc->user) {
991 fprintf( stderr, "Skipping server %s, no user\n", srvc->host );
992 goto bail;
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 );
1002 if (!*arg) {
1003 fprintf( stderr, "Skipping account %s@%s, no password\n", srvc->user, srvc->host );
1004 goto bail;
1007 * getpass() returns a pointer to a static buffer. make a copy
1008 * for long term storage.
1010 srvc->pass = xstrdup( arg );
1012 if (CAP(NOLOGIN)) {
1013 fprintf( stderr, "Skipping account %s@%s, server forbids LOGIN\n", srvc->user, srvc->host );
1014 goto bail;
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;
1021 } /* !preauth */
1023 ctx->prefix = "";
1024 ctx->trashnc = 1;
1025 return (store_t *)ctx;
1027 bail:
1028 imap_close_store( &ctx->gen );
1029 return NULL;
1032 static int
1033 imap_make_flags( int flags, char *buf )
1035 const char *s;
1036 unsigned i, d;
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;
1045 buf[0] = '(';
1046 buf[d++] = ')';
1047 return d;
1050 #define TUIDL 8
1052 static int
1053 imap_store_msg( store_t *gctx, msg_data_t *data, int *uid )
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];
1064 memset( &cb, 0, sizeof(cb) );
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;
1080 if (!memcmp( fmap + start, "X-TUID: ", 8 )) {
1081 extra -= (ebreak = i) - (sbreak = start) + nocr;
1082 goto mktid;
1084 goto nloop;
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;
1094 if (nocr)
1095 for (; i < len; i++)
1096 if (fmap[i] == '\n')
1097 extra++;
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;
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;
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 );
1132 free( fmap );
1134 d = 0;
1135 if (data->flags) {
1136 d = imap_make_flags( data->flags, flagstr );
1137 flagstr[d++] = ' ';
1139 flagstr[d] = 0;
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;
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++;
1162 return DRV_OK;
1165 #define CHUNKSIZE 0x1000
1167 static int
1168 read_message( FILE *f, msg_data_t *msg )
1170 int len, r;
1172 memset( msg, 0, sizeof *msg );
1173 len = CHUNKSIZE;
1174 msg->data = xmalloc( len+1 );
1175 msg->data[0] = 0;
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;
1186 r = fread( &msg->data[msg->len], 1, len - msg->len, f );
1187 if (r <= 0)
1188 break;
1189 msg->len += r;
1191 msg->data[msg->len] = 0;
1192 return msg->len;
1195 static int
1196 count_messages( msg_data_t *msg )
1198 int count = 0;
1199 char *p = msg->data;
1201 while (1) {
1202 if (!strncmp( "From ", p, 5 )) {
1203 count++;
1204 p += 5;
1206 p = strstr( p+5, "\nFrom ");
1207 if (!p)
1208 break;
1209 p++;
1211 return count;
1214 static int
1215 split_msg( msg_data_t *all_msgs, msg_data_t *msg, int *ofs )
1217 char *p, *data;
1219 memset( msg, 0, sizeof *msg );
1220 if (*ofs >= all_msgs->len)
1221 return 0;
1223 data = &all_msgs->data[ *ofs ];
1224 msg->len = all_msgs->len - *ofs;
1226 if (msg->len < 5 || strncmp( data, "From ", 5 ))
1227 return 0;
1229 p = strstr( data, "\nFrom " );
1230 if (p)
1231 msg->len = &p[1] - data;
1233 msg->data = xmalloc( msg->len + 1 );
1234 if (!msg->data)
1235 return 0;
1237 memcpy( msg->data, data, msg->len );
1238 msg->data[ msg->len ] = 0;
1240 *ofs += msg->len;
1241 return 1;
1244 static imap_server_conf_t server =
1246 NULL, /* name */
1247 NULL, /* tunnel */
1248 NULL, /* host */
1249 0, /* port */
1250 NULL, /* user */
1251 NULL, /* pass */
1254 static char *imap_folder;
1256 static int
1257 git_imap_config(const char *key, const char *val)
1259 char imap_key[] = "imap.";
1261 if (strncmp( key, imap_key, sizeof imap_key - 1 ))
1262 return 0;
1263 key += sizeof imap_key - 1;
1265 if (!strcmp( "folder", key )) {
1266 imap_folder = xstrdup( val );
1267 } else if (!strcmp( "host", key )) {
1269 if (!strncmp( "imap:", val, 5 ))
1270 val += 5;
1271 if (!server.port)
1272 server.port = 143;
1274 if (!strncmp( "//", val, 2 ))
1275 val += 2;
1276 server.host = xstrdup( val );
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;
1290 main(int argc, char **argv)
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;
1299 /* init the random number generator */
1300 arc4_init();
1302 git_config( git_imap_config );
1304 if (!imap_folder) {
1305 fprintf( stderr, "no imap store specified\n" );
1306 return 1;
1309 /* read the messages */
1310 if (!read_message( stdin, &all_msgs )) {
1311 fprintf(stderr,"nothing to send\n");
1312 return 1;
1315 total = count_messages( &all_msgs );
1316 if (!total) {
1317 fprintf(stderr,"no messages to send\n");
1318 return 1;
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;
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++;
1339 fprintf( stderr,"\n" );
1341 imap_close_store( ctx );
1343 return 0;