]> git.ipfire.org Git - thirdparty/git.git/blame - imap-send.c
Fix the expansion pattern of the pseudo-static path buffer.
[thirdparty/git.git] / imap-send.c
CommitLineData
f2561fda
MM
1/*
2 * git-imap-send - drops patches into an imap Drafts folder
3 * derived from isync/mbsync - mailbox synchronizer
4 *
5 * Copyright (C) 2000-2002 Michael R. Elkins <me@mutt.org>
6 * Copyright (C) 2002-2004 Oswald Buddenhagen <ossi@users.sf.net>
7 * Copyright (C) 2004 Theodore Y. Ts'o <tytso@mit.edu>
8 * Copyright (C) 2006 Mike McCormack
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, write to the Free Software
22 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 */
24
25#include "cache.h"
26
f2561fda
MM
27typedef 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;
35
36typedef struct string_list {
37 struct string_list *next;
38 char string[1];
39} string_list_t;
40
41typedef 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;
51
52typedef struct group_conf {
53 struct group_conf *next;
54 char *name;
55 string_list_t *channels;
56} group_conf_t;
57
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 */
62
63typedef 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;
70
71typedef struct store {
72 store_conf_t *conf; /* foreign */
73
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;
84
85typedef struct {
86 char *data;
87 int len;
88 unsigned char flags;
2bda77e0 89 unsigned int crlf:1;
f2561fda
MM
90} msg_data_t;
91
92#define DRV_OK 0
93#define DRV_MSG_BAD -1
94#define DRV_BOX_BAD -2
95#define DRV_STORE_BAD -3
96
97static int Verbose, Quiet;
98
51dcaa96
SP
99static void imap_info( const char *, ... );
100static void imap_warn( const char *, ... );
f2561fda
MM
101
102static char *next_arg( char ** );
103
104static void free_generic_messages( message_t * );
105
f2561fda
MM
106static int nfsnprintf( char *buf, int blen, const char *fmt, ... );
107
108
109static void arc4_init( void );
110static unsigned char arc4_getbyte( void );
111
112typedef 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;
120
121typedef 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;
126
127#define NIL (void*)0x1
128#define LIST (void*)0x2
129
130typedef struct _list {
131 struct _list *next, *child;
132 char *val;
133 int len;
134} list_t;
135
136typedef struct {
137 int fd;
138} Socket_t;
139
140typedef struct {
141 Socket_t sock;
142 int bytes;
143 int offset;
144 char buf[1024];
145} buffer_t;
146
147struct imap_cmd;
148
149typedef 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;
158
159typedef 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;
166
167struct 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;
175};
176
177struct imap_cmd {
178 struct imap_cmd *next;
179 struct imap_cmd_cb cb;
180 char *cmd;
181 int tag;
182};
183
184#define CAP(cap) (imap->caps & (1 << (cap)))
185
186enum CAPABILITY {
187 NOLOGIN = 0,
188 UIDPLUS,
189 LITERALPLUS,
190 NAMESPACE,
191};
192
193static const char *cap_list[] = {
194 "LOGINDISABLED",
195 "UIDPLUS",
196 "LITERAL+",
197 "NAMESPACE",
198};
199
200#define RESP_OK 0
201#define RESP_NO 1
202#define RESP_BAD 2
203
204static int get_cmd_result( imap_store_t *ctx, struct imap_cmd *tcmd );
205
206
207static const char *Flags[] = {
208 "Draft",
209 "Flagged",
210 "Answered",
211 "Seen",
212 "Deleted",
213};
214
215static void
216socket_perror( const char *func, Socket_t *sock, int ret )
217{
218 if (ret < 0)
219 perror( func );
220 else
221 fprintf( stderr, "%s: unexpected EOF\n", func );
222}
223
224static int
225socket_read( Socket_t *sock, char *buf, int len )
226{
8a912bcb 227 ssize_t n = xread( sock->fd, buf, len );
f2561fda
MM
228 if (n <= 0) {
229 socket_perror( "read", sock, n );
230 close( sock->fd );
231 sock->fd = -1;
232 }
233 return n;
234}
235
236static int
554fe20d 237socket_write( Socket_t *sock, const char *buf, int len )
f2561fda 238{
93822c22 239 int n = write_in_full( sock->fd, buf, len );
f2561fda
MM
240 if (n != len) {
241 socket_perror( "write", sock, n );
242 close( sock->fd );
243 sock->fd = -1;
244 }
245 return n;
246}
247
248/* simple line buffering */
249static int
250buffer_gets( buffer_t * b, char **s )
251{
252 int n;
253 int start = b->offset;
254
255 *s = b->buf + start;
256
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;
263
264 assert( start <= b->bytes );
265 n = b->bytes - start;
266
267 if (n)
173a9cbe 268 memmove(b->buf, b->buf + start, n);
f2561fda
MM
269 b->offset -= start;
270 b->bytes = n;
271 start = 0;
272 }
273
274 n = socket_read( &b->sock, b->buf + b->bytes,
275 sizeof(b->buf) - b->bytes );
276
277 if (n <= 0)
278 return -1;
279
280 b->bytes += n;
281 }
282
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;
291 }
292 }
293
294 b->offset++;
295 }
296 /* not reached */
297}
298
299static void
51dcaa96 300imap_info( const char *msg, ... )
f2561fda
MM
301{
302 va_list va;
303
304 if (!Quiet) {
305 va_start( va, msg );
306 vprintf( msg, va );
307 va_end( va );
308 fflush( stdout );
309 }
310}
311
312static void
51dcaa96 313imap_warn( const char *msg, ... )
f2561fda
MM
314{
315 va_list va;
316
317 if (Quiet < 2) {
318 va_start( va, msg );
319 vfprintf( stderr, msg, va );
320 va_end( va );
321 }
322}
323
324static char *
325next_arg( char **s )
326{
327 char *ret;
328
329 if (!s || !*s)
5142db69 330 return NULL;
f2561fda
MM
331 while (isspace( (unsigned char) **s ))
332 (*s)++;
333 if (!**s) {
5142db69
RS
334 *s = NULL;
335 return NULL;
f2561fda
MM
336 }
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)++;
345 }
346 if (*s) {
347 if (**s)
348 *(*s)++ = 0;
349 if (!**s)
5142db69 350 *s = NULL;
f2561fda
MM
351 }
352 return ret;
353}
354
355static void
356free_generic_messages( message_t *msgs )
357{
358 message_t *tmsg;
359
360 for (; msgs; msgs = tmsg) {
361 tmsg = msgs->next;
362 free( msgs );
363 }
364}
365
f2561fda
MM
366static int
367nfsnprintf( char *buf, int blen, const char *fmt, ... )
368{
369 int ret;
370 va_list va;
371
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;
377}
378
f2561fda
MM
379static struct {
380 unsigned char i, j, s[256];
381} rs;
382
383static void
384arc4_init( void )
385{
386 int i, fd;
387 unsigned char j, si, dat[128];
388
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 );
392 }
93d26e4c 393 if (read_in_full( fd, dat, 128 ) != 128) {
f2561fda
MM
394 fprintf( stderr, "Fatal: cannot read random number source.\n" );
395 exit( 3 );
396 }
397 close( fd );
398
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;
406 }
407 rs.i = rs.j = 0;
408
409 for (i = 0; i < 256; i++)
410 arc4_getbyte();
411}
412
413static unsigned char
414arc4_getbyte( void )
415{
416 unsigned char si, sj;
417
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];
425}
426
427static struct imap_cmd *
428v_issue_imap_cmd( imap_store_t *ctx, struct imap_cmd_cb *cb,
429 const char *fmt, va_list ap )
430{
431 imap_t *imap = ctx->imap;
432 struct imap_cmd *cmd;
433 int n, bufl;
434 char buf[1024];
435
436 cmd = xmalloc( sizeof(struct imap_cmd) );
437 nfvasprintf( &cmd->cmd, fmt, ap );
438 cmd->tag = ++imap->nexttag;
439
440 if (cb)
441 cmd->cb = *cb;
442 else
443 memset( &cmd->cb, 0, sizeof(cmd->cb) );
444
445 while (imap->literal_pending)
5142db69 446 get_cmd_result( ctx, NULL );
f2561fda
MM
447
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 );
458 }
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;
465 }
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)
472 {
473 free( cmd->cmd );
474 free( cmd );
475 return NULL;
476 }
5142db69 477 cmd->cb.data = NULL;
f2561fda
MM
478 } else
479 imap->literal_pending = 1;
480 } else if (cmd->cb.cont)
481 imap->literal_pending = 1;
5142db69 482 cmd->next = NULL;
f2561fda
MM
483 *imap->in_progress_append = cmd;
484 imap->in_progress_append = &cmd->next;
485 imap->num_in_progress++;
486 return cmd;
487}
488
489static struct imap_cmd *
490issue_imap_cmd( imap_store_t *ctx, struct imap_cmd_cb *cb, const char *fmt, ... )
491{
492 struct imap_cmd *ret;
493 va_list ap;
494
495 va_start( ap, fmt );
496 ret = v_issue_imap_cmd( ctx, cb, fmt, ap );
497 va_end( ap );
498 return ret;
499}
500
501static int
502imap_exec( imap_store_t *ctx, struct imap_cmd_cb *cb, const char *fmt, ... )
503{
504 va_list ap;
505 struct imap_cmd *cmdp;
506
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;
512
513 return get_cmd_result( ctx, cmdp );
514}
515
516static int
517imap_exec_m( imap_store_t *ctx, struct imap_cmd_cb *cb, const char *fmt, ... )
518{
519 va_list ap;
520 struct imap_cmd *cmdp;
521
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;
527
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;
532 }
533}
534
535static int
536is_atom( list_t *list )
537{
538 return list && list->val && list->val != NIL && list->val != LIST;
539}
540
541static int
542is_list( list_t *list )
543{
544 return list && list->val == LIST;
545}
546
547static void
548free_list( list_t *list )
549{
550 list_t *tmp;
551
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 );
559 }
560}
561
562static int
563parse_imap_list_l( imap_t *imap, char **sp, list_t **curp, int level )
564{
565 list_t *cur;
566 char *s = *sp, *p;
567 int n, bytes;
568
569 for (;;) {
570 while (isspace( (unsigned char)*s ))
571 s++;
572 if (level && *s == ')') {
573 s++;
574 break;
575 }
576 *curp = cur = xmalloc( sizeof(*cur) );
577 curp = &cur->next;
5142db69 578 cur->val = NULL; /* for clean bail */
f2561fda
MM
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;
590
591 s = cur->val = xmalloc( cur->len );
592
593 /* dump whats left over in the input buffer */
594 n = imap->buf.bytes - imap->buf.offset;
595
596 if (n > bytes)
597 /* the entire message fit in the buffer */
598 n = bytes;
599
600 memcpy( s, imap->buf.buf + imap->buf.offset, n );
601 s += n;
602 bytes -= n;
603
604 /* mark that we used part of the buffer */
605 imap->buf.offset += n;
606
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;
613 }
614
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++;
182af834 626 cur->val = xmemdupz(p, cur->len);
f2561fda
MM
627 } else {
628 /* atom */
629 p = s;
630 for (; *s && !isspace( (unsigned char)*s ); s++)
631 if (level && *s == ')')
632 break;
633 cur->len = s - p;
182af834 634 if (cur->len == 3 && !memcmp ("NIL", p, 3)) {
f2561fda 635 cur->val = NIL;
182af834
PH
636 } else {
637 cur->val = xmemdupz(p, cur->len);
f2561fda
MM
638 }
639 }
640
641 if (!level)
642 break;
643 if (!*s)
644 goto bail;
645 }
646 *sp = s;
5142db69 647 *curp = NULL;
f2561fda
MM
648 return 0;
649
650 bail:
5142db69 651 *curp = NULL;
f2561fda
MM
652 return -1;
653}
654
655static list_t *
656parse_imap_list( imap_t *imap, char **sp )
657{
658 list_t *head;
659
660 if (!parse_imap_list_l( imap, sp, &head, 0 ))
661 return head;
662 free_list( head );
663 return NULL;
664}
665
666static list_t *
667parse_list( char **sp )
668{
5142db69 669 return parse_imap_list( NULL, sp );
f2561fda
MM
670}
671
672static void
673parse_capability( imap_t *imap, char *cmd )
674{
675 char *arg;
676 unsigned i;
677
678 imap->caps = 0x80000000;
679 while ((arg = next_arg( &cmd )))
680 for (i = 0; i < ARRAY_SIZE(cap_list); i++)
681 if (!strcmp( cap_list[i], arg ))
682 imap->caps |= 1 << i;
683 imap->rcaps = imap->caps;
684}
685
686static int
687parse_response_code( imap_store_t *ctx, struct imap_cmd_cb *cb, char *s )
688{
689 imap_t *imap = ctx->imap;
690 char *arg, *p;
691
692 if (*s != '[')
693 return RESP_OK; /* no response code */
694 s++;
695 if (!(p = strchr( s, ']' ))) {
696 fprintf( stderr, "IMAP error: malformed response code\n" );
697 return RESP_BAD;
698 }
699 *p++ = 0;
700 arg = next_arg( &s );
701 if (!strcmp( "UIDVALIDITY", arg )) {
702 if (!(arg = next_arg( &s )) || !(ctx->gen.uidvalidity = atoi( arg ))) {
703 fprintf( stderr, "IMAP error: malformed UIDVALIDITY status\n" );
704 return RESP_BAD;
705 }
706 } else if (!strcmp( "UIDNEXT", arg )) {
707 if (!(arg = next_arg( &s )) || !(imap->uidnext = atoi( arg ))) {
708 fprintf( stderr, "IMAP error: malformed NEXTUID status\n" );
709 return RESP_BAD;
710 }
711 } else if (!strcmp( "CAPABILITY", arg )) {
712 parse_capability( imap, s );
713 } else if (!strcmp( "ALERT", arg )) {
714 /* RFC2060 says that these messages MUST be displayed
715 * to the user
716 */
717 for (; isspace( (unsigned char)*p ); p++);
718 fprintf( stderr, "*** IMAP ALERT *** %s\n", p );
719 } else if (cb && cb->ctx && !strcmp( "APPENDUID", arg )) {
720 if (!(arg = next_arg( &s )) || !(ctx->gen.uidvalidity = atoi( arg )) ||
721 !(arg = next_arg( &s )) || !(*(int *)cb->ctx = atoi( arg )))
722 {
723 fprintf( stderr, "IMAP error: malformed APPENDUID status\n" );
724 return RESP_BAD;
725 }
726 }
727 return RESP_OK;
728}
729
730static int
731get_cmd_result( imap_store_t *ctx, struct imap_cmd *tcmd )
732{
733 imap_t *imap = ctx->imap;
734 struct imap_cmd *cmdp, **pcmdp, *ncmdp;
735 char *cmd, *arg, *arg1, *p;
736 int n, resp, resp2, tag;
737
738 for (;;) {
739 if (buffer_gets( &imap->buf, &cmd ))
740 return RESP_BAD;
741
742 arg = next_arg( &cmd );
743 if (*arg == '*') {
744 arg = next_arg( &cmd );
745 if (!arg) {
746 fprintf( stderr, "IMAP error: unable to parse untagged response\n" );
747 return RESP_BAD;
748 }
749
750 if (!strcmp( "NAMESPACE", arg )) {
751 imap->ns_personal = parse_list( &cmd );
752 imap->ns_other = parse_list( &cmd );
753 imap->ns_shared = parse_list( &cmd );
754 } else if (!strcmp( "OK", arg ) || !strcmp( "BAD", arg ) ||
755 !strcmp( "NO", arg ) || !strcmp( "BYE", arg )) {
5142db69 756 if ((resp = parse_response_code( ctx, NULL, cmd )) != RESP_OK)
f2561fda
MM
757 return resp;
758 } else if (!strcmp( "CAPABILITY", arg ))
759 parse_capability( imap, cmd );
760 else if ((arg1 = next_arg( &cmd ))) {
761 if (!strcmp( "EXISTS", arg1 ))
762 ctx->gen.count = atoi( arg );
763 else if (!strcmp( "RECENT", arg1 ))
764 ctx->gen.recent = atoi( arg );
765 } else {
766 fprintf( stderr, "IMAP error: unable to parse untagged response\n" );
767 return RESP_BAD;
768 }
769 } else if (!imap->in_progress) {
770 fprintf( stderr, "IMAP error: unexpected reply: %s %s\n", arg, cmd ? cmd : "" );
771 return RESP_BAD;
772 } else if (*arg == '+') {
773 /* This can happen only with the last command underway, as
774 it enforces a round-trip. */
775 cmdp = (struct imap_cmd *)((char *)imap->in_progress_append -
776 offsetof(struct imap_cmd, next));
777 if (cmdp->cb.data) {
778 n = socket_write( &imap->buf.sock, cmdp->cb.data, cmdp->cb.dlen );
779 free( cmdp->cb.data );
5142db69 780 cmdp->cb.data = NULL;
f2561fda
MM
781 if (n != (int)cmdp->cb.dlen)
782 return RESP_BAD;
783 } else if (cmdp->cb.cont) {
784 if (cmdp->cb.cont( ctx, cmdp, cmd ))
785 return RESP_BAD;
786 } else {
787 fprintf( stderr, "IMAP error: unexpected command continuation request\n" );
788 return RESP_BAD;
789 }
790 if (socket_write( &imap->buf.sock, "\r\n", 2 ) != 2)
791 return RESP_BAD;
792 if (!cmdp->cb.cont)
793 imap->literal_pending = 0;
794 if (!tcmd)
795 return DRV_OK;
796 } else {
797 tag = atoi( arg );
798 for (pcmdp = &imap->in_progress; (cmdp = *pcmdp); pcmdp = &cmdp->next)
799 if (cmdp->tag == tag)
800 goto gottag;
801 fprintf( stderr, "IMAP error: unexpected tag %s\n", arg );
802 return RESP_BAD;
803 gottag:
804 if (!(*pcmdp = cmdp->next))
805 imap->in_progress_append = pcmdp;
806 imap->num_in_progress--;
807 if (cmdp->cb.cont || cmdp->cb.data)
808 imap->literal_pending = 0;
809 arg = next_arg( &cmd );
810 if (!strcmp( "OK", arg ))
811 resp = DRV_OK;
812 else {
813 if (!strcmp( "NO", arg )) {
814 if (cmdp->cb.create && cmd && (cmdp->cb.trycreate || !memcmp( cmd, "[TRYCREATE]", 11 ))) { /* SELECT, APPEND or UID COPY */
815 p = strchr( cmdp->cmd, '"' );
5142db69 816 if (!issue_imap_cmd( ctx, NULL, "CREATE \"%.*s\"", strchr( p + 1, '"' ) - p + 1, p )) {
f2561fda
MM
817 resp = RESP_BAD;
818 goto normal;
819 }
820 /* not waiting here violates the spec, but a server that does not
821 grok this nonetheless violates it too. */
822 cmdp->cb.create = 0;
823 if (!(ncmdp = issue_imap_cmd( ctx, &cmdp->cb, "%s", cmdp->cmd ))) {
824 resp = RESP_BAD;
825 goto normal;
826 }
827 free( cmdp->cmd );
828 free( cmdp );
829 if (!tcmd)
830 return 0; /* ignored */
831 if (cmdp == tcmd)
832 tcmd = ncmdp;
833 continue;
834 }
835 resp = RESP_NO;
836 } else /*if (!strcmp( "BAD", arg ))*/
837 resp = RESP_BAD;
838 fprintf( stderr, "IMAP command '%s' returned response (%s) - %s\n",
839 memcmp (cmdp->cmd, "LOGIN", 5) ?
840 cmdp->cmd : "LOGIN <user> <pass>",
841 arg, cmd ? cmd : "");
842 }
843 if ((resp2 = parse_response_code( ctx, &cmdp->cb, cmd )) > resp)
844 resp = resp2;
845 normal:
846 if (cmdp->cb.done)
847 cmdp->cb.done( ctx, cmdp, resp );
848 if (cmdp->cb.data)
849 free( cmdp->cb.data );
850 free( cmdp->cmd );
851 free( cmdp );
852 if (!tcmd || tcmd == cmdp)
853 return resp;
854 }
855 }
856 /* not reached */
857}
858
859static void
860imap_close_server( imap_store_t *ictx )
861{
862 imap_t *imap = ictx->imap;
863
864 if (imap->buf.sock.fd != -1) {
5142db69 865 imap_exec( ictx, NULL, "LOGOUT" );
f2561fda
MM
866 close( imap->buf.sock.fd );
867 }
868 free_list( imap->ns_personal );
869 free_list( imap->ns_other );
870 free_list( imap->ns_shared );
871 free( imap );
872}
873
874static void
875imap_close_store( store_t *ctx )
876{
877 imap_close_server( (imap_store_t *)ctx );
878 free_generic_messages( ctx->msgs );
879 free( ctx );
880}
881
882static store_t *
883imap_open_store( imap_server_conf_t *srvc )
884{
885 imap_store_t *ctx;
886 imap_t *imap;
887 char *arg, *rsp;
888 struct hostent *he;
889 struct sockaddr_in addr;
890 int s, a[2], preauth;
c9bc159d 891 pid_t pid;
f2561fda
MM
892
893 ctx = xcalloc( sizeof(*ctx), 1 );
894
895 ctx->imap = imap = xcalloc( sizeof(*imap), 1 );
896 imap->buf.sock.fd = -1;
897 imap->in_progress_append = &imap->in_progress;
898
899 /* open connection to IMAP server */
900
901 if (srvc->tunnel) {
51dcaa96 902 imap_info( "Starting tunnel '%s'... ", srvc->tunnel );
f2561fda
MM
903
904 if (socketpair( PF_UNIX, SOCK_STREAM, 0, a )) {
905 perror( "socketpair" );
906 exit( 1 );
907 }
908
c9bc159d
PD
909 pid = fork();
910 if (pid < 0)
911 _exit( 127 );
912 if (!pid) {
f2561fda
MM
913 if (dup2( a[0], 0 ) == -1 || dup2( a[0], 1 ) == -1)
914 _exit( 127 );
915 close( a[0] );
916 close( a[1] );
8e7f9035 917 execl( "/bin/sh", "sh", "-c", srvc->tunnel, NULL );
f2561fda
MM
918 _exit( 127 );
919 }
920
921 close (a[0]);
922
923 imap->buf.sock.fd = a[1];
924
51dcaa96 925 imap_info( "ok\n" );
f2561fda
MM
926 } else {
927 memset( &addr, 0, sizeof(addr) );
928 addr.sin_port = htons( srvc->port );
929 addr.sin_family = AF_INET;
930
51dcaa96 931 imap_info( "Resolving %s... ", srvc->host );
f2561fda
MM
932 he = gethostbyname( srvc->host );
933 if (!he) {
934 perror( "gethostbyname" );
935 goto bail;
936 }
51dcaa96 937 imap_info( "ok\n" );
f2561fda
MM
938
939 addr.sin_addr.s_addr = *((int *) he->h_addr_list[0]);
940
941 s = socket( PF_INET, SOCK_STREAM, 0 );
942
51dcaa96 943 imap_info( "Connecting to %s:%hu... ", inet_ntoa( addr.sin_addr ), ntohs( addr.sin_port ) );
f2561fda
MM
944 if (connect( s, (struct sockaddr *)&addr, sizeof(addr) )) {
945 close( s );
946 perror( "connect" );
947 goto bail;
948 }
51dcaa96 949 imap_info( "ok\n" );
f2561fda
MM
950
951 imap->buf.sock.fd = s;
952
953 }
954
955 /* read the greeting string */
956 if (buffer_gets( &imap->buf, &rsp )) {
957 fprintf( stderr, "IMAP error: no greeting response\n" );
958 goto bail;
959 }
960 arg = next_arg( &rsp );
961 if (!arg || *arg != '*' || (arg = next_arg( &rsp )) == NULL) {
962 fprintf( stderr, "IMAP error: invalid greeting response\n" );
963 goto bail;
964 }
965 preauth = 0;
966 if (!strcmp( "PREAUTH", arg ))
967 preauth = 1;
968 else if (strcmp( "OK", arg ) != 0) {
969 fprintf( stderr, "IMAP error: unknown greeting response\n" );
970 goto bail;
971 }
5142db69
RS
972 parse_response_code( ctx, NULL, rsp );
973 if (!imap->caps && imap_exec( ctx, NULL, "CAPABILITY" ) != RESP_OK)
f2561fda
MM
974 goto bail;
975
976 if (!preauth) {
977
51dcaa96 978 imap_info ("Logging in...\n");
f2561fda
MM
979 if (!srvc->user) {
980 fprintf( stderr, "Skipping server %s, no user\n", srvc->host );
981 goto bail;
982 }
983 if (!srvc->pass) {
984 char prompt[80];
985 sprintf( prompt, "Password (%s@%s): ", srvc->user, srvc->host );
986 arg = getpass( prompt );
987 if (!arg) {
988 perror( "getpass" );
989 exit( 1 );
990 }
991 if (!*arg) {
992 fprintf( stderr, "Skipping account %s@%s, no password\n", srvc->user, srvc->host );
993 goto bail;
994 }
995 /*
996 * getpass() returns a pointer to a static buffer. make a copy
997 * for long term storage.
998 */
9befac47 999 srvc->pass = xstrdup( arg );
f2561fda
MM
1000 }
1001 if (CAP(NOLOGIN)) {
1002 fprintf( stderr, "Skipping account %s@%s, server forbids LOGIN\n", srvc->user, srvc->host );
1003 goto bail;
1004 }
51dcaa96 1005 imap_warn( "*** IMAP Warning *** Password is being sent in the clear\n" );
5142db69 1006 if (imap_exec( ctx, NULL, "LOGIN \"%s\" \"%s\"", srvc->user, srvc->pass ) != RESP_OK) {
f2561fda
MM
1007 fprintf( stderr, "IMAP error: LOGIN failed\n" );
1008 goto bail;
1009 }
1010 } /* !preauth */
1011
1012 ctx->prefix = "";
1013 ctx->trashnc = 1;
1014 return (store_t *)ctx;
1015
1016 bail:
1017 imap_close_store( &ctx->gen );
5142db69 1018 return NULL;
f2561fda
MM
1019}
1020
1021static int
1022imap_make_flags( int flags, char *buf )
1023{
1024 const char *s;
1025 unsigned i, d;
1026
1027 for (i = d = 0; i < ARRAY_SIZE(Flags); i++)
1028 if (flags & (1 << i)) {
1029 buf[d++] = ' ';
1030 buf[d++] = '\\';
1031 for (s = Flags[i]; *s; s++)
1032 buf[d++] = *s;
1033 }
1034 buf[0] = '(';
1035 buf[d++] = ')';
1036 return d;
1037}
1038
1039#define TUIDL 8
1040
1041static int
1042imap_store_msg( store_t *gctx, msg_data_t *data, int *uid )
1043{
1044 imap_store_t *ctx = (imap_store_t *)gctx;
1045 imap_t *imap = ctx->imap;
1046 struct imap_cmd_cb cb;
1047 char *fmap, *buf;
1048 const char *prefix, *box;
1049 int ret, i, j, d, len, extra, nocr;
1050 int start, sbreak = 0, ebreak = 0;
1051 char flagstr[128], tuid[TUIDL * 2 + 1];
1052
1053 memset( &cb, 0, sizeof(cb) );
1054
1055 fmap = data->data;
1056 len = data->len;
1057 nocr = !data->crlf;
1058 extra = 0, i = 0;
1059 if (!CAP(UIDPLUS) && uid) {
1060 nloop:
1061 start = i;
1062 while (i < len)
1063 if (fmap[i++] == '\n') {
1064 extra += nocr;
1065 if (i - 2 + nocr == start) {
1066 sbreak = ebreak = i - 2 + nocr;
1067 goto mktid;
1068 }
1069 if (!memcmp( fmap + start, "X-TUID: ", 8 )) {
1070 extra -= (ebreak = i) - (sbreak = start) + nocr;
1071 goto mktid;
1072 }
1073 goto nloop;
1074 }
1075 /* invalid message */
1076 free( fmap );
1077 return DRV_MSG_BAD;
1078 mktid:
1079 for (j = 0; j < TUIDL; j++)
1080 sprintf( tuid + j * 2, "%02x", arc4_getbyte() );
1081 extra += 8 + TUIDL * 2 + 2;
1082 }
1083 if (nocr)
1084 for (; i < len; i++)
1085 if (fmap[i] == '\n')
1086 extra++;
1087
1088 cb.dlen = len + extra;
1089 buf = cb.data = xmalloc( cb.dlen );
1090 i = 0;
1091 if (!CAP(UIDPLUS) && uid) {
1092 if (nocr) {
1093 for (; i < sbreak; i++)
1094 if (fmap[i] == '\n') {
1095 *buf++ = '\r';
1096 *buf++ = '\n';
1097 } else
1098 *buf++ = fmap[i];
1099 } else {
1100 memcpy( buf, fmap, sbreak );
1101 buf += sbreak;
1102 }
1103 memcpy( buf, "X-TUID: ", 8 );
1104 buf += 8;
1105 memcpy( buf, tuid, TUIDL * 2 );
1106 buf += TUIDL * 2;
1107 *buf++ = '\r';
1108 *buf++ = '\n';
1109 i = ebreak;
1110 }
1111 if (nocr) {
1112 for (; i < len; i++)
1113 if (fmap[i] == '\n') {
1114 *buf++ = '\r';
1115 *buf++ = '\n';
1116 } else
1117 *buf++ = fmap[i];
1118 } else
1119 memcpy( buf, fmap + i, len - i );
1120
1121 free( fmap );
1122
1123 d = 0;
1124 if (data->flags) {
1125 d = imap_make_flags( data->flags, flagstr );
1126 flagstr[d++] = ' ';
1127 }
1128 flagstr[d] = 0;
1129
1130 if (!uid) {
1131 box = gctx->conf->trash;
1132 prefix = ctx->prefix;
1133 cb.create = 1;
1134 if (ctx->trashnc)
1135 imap->caps = imap->rcaps & ~(1 << LITERALPLUS);
1136 } else {
1137 box = gctx->name;
1138 prefix = !strcmp( box, "INBOX" ) ? "" : ctx->prefix;
1139 cb.create = 0;
1140 }
1141 cb.ctx = uid;
1142 ret = imap_exec_m( ctx, &cb, "APPEND \"%s%s\" %s", prefix, box, flagstr );
1143 imap->caps = imap->rcaps;
1144 if (ret != DRV_OK)
1145 return ret;
1146 if (!uid)
1147 ctx->trashnc = 0;
1148 else
1149 gctx->count++;
1150
1151 return DRV_OK;
1152}
1153
1154#define CHUNKSIZE 0x1000
1155
1156static int
1157read_message( FILE *f, msg_data_t *msg )
1158{
635d043f 1159 struct strbuf buf;
f2561fda 1160
635d043f
PH
1161 memset(msg, 0, sizeof(*msg));
1162 strbuf_init(&buf, 0);
1163
1164 do {
1165 if (strbuf_fread(&buf, CHUNKSIZE, f) <= 0)
f2561fda 1166 break;
635d043f
PH
1167 } while (!feof(f));
1168
1169 msg->len = buf.len;
1170 msg->data = strbuf_detach(&buf);
f2561fda
MM
1171 return msg->len;
1172}
1173
1174static int
1175count_messages( msg_data_t *msg )
1176{
1177 int count = 0;
1178 char *p = msg->data;
1179
1180 while (1) {
1968d77d 1181 if (!prefixcmp(p, "From ")) {
f2561fda
MM
1182 count++;
1183 p += 5;
1184 }
1185 p = strstr( p+5, "\nFrom ");
1186 if (!p)
1187 break;
1188 p++;
1189 }
1190 return count;
1191}
1192
1193static int
1194split_msg( msg_data_t *all_msgs, msg_data_t *msg, int *ofs )
1195{
1196 char *p, *data;
1197
1198 memset( msg, 0, sizeof *msg );
1199 if (*ofs >= all_msgs->len)
1200 return 0;
1201
1202 data = &all_msgs->data[ *ofs ];
1203 msg->len = all_msgs->len - *ofs;
1204
1968d77d 1205 if (msg->len < 5 || prefixcmp(data, "From "))
f2561fda
MM
1206 return 0;
1207
e0b08307
MA
1208 p = strchr( data, '\n' );
1209 if (p) {
1210 p = &p[1];
1211 msg->len -= p-data;
1212 *ofs += p-data;
1213 data = p;
1214 }
1215
f2561fda
MM
1216 p = strstr( data, "\nFrom " );
1217 if (p)
1218 msg->len = &p[1] - data;
1219
182af834 1220 msg->data = xmemdupz(data, msg->len);
f2561fda 1221 *ofs += msg->len;
a6080a0a 1222 return 1;
f2561fda
MM
1223}
1224
1225static imap_server_conf_t server =
1226{
1227 NULL, /* name */
1228 NULL, /* tunnel */
1229 NULL, /* host */
1230 0, /* port */
1231 NULL, /* user */
1232 NULL, /* pass */
1233};
1234
1235static char *imap_folder;
1236
1237static int
1238git_imap_config(const char *key, const char *val)
1239{
1240 char imap_key[] = "imap.";
1241
1242 if (strncmp( key, imap_key, sizeof imap_key - 1 ))
1243 return 0;
1244 key += sizeof imap_key - 1;
1245
1246 if (!strcmp( "folder", key )) {
9befac47 1247 imap_folder = xstrdup( val );
f2561fda
MM
1248 } else if (!strcmp( "host", key )) {
1249 {
1968d77d 1250 if (!prefixcmp(val, "imap:"))
f2561fda
MM
1251 val += 5;
1252 if (!server.port)
1253 server.port = 143;
1254 }
1968d77d 1255 if (!prefixcmp(val, "//"))
f2561fda 1256 val += 2;
9befac47 1257 server.host = xstrdup( val );
f2561fda
MM
1258 }
1259 else if (!strcmp( "user", key ))
9befac47 1260 server.user = xstrdup( val );
f2561fda 1261 else if (!strcmp( "pass", key ))
9befac47 1262 server.pass = xstrdup( val );
f2561fda
MM
1263 else if (!strcmp( "port", key ))
1264 server.port = git_config_int( key, val );
1265 else if (!strcmp( "tunnel", key ))
9befac47 1266 server.tunnel = xstrdup( val );
f2561fda
MM
1267 return 0;
1268}
1269
1270int
1271main(int argc, char **argv)
1272{
1273 msg_data_t all_msgs, msg;
5142db69 1274 store_t *ctx = NULL;
f2561fda
MM
1275 int uid = 0;
1276 int ofs = 0;
1277 int r;
1278 int total, n = 0;
1279
1280 /* init the random number generator */
1281 arc4_init();
1282
1283 git_config( git_imap_config );
1284
1285 if (!imap_folder) {
1286 fprintf( stderr, "no imap store specified\n" );
1287 return 1;
1288 }
1289
1290 /* read the messages */
1291 if (!read_message( stdin, &all_msgs )) {
1292 fprintf(stderr,"nothing to send\n");
1293 return 1;
1294 }
1295
1cd88cc9
MM
1296 total = count_messages( &all_msgs );
1297 if (!total) {
1298 fprintf(stderr,"no messages to send\n");
1299 return 1;
1300 }
1301
f2561fda
MM
1302 /* write it to the imap server */
1303 ctx = imap_open_store( &server );
1304 if (!ctx) {
1305 fprintf( stderr,"failed to open store\n");
1306 return 1;
1307 }
1308
f2561fda
MM
1309 fprintf( stderr, "sending %d message%s\n", total, (total!=1)?"s":"" );
1310 ctx->name = imap_folder;
1311 while (1) {
1312 unsigned percent = n * 100 / total;
1313 fprintf( stderr, "%4u%% (%d/%d) done\r", percent, n, total );
1314 if (!split_msg( &all_msgs, &msg, &ofs ))
1315 break;
1316 r = imap_store_msg( ctx, &msg, &uid );
1317 if (r != DRV_OK) break;
1318 n++;
1319 }
1320 fprintf( stderr,"\n" );
1321
1322 imap_close_store( ctx );
1323
1324 return 0;
1325}