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