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