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