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