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