Andreas Krennmair:
[apps/madmutt.git] / copy.c
1 /*
2  * Copyright (C) 1996-2000,2002 Michael R. Elkins <me@mutt.org>
3  * 
4  *     This program is free software; you can redistribute it and/or modify
5  *     it under the terms of the GNU General Public License as published by
6  *     the Free Software Foundation; either version 2 of the License, or
7  *     (at your option) any later version.
8  * 
9  *     This program is distributed in the hope that it will be useful,
10  *     but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *     GNU General Public License for more details.
13  * 
14  *     You should have received a copy of the GNU General Public License
15  *     along with this program; if not, write to the Free Software
16  *     Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
17  */
18
19 #if HAVE_CONFIG_H
20 # include "config.h"
21 #endif
22
23 #include "mutt.h"
24 #include "mailbox.h"
25 #include "mx.h"
26 #include "copy.h"
27 #include "rfc2047.h"
28 #include "mime.h"
29 #include "mutt_crypt.h"
30 #include "mutt_idna.h"
31
32 #include <string.h>
33 #include <stdlib.h>
34 #include <ctype.h>
35 #include <unistd.h>             /* needed for SEEK_SET under SunOS 4.1.4 */
36
37 static int address_header_decode (char **str);
38 static int copy_delete_attach (BODY * b, FILE * fpin, FILE * fpout,
39                                char *date);
40
41 /* Ok, the only reason for not merging this with mutt_copy_header()
42  * below is to avoid creating a HEADER structure in message_handler().
43  */
44 int
45 mutt_copy_hdr (FILE * in, FILE * out, long off_start, long off_end, int flags,
46                const char *prefix)
47 {
48   int from = 0;
49   int this_is_from;
50   int ignore = 0;
51   char buf[STRING];             /* should be long enough to get most fields in one pass */
52   char *nl;
53   LIST *t;
54   char **headers;
55   int hdr_count;
56   int x;
57   char *this_one = NULL;
58   int error;
59
60   if (ftell (in) != off_start)
61     fseek (in, off_start, 0);
62
63   buf[0] = '\n';
64   buf[1] = 0;
65
66   if ((flags &
67        (CH_REORDER | CH_WEED | CH_MIME | CH_DECODE | CH_PREFIX |
68         CH_WEED_DELIVERED)) == 0) {
69     /* Without these flags to complicate things
70      * we can do a more efficient line to line copying
71      */
72     while (ftell (in) < off_end) {
73       nl = strchr (buf, '\n');
74
75       if ((fgets (buf, sizeof (buf), in)) == NULL)
76         break;
77
78       /* Is it the begining of a header? */
79       if (nl && buf[0] != ' ' && buf[0] != '\t') {
80         ignore = 1;
81         if (!from && mutt_strncmp ("From ", buf, 5) == 0) {
82           if ((flags & CH_FROM) == 0)
83             continue;
84           from = 1;
85         }
86         else if (flags & (CH_NOQFROM) &&
87                  ascii_strncasecmp (">From ", buf, 6) == 0)
88           continue;
89
90         else if (buf[0] == '\n' || (buf[0] == '\r' && buf[1] == '\n'))
91           break;                /* end of header */
92
93         if ((flags & (CH_UPDATE | CH_XMIT | CH_NOSTATUS)) &&
94             (ascii_strncasecmp ("Status:", buf, 7) == 0 ||
95              ascii_strncasecmp ("X-Status:", buf, 9) == 0))
96           continue;
97         if ((flags & (CH_UPDATE_LEN | CH_XMIT | CH_NOLEN)) &&
98             (ascii_strncasecmp ("Content-Length:", buf, 15) == 0 ||
99              ascii_strncasecmp ("Lines:", buf, 6) == 0))
100           continue;
101         if ((flags & CH_UPDATE_REFS) &&
102             ascii_strncasecmp ("References:", buf, 11) == 0)
103           continue;
104         if ((flags & CH_UPDATE_IRT) &&
105             ascii_strncasecmp ("In-Reply-To:", buf, 12) == 0)
106           continue;
107         ignore = 0;
108       }
109
110       if (!ignore && fputs (buf, out) == EOF)
111         return (-1);
112     }
113     return 0;
114   }
115
116   hdr_count = 1;
117   x = 0;
118   error = FALSE;
119
120   /* We are going to read and collect the headers in an array
121    * so we are able to do re-ordering.
122    * First count the number of entries in the array
123    */
124   if (flags & CH_REORDER) {
125     for (t = HeaderOrderList; t; t = t->next) {
126       dprint (1, (debugfile, "Reorder list: %s\n", t->data));
127       hdr_count++;
128     }
129   }
130
131   dprint (1, (debugfile, "WEED is %s\n", (flags & CH_WEED) ? "Set" : "Not"));
132
133   headers = safe_calloc (hdr_count, sizeof (char *));
134
135   /* Read all the headers into the array */
136   while (ftell (in) < off_end) {
137     nl = strchr (buf, '\n');
138
139     /* Read a line */
140     if ((fgets (buf, sizeof (buf), in)) == NULL)
141       break;
142
143     /* Is it the begining of a header? */
144     if (nl && buf[0] != ' ' && buf[0] != '\t') {
145       /* Do we have anything pending? */
146       if (this_one) {
147         if (flags & CH_DECODE) {
148           if (!address_header_decode (&this_one))
149             rfc2047_decode (&this_one);
150         }
151
152         if (!headers[x])
153           headers[x] = this_one;
154         else {
155           safe_realloc (&headers[x], mutt_strlen (headers[x]) +
156                         mutt_strlen (this_one) + sizeof (char));
157           strcat (headers[x], this_one);        /* __STRCAT_CHECKED__ */
158           FREE (&this_one);
159         }
160
161         this_one = NULL;
162       }
163
164       ignore = 1;
165       this_is_from = 0;
166       if (!from && mutt_strncmp ("From ", buf, 5) == 0) {
167         if ((flags & CH_FROM) == 0)
168           continue;
169         this_is_from = from = 1;
170       }
171       else if (buf[0] == '\n' || (buf[0] == '\r' && buf[1] == '\n'))
172         break;                  /* end of header */
173
174       /* note: CH_FROM takes precedence over header weeding. */
175       if (!((flags & CH_FROM) && (flags & CH_FORCE_FROM) && this_is_from) &&
176           (flags & CH_WEED) &&
177           mutt_matches_ignore (buf, Ignore) &&
178           !mutt_matches_ignore (buf, UnIgnore))
179         continue;
180       if ((flags & CH_WEED_DELIVERED) &&
181           ascii_strncasecmp ("Delivered-To:", buf, 13) == 0)
182         continue;
183       if ((flags & (CH_UPDATE | CH_XMIT | CH_NOSTATUS)) &&
184           (ascii_strncasecmp ("Status:", buf, 7) == 0 ||
185            ascii_strncasecmp ("X-Status:", buf, 9) == 0))
186         continue;
187       if ((flags & (CH_UPDATE_LEN | CH_XMIT | CH_NOLEN)) &&
188           (ascii_strncasecmp ("Content-Length:", buf, 15) == 0 ||
189            ascii_strncasecmp ("Lines:", buf, 6) == 0))
190         continue;
191       if ((flags & CH_MIME) &&
192           ((ascii_strncasecmp ("content-", buf, 8) == 0 &&
193             (ascii_strncasecmp ("transfer-encoding:", buf + 8, 18) == 0 ||
194              ascii_strncasecmp ("type:", buf + 8, 5) == 0)) ||
195            ascii_strncasecmp ("mime-version:", buf, 13) == 0))
196         continue;
197       if ((flags & CH_UPDATE_REFS) &&
198           ascii_strncasecmp ("References:", buf, 11) == 0)
199         continue;
200       if ((flags & CH_UPDATE_IRT) &&
201           ascii_strncasecmp ("In-Reply-To:", buf, 12) == 0)
202         continue;
203
204       /* Find x -- the array entry where this header is to be saved */
205       if (flags & CH_REORDER) {
206         for (t = HeaderOrderList, x = 0; (t); t = t->next, x++) {
207           if (!ascii_strncasecmp (buf, t->data, mutt_strlen (t->data))) {
208             dprint (2, (debugfile, "Reorder: %s matches %s\n", t->data, buf));
209             break;
210           }
211         }
212       }
213
214       ignore = 0;
215     }                           /* If beginning of header */
216
217     if (!ignore) {
218       dprint (2,
219               (debugfile, "Reorder: x = %d; hdr_count = %d\n", x, hdr_count));
220       if (!this_one)
221         this_one = safe_strdup (buf);
222       else {
223         safe_realloc (&this_one,
224                       mutt_strlen (this_one) + mutt_strlen (buf) +
225                       sizeof (char));
226         strcat (this_one, buf); /* __STRCAT_CHECKED__ */
227       }
228     }
229   }                             /* while (ftell (in) < off_end) */
230
231   /* Do we have anything pending?  -- XXX, same code as in above in the loop. */
232   if (this_one) {
233     if (flags & CH_DECODE) {
234       if (!address_header_decode (&this_one))
235         rfc2047_decode (&this_one);
236     }
237
238     if (!headers[x])
239       headers[x] = this_one;
240     else {
241       safe_realloc (&headers[x], mutt_strlen (headers[x]) +
242                     mutt_strlen (this_one) + sizeof (char));
243       strcat (headers[x], this_one);    /* __STRCAT_CHECKED__ */
244       FREE (&this_one);
245     }
246
247     this_one = NULL;
248   }
249
250   /* Now output the headers in order */
251   for (x = 0; x < hdr_count; x++) {
252     if (headers[x]) {
253 #if 0
254       if (flags & CH_DECODE)
255         rfc2047_decode (&headers[x]);
256 #endif
257
258       /* We couldn't do the prefixing when reading because RFC 2047
259        * decoding may have concatenated lines.
260        */
261       if (flags & CH_PREFIX) {
262         char *ch = headers[x];
263         int print_prefix = 1;
264
265         while (*ch) {
266           if (print_prefix) {
267             if (fputs (prefix, out) == EOF) {
268               error = TRUE;
269               break;
270             }
271             print_prefix = 0;
272           }
273
274           if (*ch == '\n' && ch[1])
275             print_prefix = 1;
276
277           if (putc (*ch++, out) == EOF) {
278             error = TRUE;
279             break;
280           }
281         }
282         if (error)
283           break;
284       }
285       else {
286         if (fputs (headers[x], out) == EOF) {
287           error = TRUE;
288           break;
289         }
290       }
291     }
292   }
293
294   /* Free in a separate loop to be sure that all headers are freed
295    * in case of error. */
296   for (x = 0; x < hdr_count; x++)
297     FREE (&headers[x]);
298   FREE (&headers);
299
300   if (error)
301     return (-1);
302   return (0);
303 }
304
305 /* flags
306         CH_DECODE       RFC2047 header decoding
307         CH_FROM         retain the "From " message separator
308         CH_FORCE_FROM   give CH_FROM precedence over CH_WEED
309         CH_MIME         ignore MIME fields
310         CH_NOLEN        don't write Content-Length: and Lines:
311         CH_NONEWLINE    don't output a newline after the header
312         CH_NOSTATUS     ignore the Status: and X-Status:
313         CH_PREFIX       quote header with $indent_str
314         CH_REORDER      output header in order specified by `hdr_order'
315         CH_TXTPLAIN     generate text/plain MIME headers [hack alert.]
316         CH_UPDATE       write new Status: and X-Status:
317         CH_UPDATE_LEN   write new Content-Length: and Lines:
318         CH_XMIT         ignore Lines: and Content-Length:
319         CH_WEED         do header weeding
320         CH_NOQFROM      ignore ">From " line
321         CH_UPDATE_IRT   update the In-Reply-To: header
322         CH_UPDATE_REFS  update the References: header
323
324    prefix
325         string to use if CH_PREFIX is set
326  */
327
328 int
329 mutt_copy_header (FILE * in, HEADER * h, FILE * out, int flags,
330                   const char *prefix)
331 {
332   char buffer[SHORT_STRING];
333
334   flags |= (h->irt_changed ? CH_UPDATE_IRT : 0)
335     | (h->refs_changed ? CH_UPDATE_REFS : 0);
336
337   if (mutt_copy_hdr (in, out, h->offset, h->content->offset, flags, prefix) ==
338       -1)
339     return (-1);
340
341   if (flags & CH_TXTPLAIN) {
342     char chsbuf[SHORT_STRING];
343
344     fputs ("Mime-Version: 1.0\n", out);
345     fputs ("Content-Transfer-Encoding: 8bit\n", out);
346     fputs ("Content-Type: text/plain; charset=", out);
347     mutt_canonical_charset (chsbuf, sizeof (chsbuf),
348                             Charset ? Charset : "us-ascii");
349     rfc822_cat (buffer, sizeof (buffer), chsbuf, MimeSpecials);
350     fputs (buffer, out);
351     fputc ('\n', out);
352
353     if (ferror (out) != 0 || feof (out) != 0)
354       return -1;
355
356   }
357
358   if (flags & CH_UPDATE) {
359     if ((flags & CH_NOSTATUS) == 0) {
360       if (h->irt_changed && h->new_env->in_reply_to) {
361         LIST *listp = h->new_env->in_reply_to;
362
363         if (fputs ("In-Reply-To: ", out) == EOF)
364           return (-1);
365
366         for (; listp; listp = listp->next)
367           if ((fputs (listp->data, out) == EOF) || (fputc (' ', out) == EOF))
368             return (-1);
369
370         if (fputc ('\n', out) == EOF)
371           return (-1);
372       }
373
374       if (h->refs_changed && h->new_env->references) {
375         LIST *listp = h->new_env->references, *refs = NULL, *t;
376
377         if (fputs ("References: ", out) == EOF)
378           return (-1);
379
380         /* Mutt stores references in reverse order, thus we create
381          * a reordered refs list that we can put in the headers */
382         for (; listp; listp = listp->next, refs = t) {
383           t = (LIST *) safe_malloc (sizeof (LIST));
384           t->data = listp->data;
385           t->next = refs;
386         }
387
388         for (; refs; refs = refs->next)
389           if ((fputs (refs->data, out) == EOF) || (fputc (' ', out) == EOF))
390             return (-1);
391
392         /* clearing refs from memory */
393         for (t = refs; refs; refs = t->next, t = refs)
394           FREE (&refs);
395
396         if (fputc ('\n', out) == EOF)
397           return (-1);
398       }
399
400       if (h->old || h->read) {
401         if (fputs ("Status: ", out) == EOF)
402           return (-1);
403
404         if (h->read) {
405           if (fputs ("RO", out) == EOF)
406             return (-1);
407         }
408         else if (h->old) {
409           if (fputc ('O', out) == EOF)
410             return (-1);
411         }
412
413         if (fputc ('\n', out) == EOF)
414           return (-1);
415       }
416
417       if (h->flagged || h->replied) {
418         if (fputs ("X-Status: ", out) == EOF)
419           return (-1);
420
421         if (h->replied) {
422           if (fputc ('A', out) == EOF)
423             return (-1);
424         }
425
426         if (h->flagged) {
427           if (fputc ('F', out) == EOF)
428             return (-1);
429         }
430
431         if (fputc ('\n', out) == EOF)
432           return (-1);
433       }
434     }
435   }
436
437   if (flags & CH_UPDATE_LEN && (flags & CH_NOLEN) == 0) {
438     fprintf (out, "Content-Length: %ld\n", h->content->length);
439     if (h->lines != 0 || h->content->length == 0)
440       fprintf (out, "Lines: %d\n", h->lines);
441   }
442
443   if ((flags & CH_NONEWLINE) == 0) {
444     if (flags & CH_PREFIX)
445       fputs (prefix, out);
446     if (fputc ('\n', out) == EOF)       /* add header terminator */
447       return (-1);
448   }
449
450   if (ferror (out) || feof (out))
451     return -1;
452
453   return (0);
454 }
455
456 /* Count the number of lines and bytes to be deleted in this body*/
457 static int count_delete_lines (FILE * fp, BODY * b, long *length,
458                                size_t datelen)
459 {
460   int dellines = 0;
461   long l;
462   int ch;
463
464   if (b->deleted) {
465     fseek (fp, b->offset, SEEK_SET);
466     for (l = b->length; l; l--) {
467       ch = getc (fp);
468       if (ch == EOF)
469         break;
470       if (ch == '\n')
471         dellines++;
472     }
473     dellines -= 3;
474     *length -= b->length - (84 + datelen);
475     /* Count the number of digits exceeding the first one to write the size */
476     for (l = 10; b->length >= l; l *= 10)
477       (*length)++;
478   }
479   else {
480     for (b = b->parts; b; b = b->next)
481       dellines += count_delete_lines (fp, b, length, datelen);
482   }
483   return dellines;
484 }
485
486 /* make a copy of a message
487  * 
488  * fpout        where to write output
489  * fpin         where to get input
490  * hdr          header of message being copied
491  * body         structure of message being copied
492  * flags
493  *      M_CM_NOHEADER   don't copy header
494  *      M_CM_PREFIX     quote header and body
495  *      M_CM_DECODE     decode message body to text/plain
496  *      M_CM_DISPLAY    displaying output to the user
497  *      M_CM_PRINTING   printing the message
498  *      M_CM_UPDATE     update structures in memory after syncing
499  *      M_CM_DECODE_PGP used for decoding PGP messages
500  *      M_CM_CHARCONV   perform character set conversion 
501  * chflags      flags to mutt_copy_header()
502  */
503
504 int
505 _mutt_copy_message (FILE * fpout, FILE * fpin, HEADER * hdr, BODY * body,
506                     int flags, int chflags)
507 {
508   char prefix[SHORT_STRING];
509   STATE s;
510   long new_offset = -1;
511
512   if (flags & M_CM_PREFIX) {
513     if (option (OPTTEXTFLOWED))
514       strfcpy (prefix, ">", sizeof (prefix));
515     else
516       _mutt_make_string (prefix, sizeof (prefix), NONULL (Prefix), Context,
517                          hdr, 0);
518   }
519
520   if ((flags & M_CM_NOHEADER) == 0) {
521     if (flags & M_CM_PREFIX)
522       chflags |= CH_PREFIX;
523
524     else if (hdr->attach_del && (chflags & CH_UPDATE_LEN)) {
525       int new_lines;
526       long new_length = body->length;
527       char date[SHORT_STRING];
528
529       mutt_make_date (date, sizeof (date));
530       date[5] = date[mutt_strlen (date) - 1] = '\"';
531
532       /* Count the number of lines and bytes to be deleted */
533       fseek (fpin, body->offset, SEEK_SET);
534       new_lines = hdr->lines -
535         count_delete_lines (fpin, body, &new_length, mutt_strlen (date));
536
537       /* Copy the headers */
538       if (mutt_copy_header (fpin, hdr, fpout,
539                             chflags | CH_NOLEN | CH_NONEWLINE, NULL))
540         return -1;
541       fprintf (fpout, "Content-Length: %ld\n", new_length);
542       if (new_lines <= 0)
543         new_lines = 0;
544       else
545         fprintf (fpout, "Lines: %d\n\n", new_lines);
546       if (ferror (fpout) || feof (fpout))
547         return -1;
548       new_offset = ftell (fpout);
549
550       /* Copy the body */
551       fseek (fpin, body->offset, SEEK_SET);
552       if (copy_delete_attach (body, fpin, fpout, date))
553         return -1;
554
555 #ifdef DEBUG
556       {
557         long fail = ((ftell (fpout) - new_offset) - new_length);
558
559         if (fail) {
560           mutt_error ("The length calculation was wrong by %ld bytes", fail);
561           new_length += fail;
562           mutt_sleep (1);
563         }
564       }
565 #endif
566
567       /* Update original message if we are sync'ing a mailfolder */
568       if (flags & M_CM_UPDATE) {
569         hdr->attach_del = 0;
570         hdr->lines = new_lines;
571         body->offset = new_offset;
572
573         /* update the total size of the mailbox to reflect this deletion */
574         Context->size -= body->length - new_length;
575         /*
576          * if the message is visible, update the visible size of the mailbox
577          * as well.
578          */
579         if (Context->v2r[hdr->msgno] != -1)
580           Context->vsize -= body->length - new_length;
581
582         body->length = new_length;
583         mutt_free_body (&body->parts);
584       }
585
586       return 0;
587     }
588
589     if (mutt_copy_header (fpin, hdr, fpout, chflags,
590                           (chflags & CH_PREFIX) ? prefix : NULL) == -1)
591       return -1;
592
593     new_offset = ftell (fpout);
594   }
595
596   if (flags & M_CM_DECODE) {
597     /* now make a text/plain version of the message */
598     memset (&s, 0, sizeof (STATE));
599     s.fpin = fpin;
600     s.fpout = fpout;
601     if (flags & M_CM_PREFIX)
602       s.prefix = prefix;
603     if (flags & M_CM_DISPLAY)
604       s.flags |= M_DISPLAY;
605     if (flags & M_CM_PRINTING)
606       s.flags |= M_PRINTING;
607     if (flags & M_CM_WEED)
608       s.flags |= M_WEED;
609     if (flags & M_CM_CHARCONV)
610       s.flags |= M_CHARCONV;
611     if (flags & M_CM_REPLYING)
612       s.flags |= M_REPLYING;
613
614     if (WithCrypto && flags & M_CM_VERIFY)
615       s.flags |= M_VERIFY;
616
617     mutt_body_handler (body, &s);
618   }
619   else if (WithCrypto
620            && (flags & M_CM_DECODE_CRYPT) && (hdr->security & ENCRYPT)) {
621     BODY *cur;
622     FILE *fp;
623
624     if ((WithCrypto & APPLICATION_PGP)
625         && (flags & M_CM_DECODE_PGP) && (hdr->security & APPLICATION_PGP) &&
626         hdr->content->type == TYPEMULTIPART) {
627       if (crypt_pgp_decrypt_mime (fpin, &fp, hdr->content, &cur))
628         return (-1);
629       fputs ("Mime-Version: 1.0\n", fpout);
630     }
631
632     if ((WithCrypto & APPLICATION_SMIME)
633         && (flags & M_CM_DECODE_SMIME) && (hdr->security & APPLICATION_SMIME)
634         && hdr->content->type == TYPEAPPLICATION) {
635       if (crypt_smime_decrypt_mime (fpin, &fp, hdr->content, &cur))
636         return (-1);
637     }
638
639     mutt_write_mime_header (cur, fpout);
640     fputc ('\n', fpout);
641
642     fseek (fp, cur->offset, 0);
643     if (mutt_copy_bytes (fp, fpout, cur->length) == -1) {
644       fclose (fp);
645       mutt_free_body (&cur);
646       return (-1);
647     }
648     mutt_free_body (&cur);
649     fclose (fp);
650   }
651   else {
652     fseek (fpin, body->offset, 0);
653     if (flags & M_CM_PREFIX) {
654       int c;
655       size_t bytes = body->length;
656
657       fputs (prefix, fpout);
658
659       while ((c = fgetc (fpin)) != EOF && bytes--) {
660         fputc (c, fpout);
661         if (c == '\n') {
662           fputs (prefix, fpout);
663         }
664       }
665     }
666     else if (mutt_copy_bytes (fpin, fpout, body->length) == -1)
667       return -1;
668   }
669
670   if ((flags & M_CM_UPDATE) && (flags & M_CM_NOHEADER) == 0
671       && new_offset != -1) {
672     body->offset = new_offset;
673     mutt_free_body (&body->parts);
674   }
675
676   return 0;
677 }
678
679 int
680 mutt_copy_message (FILE * fpout, CONTEXT * src, HEADER * hdr, int flags,
681                    int chflags)
682 {
683   MESSAGE *msg;
684   int r;
685
686   if ((msg = mx_open_message (src, hdr->msgno)) == NULL)
687     return -1;
688   if ((r =
689        _mutt_copy_message (fpout, msg->fp, hdr, hdr->content, flags,
690                            chflags)) == 0 && (ferror (fpout)
691                                               || feof (fpout))) {
692     dprint (1, (debugfile, "_mutt_copy_message failed to detect EOF!\n"));
693     r = -1;
694   }
695   mx_close_message (&msg);
696   return r;
697 }
698
699 /* appends a copy of the given message to a mailbox
700  *
701  * dest         destination mailbox
702  * fpin         where to get input
703  * src          source mailbox
704  * hdr          message being copied
705  * body         structure of message being copied
706  * flags        mutt_copy_message() flags
707  * chflags      mutt_copy_header() flags
708  */
709
710 int
711 _mutt_append_message (CONTEXT * dest, FILE * fpin, CONTEXT * src,
712                       HEADER * hdr, BODY * body, int flags, int chflags)
713 {
714   MESSAGE *msg;
715   int r;
716
717   if ((msg =
718        mx_open_new_message (dest, hdr,
719                             (src->magic == M_MBOX
720                              || src->magic == M_MMDF) ? 0 : M_ADD_FROM)) ==
721       NULL)
722     return -1;
723   if (dest->magic == M_MBOX || dest->magic == M_MMDF)
724     chflags |= CH_FROM | CH_FORCE_FROM;
725   chflags |= (dest->magic == M_MAILDIR ? CH_NOSTATUS : CH_UPDATE);
726   r = _mutt_copy_message (msg->fp, fpin, hdr, body, flags, chflags);
727   if (mx_commit_message (msg, dest) != 0)
728     r = -1;
729
730   mx_close_message (&msg);
731   return r;
732 }
733
734 int
735 mutt_append_message (CONTEXT * dest, CONTEXT * src, HEADER * hdr, int cmflags,
736                      int chflags)
737 {
738   MESSAGE *msg;
739   int r;
740
741   if ((msg = mx_open_message (src, hdr->msgno)) == NULL)
742     return -1;
743   r =
744     _mutt_append_message (dest, msg->fp, src, hdr, hdr->content, cmflags,
745                           chflags);
746   mx_close_message (&msg);
747   return r;
748 }
749
750 /*
751  * This function copies a message body, while deleting _in_the_copy_
752  * any attachments which are marked for deletion.
753  * Nothing is changed in the original message -- this is left to the caller.
754  *
755  * The function will return 0 on success and -1 on failure.
756  */
757 static int copy_delete_attach (BODY * b, FILE * fpin, FILE * fpout,
758                                char *date)
759 {
760   BODY *part;
761
762   for (part = b->parts; part; part = part->next) {
763     if (part->deleted || part->parts) {
764       /* Copy till start of this part */
765       if (mutt_copy_bytes (fpin, fpout, part->hdr_offset - ftell (fpin)))
766         return -1;
767
768       if (part->deleted) {
769         fprintf (fpout,
770                  "Content-Type: message/external-body; access-type=x-mutt-deleted;\n"
771                  "\texpiration=%s; length=%ld\n"
772                  "\n", date + 5, part->length);
773         if (ferror (fpout))
774           return -1;
775
776         /* Copy the original mime headers */
777         if (mutt_copy_bytes (fpin, fpout, part->offset - ftell (fpin)))
778           return -1;
779
780         /* Skip the deleted body */
781         fseek (fpin, part->offset + part->length, SEEK_SET);
782       }
783       else {
784         if (copy_delete_attach (part, fpin, fpout, date))
785           return -1;
786       }
787     }
788   }
789
790   /* Copy the last parts */
791   if (mutt_copy_bytes (fpin, fpout, b->offset + b->length - ftell (fpin)))
792     return -1;
793
794   return 0;
795 }
796
797 /* 
798  * This function is the equivalent of mutt_write_address_list(),
799  * but writes to a buffer instead of writing to a stream.
800  * mutt_write_address_list could be re-used if we wouldn't store
801  * all the decoded headers in a huge array, first. 
802  *
803  * XXX - fix that. 
804  */
805
806 static void format_address_header (char **h, ADDRESS * a)
807 {
808   char buf[HUGE_STRING];
809   char cbuf[STRING];
810   char c2buf[STRING];
811
812   int l, linelen, buflen, count;
813
814   linelen = mutt_strlen (*h);
815   buflen = linelen + 3;
816
817
818   safe_realloc (h, buflen);
819   for (count = 0; a; a = a->next, count++) {
820     ADDRESS *tmp = a->next;
821
822     a->next = NULL;
823     *buf = *cbuf = *c2buf = '\0';
824     rfc822_write_address (buf, sizeof (buf), a, 0);
825     a->next = tmp;
826
827     l = mutt_strlen (buf);
828     if (count && linelen + l > 74) {
829       strcpy (cbuf, "\n\t");    /* __STRCPY_CHECKED__ */
830       linelen = l + 8;
831     }
832     else {
833       if (a->mailbox) {
834         strcpy (cbuf, " ");     /* __STRCPY_CHECKED__ */
835         linelen++;
836       }
837       linelen += l;
838     }
839     if (!a->group && a->next && a->next->mailbox) {
840       linelen++;
841       buflen++;
842       strcpy (c2buf, ",");      /* __STRCPY_CHECKED__ */
843     }
844
845     buflen += l + mutt_strlen (cbuf) + mutt_strlen (c2buf);
846     safe_realloc (h, buflen);
847     strcat (*h, cbuf);          /* __STRCAT_CHECKED__ */
848     strcat (*h, buf);           /* __STRCAT_CHECKED__ */
849     strcat (*h, c2buf);         /* __STRCAT_CHECKED__ */
850   }
851
852   /* Space for this was allocated in the beginning of this function. */
853   strcat (*h, "\n");            /* __STRCAT_CHECKED__ */
854 }
855
856 static int address_header_decode (char **h)
857 {
858   char *s = *h;
859   int l;
860
861   ADDRESS *a = NULL;
862
863   switch (tolower ((unsigned char) *s)) {
864   case 'r':
865     {
866       if (ascii_strncasecmp (s, "return-path:", 12) == 0) {
867         l = 12;
868         break;
869       }
870       else if (ascii_strncasecmp (s, "reply-to:", 9) == 0) {
871         l = 9;
872         break;
873       }
874       return 0;
875     }
876   case 'f':
877     {
878       if (ascii_strncasecmp (s, "from:", 5))
879         return 0;
880       l = 5;
881       break;
882     }
883   case 'c':
884     {
885       if (ascii_strncasecmp (s, "cc:", 3))
886         return 0;
887       l = 3;
888       break;
889
890     }
891   case 'b':
892     {
893       if (ascii_strncasecmp (s, "bcc:", 4))
894         return 0;
895       l = 4;
896       break;
897     }
898   case 's':
899     {
900       if (ascii_strncasecmp (s, "sender:", 7))
901         return 0;
902       l = 7;
903       break;
904     }
905   case 't':
906     {
907       if (ascii_strncasecmp (s, "to:", 3))
908         return 0;
909       l = 3;
910       break;
911     }
912   case 'm':
913     {
914       if (ascii_strncasecmp (s, "mail-followup-to:", 17))
915         return 0;
916       l = 17;
917       break;
918     }
919   default:
920     return 0;
921   }
922
923   if ((a = rfc822_parse_adrlist (a, s + l)) == NULL)
924     return 0;
925
926   mutt_addrlist_to_local (a);
927   rfc2047_decode_adrlist (a);
928
929   *h = safe_calloc (1, l + 2);
930
931   strfcpy (*h, s, l + 1);
932
933   format_address_header (h, a);
934
935   rfc822_free_address (&a);
936
937   FREE (&s);
938   return 1;
939 }