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