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