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