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