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