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