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