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