Nico Golde:
[apps/madmutt.git] / imap / message.c
1 /*
2  * Copyright notice from original mutt:
3  * Copyright (C) 1996-9 Brandon Long <blong@fiction.net>
4  * Copyright (C) 1999-2002 Brendan Cully <brendan@kublai.com>
5  *
6  * This file is part of mutt-ng, see http://www.muttng.org/.
7  * It's licensed under the GNU General Public License,
8  * please see the file GPL in the top level source directory.
9  */
10
11 /* message parsing/updating functions */
12
13 #if HAVE_CONFIG_H
14 # include "config.h"
15 #endif
16
17 #include <stdlib.h>
18 #include <ctype.h>
19
20 #include "mutt.h"
21 #include "ascii.h"
22 #include "buffer.h"
23 #include "mutt_curses.h"
24 #include "imap_private.h"
25 #include "message.h"
26 #include "mx.h"
27 #include "hcache.h"
28
29 #ifdef HAVE_PGP
30 #include "pgp.h"
31 #endif
32
33 #include "lib/mem.h"
34 #include "lib/intl.h"
35 #include "lib/str.h"
36 #include "lib/debug.h"
37
38 #if HAVE_STDINT_H
39 #include <stdint.h>
40 #elif HAVE_INTTYPES_H
41 #include <inttypes.h>
42 #endif
43
44 static void flush_buffer (char *buf, size_t * len, CONNECTION * conn);
45 static int msg_fetch_header (CONTEXT * ctx, IMAP_HEADER * h, char *buf,
46                              FILE * fp);
47 static int msg_has_flag (LIST * flag_list, const char *flag);
48 static int msg_parse_fetch (IMAP_HEADER * h, char *s);
49 static char *msg_parse_flags (IMAP_HEADER * h, char *s);
50
51 #if USE_HCACHE
52 static int msg_fetch_header_fetch (CONTEXT * ctx, IMAP_HEADER * h, char *buf,
53                                    FILE * fp);
54 static size_t imap_hcache_keylen (const char *fn);
55 #endif /* USE_HCACHE */
56
57 /* imap_read_headers:
58  * Changed to read many headers instead of just one. It will return the
59  * msgno of the last message read. It will return a value other than
60  * msgend if mail comes in while downloading headers (in theory).
61  */
62 int imap_read_headers (IMAP_DATA * idata, int msgbegin, int msgend)
63 {
64   CONTEXT *ctx;
65   char buf[LONG_STRING];
66   char hdrreq[STRING];
67   FILE *fp;
68   char tempfile[_POSIX_PATH_MAX];
69   int msgno;
70   IMAP_HEADER h;
71   int rc, mfhrc, oldmsgcount;
72   int fetchlast = 0;
73   const char *want_headers =
74     "DATE FROM SUBJECT TO CC MESSAGE-ID REFERENCES CONTENT-TYPE CONTENT-DESCRIPTION IN-REPLY-TO REPLY-TO LINES LIST-POST X-LABEL";
75
76 #if USE_HCACHE
77   void *hc = NULL;
78   unsigned long *uid_validity = NULL;
79   char uid_buf[64];
80 #endif /* USE_HCACHE */
81
82   ctx = idata->ctx;
83
84   if (mutt_bit_isset (idata->capabilities, IMAP4REV1)) {
85     snprintf (hdrreq, sizeof (hdrreq), "BODY.PEEK[HEADER.FIELDS (%s%s%s)]",
86               want_headers, ImapHeaders ? " " : "",
87               ImapHeaders ? ImapHeaders : "");
88   }
89   else if (mutt_bit_isset (idata->capabilities, IMAP4)) {
90     snprintf (hdrreq, sizeof (hdrreq), "RFC822.HEADER.LINES (%s%s%s)",
91               want_headers, ImapHeaders ? " " : "",
92               ImapHeaders ? ImapHeaders : "");
93   }
94   else {                        /* Unable to fetch headers for lower versions */
95     mutt_error _("Unable to fetch headers from this IMAP server version.");
96
97     mutt_sleep (2);             /* pause a moment to let the user see the error */
98     return -1;
99   }
100
101   /* instead of downloading all headers and then parsing them, we parse them
102    * as they come in. */
103   mutt_mktemp (tempfile);
104   if (!(fp = safe_fopen (tempfile, "w+"))) {
105     mutt_error (_("Could not create temporary file %s"), tempfile);
106     mutt_sleep (2);
107     return -1;
108   }
109   unlink (tempfile);
110
111   /* make sure context has room to hold the mailbox */
112   while ((msgend) >= idata->ctx->hdrmax)
113     mx_alloc_memory (idata->ctx);
114
115   oldmsgcount = ctx->msgcount;
116   idata->reopen &= ~IMAP_NEWMAIL_PENDING;
117   idata->newMailCount = 0;
118
119 #if USE_HCACHE
120   hc = mutt_hcache_open (HeaderCache, ctx->path);
121
122   snprintf (buf, sizeof (buf),
123             "FETCH %d:%d (UID FLAGS)", msgbegin + 1, msgend + 1);
124   fetchlast = msgend + 1;
125
126   imap_cmd_start (idata, buf);
127
128   for (msgno = msgbegin; msgno <= msgend; msgno++) {
129     if (ReadInc && (!msgno || ((msgno + 1) % ReadInc == 0)))
130       mutt_message (_("Evaluating cache... [%d/%d]"), msgno + 1, msgend + 1);
131
132     rewind (fp);
133     memset (&h, 0, sizeof (h));
134     h.data = mem_calloc (1, sizeof (IMAP_HEADER_DATA));
135     do {
136       mfhrc = 0;
137
138       rc = imap_cmd_step (idata);
139       if (rc != IMAP_CMD_CONTINUE)
140         break;
141
142       if ((mfhrc =
143            msg_fetch_header_fetch (idata->ctx, &h, idata->cmd.buf, fp)) == -1)
144         continue;
145       else if (mfhrc < 0)
146         break;
147
148       /* make sure we don't get remnants from older larger message headers */
149       fputs ("\n\n", fp);
150
151       sprintf (uid_buf, "/%u", h.data->uid);    /* XXX --tg 21:41 04-07-11 */
152       uid_validity =
153         (unsigned long *) mutt_hcache_fetch (hc, uid_buf, &imap_hcache_keylen);
154
155       if (uid_validity != NULL && *uid_validity == idata->uid_validity) {
156         ctx->hdrs[msgno] = mutt_hcache_restore((unsigned char *) uid_validity, 0);
157         ctx->hdrs[msgno]->index = h.sid - 1;
158         if (h.sid != ctx->msgcount + 1)
159           debug_print (1, ("imap_read_headers: msgcount and sequence ID are inconsistent!"));
160         /* messages which have not been expunged are ACTIVE (borrowed from mh 
161          * folders) */
162         ctx->hdrs[msgno]->active = 1;
163         ctx->hdrs[msgno]->read = h.read;
164         ctx->hdrs[msgno]->old = h.old;
165         ctx->hdrs[msgno]->deleted = h.deleted;
166         ctx->hdrs[msgno]->flagged = h.flagged;
167         ctx->hdrs[msgno]->replied = h.replied;
168         ctx->hdrs[msgno]->changed = h.changed;
169         /*  ctx->hdrs[msgno]->received is restored from mutt_hcache_restore */
170         ctx->hdrs[msgno]->data = (void *) (h.data);
171
172         ctx->msgcount++;
173       }
174
175       rewind (fp);
176
177       mem_free (&uid_validity);
178
179     }
180     while ((rc != IMAP_CMD_OK) && ((mfhrc == -1) ||
181                                    ((msgno + 1) >= fetchlast)));
182
183     if ((mfhrc < -1) || ((rc != IMAP_CMD_CONTINUE) && (rc != IMAP_CMD_OK))) {
184       imap_free_header_data ((void **) &h.data);
185       fclose (fp);
186       mutt_hcache_close (hc);
187       return -1;
188     }
189   }
190
191   fetchlast = msgbegin;
192 #endif /* USE_HCACHE */
193
194   for (msgno = msgbegin; msgno <= msgend; msgno++) {
195     if (ReadInc && (!msgno || ((msgno + 1) % ReadInc == 0)))
196       mutt_message (_("Fetching message headers... [%d/%d]"), msgno + 1,
197                     msgend + 1);
198
199     if (ctx->hdrs[msgno])
200       continue;
201
202     if (msgno + 1 > fetchlast) {
203       fetchlast = msgno + 1;
204       while ((fetchlast <= msgend) && (!ctx->hdrs[fetchlast]))
205         fetchlast++;
206
207       /*
208        * Make one request for everything. This makes fetching headers an
209        * order of magnitude faster if you have a large mailbox.
210        *
211        * If we get more messages while doing this, we make another
212        * request for all the new messages.
213        */
214       snprintf (buf, sizeof (buf),
215                 "FETCH %d:%d (UID FLAGS INTERNALDATE RFC822.SIZE %s)",
216                 msgno + 1, fetchlast, hdrreq);
217
218       imap_cmd_start (idata, buf);
219     }
220
221     /* freshen fp, h */
222     rewind (fp);
223     memset (&h, 0, sizeof (h));
224     h.data = mem_calloc (1, sizeof (IMAP_HEADER_DATA));
225
226     /* this DO loop does two things:
227      * 1. handles untagged messages, so we can try again on the same msg
228      * 2. fetches the tagged response at the end of the last message.
229      */
230     do {
231       mfhrc = 0;
232
233       rc = imap_cmd_step (idata);
234       if (rc != IMAP_CMD_CONTINUE)
235         break;
236
237       if ((mfhrc =
238            msg_fetch_header (idata->ctx, &h, idata->cmd.buf, fp)) == -1)
239         continue;
240       else if (mfhrc < 0)
241         break;
242
243       /* make sure we don't get remnants from older larger message headers */
244       fputs ("\n\n", fp);
245
246       /* update context with message header */
247       ctx->hdrs[msgno] = mutt_new_header ();
248
249       ctx->hdrs[msgno]->index = h.sid - 1;
250       if (h.sid != ctx->msgcount + 1)
251         debug_print (1, ("msgcount and sequence ID are inconsistent!\n"));
252       /* messages which have not been expunged are ACTIVE (borrowed from mh 
253        * folders) */
254       ctx->hdrs[msgno]->active = 1;
255       ctx->hdrs[msgno]->read = h.read;
256       ctx->hdrs[msgno]->old = h.old;
257       ctx->hdrs[msgno]->deleted = h.deleted;
258       ctx->hdrs[msgno]->flagged = h.flagged;
259       ctx->hdrs[msgno]->replied = h.replied;
260       ctx->hdrs[msgno]->changed = h.changed;
261       ctx->hdrs[msgno]->received = h.received;
262       ctx->hdrs[msgno]->data = (void *) (h.data);
263
264       rewind (fp);
265       /* NOTE: if Date: header is missing, mutt_read_rfc822_header depends
266        *   on h.received being set */
267       ctx->hdrs[msgno]->env = mutt_read_rfc822_header (fp, ctx->hdrs[msgno],
268                                                        0, 0);
269       /* content built as a side-effect of mutt_read_rfc822_header */
270       ctx->hdrs[msgno]->content->length = h.content_length;
271
272 #if USE_HCACHE
273       sprintf (uid_buf, "/%u", h.data->uid);
274       mutt_hcache_store (hc, uid_buf, ctx->hdrs[msgno], idata->uid_validity,
275                          &imap_hcache_keylen);
276 #endif /* USE_HCACHE */
277
278       ctx->msgcount++;
279     }
280     while ((rc != IMAP_CMD_OK) && ((mfhrc == -1) ||
281                                    ((msgno + 1) >= fetchlast)));
282
283     if ((mfhrc < -1) || ((rc != IMAP_CMD_CONTINUE) && (rc != IMAP_CMD_OK))) {
284       imap_free_header_data ((void **) &h.data);
285       fclose (fp);
286 #if USE_HCACHE
287       mutt_hcache_close (hc);
288 #endif /* USE_HCACHE */
289       return -1;
290     }
291
292     /* in case we get new mail while fetching the headers */
293     if (idata->reopen & IMAP_NEWMAIL_PENDING) {
294       msgend = idata->newMailCount - 1;
295       while ((msgend) >= ctx->hdrmax)
296         mx_alloc_memory (ctx);
297       idata->reopen &= ~IMAP_NEWMAIL_PENDING;
298       idata->newMailCount = 0;
299     }
300   }
301
302 #if USE_HCACHE
303   mutt_hcache_close (hc);
304 #endif /* USE_HCACHE */
305
306   fclose (fp);
307
308   if (ctx->msgcount > oldmsgcount)
309     mx_update_context (ctx, ctx->msgcount - oldmsgcount);
310
311   return msgend;
312 }
313
314 int imap_fetch_message (MESSAGE * msg, CONTEXT * ctx, int msgno)
315 {
316   IMAP_DATA *idata;
317   HEADER *h;
318   ENVELOPE* newenv;
319   char buf[LONG_STRING];
320   char path[_POSIX_PATH_MAX];
321   char *pc;
322   long bytes;
323   int uid;
324   int cacheno;
325   IMAP_CACHE *cache;
326   int read;
327   int rc;
328   progress_t bar;
329
330   /* Sam's weird courier server returns an OK response even when FETCH
331    * fails. Thanks Sam. */
332   short fetched = 0;
333
334   idata = (IMAP_DATA *) ctx->data;
335   h = ctx->hdrs[msgno];
336
337   /* see if we already have the message in our cache */
338   cacheno = HEADER_DATA (h)->uid % IMAP_CACHE_LEN;
339   cache = &idata->cache[cacheno];
340
341   if (cache->path) {
342     /* don't treat cache errors as fatal, just fall back. */
343     if (cache->uid == HEADER_DATA(h)->uid && (msg->fp = fopen (cache->path, "r")))
344       return 0;
345     else {
346       unlink (cache->path);
347       mem_free (&cache->path);
348     }
349   }
350
351   if (!isendwin ())
352     mutt_message _("Fetching message...");
353
354   cache->uid = HEADER_DATA (h)->uid;
355   mutt_mktemp (path);
356   cache->path = str_dup (path);
357   if (!(msg->fp = safe_fopen (path, "w+"))) {
358     mem_free (&cache->path);
359     return -1;
360   }
361
362   /* mark this header as currently inactive so the command handler won't
363    * also try to update it. HACK until all this code can be moved into the
364    * command handler */
365   h->active = 0;
366
367   snprintf (buf, sizeof (buf), "UID FETCH %u %s", HEADER_DATA (h)->uid,
368             (mutt_bit_isset (idata->capabilities, IMAP4REV1) ?
369              (option (OPTIMAPPEEK) ? "BODY.PEEK[]" : "BODY[]") : "RFC822"));
370
371   imap_cmd_start (idata, buf);
372   do {
373     if ((rc = imap_cmd_step (idata)) != IMAP_CMD_CONTINUE)
374       break;
375
376     pc = idata->cmd.buf;
377     pc = imap_next_word (pc);
378     pc = imap_next_word (pc);
379
380     if (!ascii_strncasecmp ("FETCH", pc, 5)) {
381       while (*pc) {
382         pc = imap_next_word (pc);
383         if (pc[0] == '(')
384           pc++;
385         if (ascii_strncasecmp ("UID", pc, 3) == 0) {
386           pc = imap_next_word (pc);
387           uid = atoi (pc);
388           if (uid != HEADER_DATA (h)->uid)
389             mutt_error (_
390                         ("The message index is incorrect. Try reopening the mailbox."));
391         }
392         else if ((ascii_strncasecmp ("RFC822", pc, 6) == 0) ||
393                  (ascii_strncasecmp ("BODY[]", pc, 6) == 0)) {
394           pc = imap_next_word (pc);
395           if (imap_get_literal_count (pc, &bytes) < 0) {
396             imap_error ("imap_fetch_message()", buf);
397             goto bail;
398           }
399           bar.size = bytes;
400           bar.msg = _("Fetching message...");
401 #ifdef USE_SOCKET
402           mutt_progress_bar (&bar, 0);
403 #endif
404           if (imap_read_literal (msg->fp, idata, bytes, &bar) < 0)
405             goto bail;
406           /* pick up trailing line */
407           if ((rc = imap_cmd_step (idata)) != IMAP_CMD_CONTINUE)
408             goto bail;
409           pc = idata->cmd.buf;
410
411           fetched = 1;
412         }
413         /* UW-IMAP will provide a FLAGS update here if the FETCH causes a
414          * change (eg from \Unseen to \Seen).
415          * Uncommitted changes in mutt take precedence. If we decide to
416          * incrementally update flags later, this won't stop us syncing */
417         else if ((ascii_strncasecmp ("FLAGS", pc, 5) == 0) && !h->changed) {
418           if ((pc = imap_set_flags (idata, h, pc)) == NULL)
419             goto bail;
420         }
421       }
422     }
423   }
424   while (rc == IMAP_CMD_CONTINUE);
425
426   /* see comment before command start. */
427   h->active = 1;
428
429   fflush (msg->fp);
430   if (ferror (msg->fp)) {
431     mutt_perror (cache->path);
432     goto bail;
433   }
434
435   if (rc != IMAP_CMD_OK)
436     goto bail;
437
438   if (!fetched || !imap_code (idata->cmd.buf))
439     goto bail;
440
441   /* Update the header information.  Previously, we only downloaded a
442    * portion of the headers, those required for the main display.
443    */
444   rewind (msg->fp);
445   /* It may be that the Status header indicates a message is read, but the
446    * IMAP server doesn't know the message has been \Seen. So we capture
447    * the server's notion of 'read' and if it differs from the message info
448    * picked up in mutt_read_rfc822_header, we mark the message (and context
449    * changed). Another possiblity: ignore Status on IMAP?*/
450   read = h->read;
451   newenv = mutt_read_rfc822_header (msg->fp, h, 0, 0);
452   mutt_merge_envelopes(h->env, &newenv);
453
454   /* see above. We want the new status in h->read, so we unset it manually
455    * and let mutt_set_flag set it correctly, updating context. */
456   if (read != h->read) {
457     h->read = read;
458     mutt_set_flag (ctx, h, M_NEW, read);
459   }
460
461   h->lines = 0;
462   fgets (buf, sizeof (buf), msg->fp);
463   while (!feof (msg->fp)) {
464     h->lines++;
465     fgets (buf, sizeof (buf), msg->fp);
466   }
467
468   h->content->length = ftell (msg->fp) - h->content->offset;
469
470   /* This needs to be done in case this is a multipart message */
471 #if defined(HAVE_PGP) || defined(HAVE_SMIME)
472   h->security = crypt_query (h->content);
473 #endif
474
475   mutt_clear_error ();
476   rewind (msg->fp);
477
478   return 0;
479
480 bail:
481   safe_fclose (&msg->fp);
482   if (cache->path) {
483     unlink (cache->path);
484     mem_free (&cache->path);
485   }
486
487   return -1;
488 }
489
490 int imap_append_message (CONTEXT * ctx, MESSAGE * msg)
491 {
492   IMAP_DATA *idata;
493   FILE *fp;
494   char buf[LONG_STRING];
495   char mbox[LONG_STRING];
496   char mailbox[LONG_STRING];
497   size_t len;
498   int c, last;
499   IMAP_MBOX mx;
500   int rc;
501   progress_t bar;
502   size_t sent;
503
504   idata = (IMAP_DATA *) ctx->data;
505
506   if (imap_parse_path (ctx->path, &mx))
507     return -1;
508
509   imap_fix_path (idata, mx.mbox, mailbox, sizeof (mailbox));
510
511   if ((fp = fopen (msg->path, "r")) == NULL) {
512     mutt_perror (msg->path);
513     goto fail;
514   }
515
516   /* currently we set the \Seen flag on all messages, but probably we
517    * should scan the message Status header for flag info. Since we're
518    * already rereading the whole file for length it isn't any more
519    * expensive (it'd be nice if we had the file size passed in already
520    * by the code that writes the file, but that's a lot of changes.
521    * Ideally we'd have a HEADER structure with flag info here... */
522   for (last = EOF, len = 0; (c = fgetc (fp)) != EOF; last = c) {
523     if (c == '\n' && last != '\r')
524       len++;
525
526     len++;
527   }
528   rewind (fp);
529
530   bar.msg = _("Uploading message...");
531   bar.size = len;
532 #ifdef USE_SOCKET
533   mutt_progress_bar (&bar, 0);
534 #endif
535
536   imap_munge_mbox_name (mbox, sizeof (mbox), mailbox);
537   snprintf (buf, sizeof (buf), "APPEND %s (%s%s%s%s%s) {%lu}", mbox,
538             msg->flags.read ? "\\Seen" : "",
539             msg->flags.read && (msg->flags.replied
540                                 || msg->flags.flagged) ? " " : "",
541             msg->flags.replied ? "\\Answered" : "", msg->flags.replied
542             && msg->flags.flagged ? " " : "",
543             msg->flags.flagged ? "\\Flagged" : "", (unsigned long) len);
544
545   imap_cmd_start (idata, buf);
546
547   do
548     rc = imap_cmd_step (idata);
549   while (rc == IMAP_CMD_CONTINUE);
550
551   if (rc != IMAP_CMD_RESPOND) {
552     char *pc;
553
554     debug_print (1, ("command failed: %s\n", idata->cmd.buf));
555
556     pc = idata->cmd.buf + SEQLEN;
557     SKIPWS (pc);
558     pc = imap_next_word (pc);
559     mutt_error ("%s", pc);
560     mutt_sleep (1);
561     fclose (fp);
562     goto fail;
563   }
564
565   for (last = EOF, sent = len = 0; (c = fgetc (fp)) != EOF; last = c) {
566     if (c == '\n' && last != '\r')
567       buf[len++] = '\r';
568
569     buf[len++] = c;
570
571     if (len > sizeof (buf) - 3) {
572       sent += len;
573       flush_buffer (buf, &len, idata->conn);
574 #ifdef USE_SOCKET
575     mutt_progress_bar (&bar, sent);
576 #endif
577     }
578   }
579
580   if (len)
581     flush_buffer (buf, &len, idata->conn);
582
583   mutt_socket_write (idata->conn, "\r\n");
584   fclose (fp);
585
586   do
587     rc = imap_cmd_step (idata);
588   while (rc == IMAP_CMD_CONTINUE);
589
590   if (!imap_code (idata->cmd.buf)) {
591     char *pc;
592
593     debug_print (1, ("command failed: %s\n", idata->cmd.buf));
594     pc = idata->cmd.buf + SEQLEN;
595     SKIPWS (pc);
596     pc = imap_next_word (pc);
597     mutt_error ("%s", pc);
598     mutt_sleep (1);
599     goto fail;
600   }
601
602   mem_free (&mx.mbox);
603   return 0;
604
605 fail:
606   mem_free (&mx.mbox);
607   return -1;
608 }
609
610 /* imap_copy_messages: use server COPY command to copy messages to another
611  *   folder.
612  *   Return codes:
613  *      -1: error
614  *       0: success
615  *       1: non-fatal error - try fetch/append */
616 int imap_copy_messages (CONTEXT * ctx, HEADER * h, char *dest, int delete)
617 {
618   IMAP_DATA *idata;
619   BUFFER cmd, sync_cmd;
620   char uid[11];
621   char mbox[LONG_STRING];
622   char mmbox[LONG_STRING];
623   int rc;
624   int n;
625   IMAP_MBOX mx;
626   int err_continue = M_NO;
627
628   idata = (IMAP_DATA *) ctx->data;
629
630   if (imap_parse_path (dest, &mx)) {
631     debug_print (1, ("bad destination %s\n", dest));
632     return -1;
633   }
634
635   /* check that the save-to folder is in the same account */
636   if (!mutt_account_match (&(CTX_DATA->conn->account), &(mx.account))) {
637     debug_print (3, ("%s not same server as %s\n", dest, ctx->path));
638     return 1;
639   }
640
641   if (h && h->attach_del) {
642     debug_print (3, ("Message contains attachments to be deleted\n"));
643     return 1;
644   }
645
646   imap_fix_path (idata, mx.mbox, mbox, sizeof (mbox));
647
648   memset (&sync_cmd, 0, sizeof (sync_cmd));
649   memset (&cmd, 0, sizeof (cmd));
650   mutt_buffer_addstr (&cmd, "UID COPY ");
651
652   /* Null HEADER* means copy tagged messages */
653   if (!h) {
654     /* if any messages have attachments to delete, fall through to FETCH
655      * and APPEND. TODO: Copy what we can with COPY, fall through for the
656      * remainder. */
657     for (n = 0; n < ctx->msgcount; n++) {
658       if (ctx->hdrs[n]->tagged && ctx->hdrs[n]->attach_del) {
659         debug_print (3, ("Message contains attachments to be deleted\n"));
660         return 1;
661       }
662
663       if (ctx->hdrs[n]->tagged && ctx->hdrs[n]->active &&
664           ctx->hdrs[n]->changed)
665       {
666         rc = imap_sync_message (idata, ctx->hdrs[n], &sync_cmd, &err_continue);
667         if (rc < 0)
668         {
669           debug_print (1, ("could not sync\n"));
670           goto fail;
671         }
672       }
673     }
674
675     rc = imap_make_msg_set (idata, &cmd, M_TAG, 0);
676     if (!rc) {
677       debug_print (1, ("No messages tagged\n"));
678       goto fail;
679     }
680     mutt_message (_("Copying %d messages to %s..."), rc, mbox);
681   }
682   else {
683     mutt_message (_("Copying message %d to %s..."), h->index + 1, mbox);
684     snprintf (uid, sizeof (uid), "%u", HEADER_DATA (h)->uid);
685     mutt_buffer_addstr (&cmd, uid);
686
687     if (h->active && h->changed)
688     {
689       rc = imap_sync_message (idata, h, &sync_cmd, &err_continue);
690       if (rc < 0)
691       {
692         debug_print (1, ("could not sync\n"));
693         goto fail;
694       }
695     }
696   }
697
698   /* let's get it on */
699   mutt_buffer_addstr (&cmd, " ");
700   imap_munge_mbox_name (mmbox, sizeof (mmbox), mbox);
701   mutt_buffer_addstr (&cmd, mmbox);
702
703   rc = imap_exec (idata, cmd.data, IMAP_CMD_FAIL_OK);
704   if (rc == -2) {
705     /* bail out if command failed for reasons other than nonexistent target */
706     if (ascii_strncasecmp
707         (imap_get_qualifier (idata->cmd.buf), "[TRYCREATE]", 11)) {
708       imap_error ("imap_copy_messages", idata->cmd.buf);
709       goto fail;
710     }
711     debug_print (2, ("server suggests TRYCREATE\n"));
712     snprintf (mmbox, sizeof (mmbox), _("Create %s?"), mbox);
713     if (option (OPTCONFIRMCREATE) && mutt_yesorno (mmbox, 1) < 1) {
714       mutt_clear_error ();
715       goto fail;
716     }
717     if (imap_create_mailbox (idata, mbox) < 0)
718       goto fail;
719
720     /* try again */
721     rc = imap_exec (idata, cmd.data, 0);
722   }
723   if (rc != 0) {
724     imap_error ("imap_copy_messages", idata->cmd.buf);
725     goto fail;
726   }
727
728   /* cleanup */
729   if (delete) {
730     if (!h)
731       for (n = 0; n < ctx->msgcount; n++) {
732         if (ctx->hdrs[n]->tagged) {
733           mutt_set_flag (ctx, ctx->hdrs[n], M_DELETE, 1);
734           mutt_set_flag (ctx, ctx->hdrs[n], M_APPENDED, 1);
735           if (option (OPTDELETEUNTAG))
736             mutt_set_flag (ctx, ctx->hdrs[n], M_TAG, 0);
737         }
738       }
739     else {
740       mutt_set_flag (ctx, h, M_DELETE, 1);
741       mutt_set_flag (ctx, h, M_APPENDED, 1);
742       if (option (OPTDELETEUNTAG))
743         mutt_set_flag (ctx, h, M_TAG, 0);
744     }
745   }
746
747   if (cmd.data)
748     mem_free (&cmd.data);
749   if (sync_cmd.data)
750     mem_free (&sync_cmd.data);
751   mem_free (&mx.mbox);
752   return 0;
753
754 fail:
755   if (cmd.data)
756     mem_free (&cmd.data);
757   if (sync_cmd.data)
758     mem_free (&sync_cmd.data);
759   mem_free (&mx.mbox);
760   return -1;
761 }
762
763 /* imap_add_keywords: concatenate custom IMAP tags to list, if they
764  *   appear in the folder flags list. Why wouldn't they? */
765 void imap_add_keywords (char *s, HEADER * h, LIST * mailbox_flags,
766                         size_t slen)
767 {
768   LIST *keywords;
769
770   if (!mailbox_flags || !HEADER_DATA (h) || !HEADER_DATA (h)->keywords)
771     return;
772
773   keywords = HEADER_DATA (h)->keywords->next;
774
775   while (keywords) {
776     if (msg_has_flag (mailbox_flags, keywords->data)) {
777       str_cat (s, slen, keywords->data);
778       str_cat (s, slen, " ");
779     }
780     keywords = keywords->next;
781   }
782 }
783
784 /* imap_free_header_data: free IMAP_HEADER structure */
785 void imap_free_header_data (void **data)
786 {
787   /* this should be safe even if the list wasn't used */
788   mutt_free_list (&(((IMAP_HEADER_DATA *) * data)->keywords));
789
790   mem_free (data);
791 }
792
793 /* imap_set_flags: fill out the message header according to the flags from
794  *   the server. Expects a flags line of the form "FLAGS (flag flag ...)" */
795 char *imap_set_flags (IMAP_DATA * idata, HEADER * h, char *s)
796 {
797   CONTEXT *ctx = idata->ctx;
798   IMAP_HEADER newh;
799   unsigned char readonly;
800
801   memset (&newh, 0, sizeof (newh));
802   newh.data = mem_calloc (1, sizeof (IMAP_HEADER_DATA));
803
804   debug_print (2, ("parsing FLAGS\n"));
805   if ((s = msg_parse_flags (&newh, s)) == NULL) {
806     mem_free (&newh.data);
807     return NULL;
808   }
809
810   /* YAUH (yet another ugly hack): temporarily set context to
811    * read-write even if it's read-only, so *server* updates of
812    * flags can be processed by mutt_set_flag. ctx->changed must
813    * be restored afterwards */
814   readonly = ctx->readonly;
815   ctx->readonly = 0;
816
817   mutt_set_flag (ctx, h, M_NEW, !(newh.read || newh.old));
818   mutt_set_flag (ctx, h, M_OLD, newh.old);
819   mutt_set_flag (ctx, h, M_READ, newh.read);
820   mutt_set_flag (ctx, h, M_DELETE, newh.deleted);
821   mutt_set_flag (ctx, h, M_FLAG, newh.flagged);
822   mutt_set_flag (ctx, h, M_REPLIED, newh.replied);
823
824   /* this message is now definitively *not* changed (mutt_set_flag
825    * marks things changed as a side-effect) */
826   h->changed = 0;
827   ctx->changed &= ~readonly;
828   ctx->readonly = readonly;
829
830   mutt_free_list (&(HEADER_DATA (h)->keywords));
831   HEADER_DATA (h)->keywords = newh.data->keywords;
832   mem_free (&newh.data);
833
834   return s;
835 }
836
837
838 /* msg_fetch_header: import IMAP FETCH response into an IMAP_HEADER.
839  *   Expects string beginning with * n FETCH.
840  *   Returns:
841  *      0 on success
842  *     -1 if the string is not a fetch response
843  *     -2 if the string is a corrupt fetch response */
844 static int msg_fetch_header (CONTEXT * ctx, IMAP_HEADER * h, char *buf,
845                              FILE * fp)
846 {
847   IMAP_DATA *idata;
848   long bytes;
849   int rc = -1;                  /* default now is that string isn't FETCH response */
850
851   idata = (IMAP_DATA *) ctx->data;
852
853   if (buf[0] != '*')
854     return rc;
855
856   /* skip to message number */
857   buf = imap_next_word (buf);
858   h->sid = atoi (buf);
859
860   /* find FETCH tag */
861   buf = imap_next_word (buf);
862   if (ascii_strncasecmp ("FETCH", buf, 5))
863     return rc;
864
865   rc = -2;                      /* we've got a FETCH response, for better or worse */
866   if (!(buf = strchr (buf, '(')))
867     return rc;
868   buf++;
869
870   /* FIXME: current implementation - call msg_parse_fetch - if it returns -2,
871    *   read header lines and call it again. Silly. */
872   if (msg_parse_fetch (h, buf) != -2)
873     return rc;
874
875   if (imap_get_literal_count (buf, &bytes) == 0) {
876     imap_read_literal (fp, idata, bytes, NULL);
877
878     /* we may have other fields of the FETCH _after_ the literal
879      * (eg Domino puts FLAGS here). Nothing wrong with that, either.
880      * This all has to go - we should accept literals and nonliterals
881      * interchangeably at any time. */
882     if (imap_cmd_step (idata) != IMAP_CMD_CONTINUE)
883       return rc;
884
885     if (msg_parse_fetch (h, idata->cmd.buf) == -1)
886       return rc;
887   }
888
889   rc = 0;                       /* success */
890
891   /* subtract headers from message size - unfortunately only the subset of
892    * headers we've requested. */
893   h->content_length -= bytes;
894
895   return rc;
896 }
897
898 #if USE_HCACHE
899 static size_t imap_hcache_keylen (const char *fn)
900 {
901   return str_len (fn);
902 }
903
904 /* msg_fetch_header: import IMAP FETCH response into an IMAP_HEADER.
905  *   Expects string beginning with * n FETCH.
906  *   Returns:
907  *      0 on success
908  *     -1 if the string is not a fetch response
909  *     -2 if the string is a corrupt fetch response */
910 static int msg_fetch_header_fetch (CONTEXT * ctx, IMAP_HEADER * h, char *buf,
911                                    FILE * fp)
912 {
913   IMAP_DATA *idata;
914   int rc = -1;                  /* default now is that string isn't FETCH response */
915
916   idata = (IMAP_DATA *) ctx->data;
917
918   if (buf[0] != '*')
919     return rc;
920
921   /* skip to message number */
922   buf = imap_next_word (buf);
923   h->sid = atoi (buf);
924
925   /* find FETCH tag */
926   buf = imap_next_word (buf);
927   if (ascii_strncasecmp ("FETCH", buf, 5))
928     return rc;
929
930   rc = -2;                      /* we've got a FETCH response, for better or worse */
931   if (!(buf = strchr (buf, '(')))
932     return rc;
933   buf++;
934
935   if (msg_parse_fetch (h, buf) < 0) {
936     return -2;
937   }
938
939   if (!(buf = strchr (buf, ')')))
940     return rc;
941   buf++;
942
943   return 0;
944 }
945 #endif /* USE_HCACHE */
946
947
948 /* msg_has_flag: do a caseless comparison of the flag against a flag list,
949  *   return 1 if found or flag list has '\*', 0 otherwise */
950 static int msg_has_flag (LIST * flag_list, const char *flag)
951 {
952   if (!flag_list)
953     return 0;
954
955   flag_list = flag_list->next;
956   while (flag_list) {
957     if (!ascii_strncasecmp (flag_list->data, flag, str_len (flag_list->data)))
958       return 1;
959
960     flag_list = flag_list->next;
961   }
962
963   return 0;
964 }
965
966 /* msg_parse_fetch: handle headers returned from header fetch */
967 static int msg_parse_fetch (IMAP_HEADER * h, char *s)
968 {
969   char tmp[SHORT_STRING];
970   char *ptmp;
971
972   if (!s)
973     return -1;
974
975   while (*s) {
976     SKIPWS (s);
977
978     if (ascii_strncasecmp ("FLAGS", s, 5) == 0) {
979       if ((s = msg_parse_flags (h, s)) == NULL)
980         return -1;
981     }
982     else if (ascii_strncasecmp ("UID", s, 3) == 0) {
983       s += 3;
984       SKIPWS (s);
985       h->data->uid = (unsigned int) atoi (s);
986
987       s = imap_next_word (s);
988     }
989     else if (ascii_strncasecmp ("INTERNALDATE", s, 12) == 0) {
990       s += 12;
991       SKIPWS (s);
992       if (*s != '\"') {
993         debug_print (1, ("bogus INTERNALDATE entry: %s\n", s));
994         return -1;
995       }
996       s++;
997       ptmp = tmp;
998       while (*s && *s != '\"')
999         *ptmp++ = *s++;
1000       if (*s != '\"')
1001         return -1;
1002       s++;                      /* skip past the trailing " */
1003       *ptmp = 0;
1004       h->received = imap_parse_date (tmp);
1005     }
1006     else if (ascii_strncasecmp ("RFC822.SIZE", s, 11) == 0) {
1007       s += 11;
1008       SKIPWS (s);
1009       ptmp = tmp;
1010       while (isdigit ((unsigned char) *s))
1011         *ptmp++ = *s++;
1012       *ptmp = 0;
1013       h->content_length = atoi (tmp);
1014     }
1015     else if (!ascii_strncasecmp ("BODY", s, 4) ||
1016              !ascii_strncasecmp ("RFC822.HEADER", s, 13)) {
1017       /* handle above, in msg_fetch_header */
1018       return -2;
1019     }
1020     else if (*s == ')')
1021       s++;                      /* end of request */
1022     else if (*s) {
1023       /* got something i don't understand */
1024       imap_error ("msg_parse_fetch", s);
1025       return -1;
1026     }
1027   }
1028
1029   return 0;
1030 }
1031
1032 /* msg_parse_flags: read a FLAGS token into an IMAP_HEADER */
1033 static char *msg_parse_flags (IMAP_HEADER * h, char *s)
1034 {
1035   int recent = 0;
1036
1037   /* sanity-check string */
1038   if (ascii_strncasecmp ("FLAGS", s, 5) != 0) {
1039     debug_print (1, ("not a FLAGS response: %s\n", s));
1040     return NULL;
1041   }
1042   s += 5;
1043   SKIPWS (s);
1044   if (*s != '(') {
1045     debug_print (1, ("bogus FLAGS response: %s\n", s));
1046     return NULL;
1047   }
1048   s++;
1049
1050   /* start parsing */
1051   while (*s && *s != ')') {
1052     if (ascii_strncasecmp ("\\deleted", s, 8) == 0) {
1053       s += 8;
1054       h->deleted = 1;
1055     }
1056     else if (ascii_strncasecmp ("\\flagged", s, 8) == 0) {
1057       s += 8;
1058       h->flagged = 1;
1059     }
1060     else if (ascii_strncasecmp ("\\answered", s, 9) == 0) {
1061       s += 9;
1062       h->replied = 1;
1063     }
1064     else if (ascii_strncasecmp ("\\seen", s, 5) == 0) {
1065       s += 5;
1066       h->read = 1;
1067     }
1068     else if (ascii_strncasecmp ("\\recent", s, 5) == 0) {
1069       s += 7;
1070       recent = 1;
1071     }
1072     else {
1073       /* store custom flags as well */
1074       char ctmp;
1075       char *flag_word = s;
1076
1077       if (!h->data->keywords)
1078         h->data->keywords = mutt_new_list ();
1079
1080       while (*s && !ISSPACE (*s) && *s != ')')
1081         s++;
1082       ctmp = *s;
1083       *s = '\0';
1084       mutt_add_list (h->data->keywords, flag_word);
1085       *s = ctmp;
1086     }
1087     SKIPWS (s);
1088   }
1089
1090   /* wrap up, or note bad flags response */
1091   if (*s == ')') {
1092     /* if a message is neither seen nor recent, it is OLD. */
1093     if (option (OPTMARKOLD) && !recent && !(h->read))
1094       h->old = 1;
1095     s++;
1096   }
1097   else {
1098     debug_print (1, ("Unterminated FLAGS response: %s\n", s));
1099     return NULL;
1100   }
1101
1102   return s;
1103 }
1104
1105 static void flush_buffer (char *buf, size_t * len, CONNECTION * conn)
1106 {
1107   buf[*len] = '\0';
1108   mutt_socket_write (conn, buf);
1109   *len = 0;
1110 }