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