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