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