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