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