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