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