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