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