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