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