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