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