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