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