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