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