a66665c788307ac144ab07bef88c8cea31c515a8
[apps/madmutt.git] / attach.c
1 /*
2  * Copyright notice from original mutt:
3  * Copyright (C) 1996-2000 Michael R. Elkins <me@mutt.org>
4  * Copyright (C) 1999-2000 Thomas Roessler <roessler@does-not-exist.org>
5  *
6  * This file is part of mutt-ng, see http://www.muttng.org/.
7  * It's licensed under the GNU General Public License,
8  * please see the file GPL in the top level source directory.
9  */
10
11 #if HAVE_CONFIG_H
12 # include "config.h"
13 #endif
14
15 #include <ctype.h>
16 #include <stdlib.h>
17 #include <unistd.h>
18 #include <sys/wait.h>
19 #include <sys/stat.h>
20 #include <fcntl.h>
21 #include <string.h>
22 #include <errno.h>
23
24 #include <lib-lib/lib-lib.h>
25
26 #include <lib-sys/unix.h>
27
28 #include <lib-mime/mime.h>
29
30 #include <lib-ui/curses.h>
31 #include <lib-ui/menu.h>
32
33 #include "mutt.h"
34 #include "handler.h"
35 #include "recvattach.h"
36 #include "keymap.h"
37 #include "pager.h"
38 #include "copy.h"
39 #include "mx.h"
40 #include <lib-crypt/crypt.h>
41
42 int mutt_get_tmp_attachment (BODY * a)
43 {
44   char type[STRING];
45   char tempfile[_POSIX_PATH_MAX];
46   rfc1524_entry *entry = rfc1524_entry_new();
47   FILE *fpin = NULL, *fpout = NULL;
48   struct stat st;
49
50   if (a->unlink)
51     return 0;
52
53   snprintf (type, sizeof (type), "%s/%s", TYPE (a), a->subtype);
54   rfc1524_mailcap_lookup (a, type, entry, 0);
55   rfc1524_expand_filename (entry->nametemplate, a->filename,
56                            tempfile, sizeof (tempfile));
57
58   rfc1524_entry_delete(&entry);
59
60   if (stat (a->filename, &st) == -1)
61     return -1;
62
63   if ((fpin = fopen (a->filename, "r")) && (fpout = safe_fopen (tempfile, "w"))) {      /* __FOPEN_CHECKED__ */
64     mutt_copy_stream (fpin, fpout);
65     m_strreplace(&a->filename, tempfile);
66     a->unlink = 1;
67
68     if (a->stamp >= st.st_mtime)
69       mutt_stamp_attachment (a);
70   }
71   else
72     mutt_perror(fpin ? tempfile : a->filename);
73
74   if (fpin)
75     fclose (fpin);
76   if (fpout)
77     fclose (fpout);
78
79   return a->unlink ? 0 : -1;
80 }
81
82
83 /* return 1 if require full screen redraw, 0 otherwise */
84 int mutt_compose_attachment (BODY * a)
85 {
86   char type[STRING];
87   char command[STRING];
88   char newfile[_POSIX_PATH_MAX] = "";
89   rfc1524_entry *entry = rfc1524_entry_new();
90   short unlink_newfile = 0;
91   int rc = 0;
92
93   snprintf (type, sizeof (type), "%s/%s", TYPE (a), a->subtype);
94   if (rfc1524_mailcap_lookup (a, type, entry, M_COMPOSE)) {
95     if (entry->composecommand || entry->composetypecommand) {
96
97       if (entry->composetypecommand)
98         m_strcpy(command, sizeof(command), entry->composetypecommand);
99       else
100         m_strcpy(command, sizeof(command), entry->composecommand);
101       if (rfc1524_expand_filename (entry->nametemplate,
102                                    a->filename, newfile, sizeof (newfile))) {
103         if (safe_symlink (a->filename, newfile) == -1) {
104           if (mutt_yesorno (_("Can't match nametemplate, continue?"), M_YES)
105               != M_YES)
106             goto bailout;
107         }
108         else
109           unlink_newfile = 1;
110       }
111       else
112         m_strcpy(newfile, sizeof(newfile), a->filename);
113
114       if (rfc1524_expand_command (a, newfile, type,
115                                   command, sizeof (command))) {
116         /* For now, editing requires a file, no piping */
117         mutt_error _("Mailcap compose entry requires %%s");
118       }
119       else {
120         int r;
121
122         mutt_endwin (NULL);
123         if ((r = mutt_system (command)) == -1)
124           mutt_error (_("Error running \"%s\"!"), command);
125
126         if (r != -1 && entry->composetypecommand) {
127           BODY *b;
128           FILE *fp, *tfp;
129           char tempfile[_POSIX_PATH_MAX];
130
131           if ((fp = safe_fopen (a->filename, "r")) == NULL) {
132             mutt_perror (_("Failure to open file to parse headers."));
133
134             goto bailout;
135           }
136
137           b = mutt_read_mime_header (fp, 0);
138           if (b) {
139             if (b->parameter) {
140               parameter_list_wipe(&a->parameter);
141               a->parameter = b->parameter;
142               b->parameter = NULL;
143             }
144             if (b->description) {
145               p_delete(&a->description);
146               a->description = b->description;
147               b->description = NULL;
148             }
149             if (b->form_name) {
150               p_delete(&a->form_name);
151               a->form_name = b->form_name;
152               b->form_name = NULL;
153             }
154
155             /* Remove headers by copying out data to another file, then 
156              * copying the file back */
157             fseeko (fp, b->offset, 0);
158             mutt_mktemp (tempfile);
159             if ((tfp = safe_fopen (tempfile, "w")) == NULL) {
160               mutt_perror (_("Failure to open file to strip headers."));
161
162               goto bailout;
163             }
164             mutt_copy_stream (fp, tfp);
165             fclose (fp);
166             fclose (tfp);
167             mutt_unlink (a->filename);
168             if (mutt_rename_file (tempfile, a->filename) != 0) {
169               mutt_perror (_("Failure to rename file."));
170
171               goto bailout;
172             }
173
174             body_list_wipe(&b);
175           }
176         }
177       }
178     }
179   }
180   else {
181     rfc1524_entry_delete(&entry);
182     mutt_message (_("No mailcap compose entry for %s, creating empty file."),
183                   type);
184     return 1;
185   }
186
187   rc = 1;
188
189 bailout:
190
191   if (unlink_newfile)
192     unlink (newfile);
193
194   rfc1524_entry_delete(&entry);
195   return rc;
196 }
197
198 /* 
199  * Currently, this only works for send mode, as it assumes that the 
200  * BODY->filename actually contains the information.  I'm not sure
201  * we want to deal with editing attachments we've already received,
202  * so this should be ok.
203  *
204  * Returns 1 if editor found, 0 if not (useful to tell calling menu to
205  * redraw)
206  */
207 int mutt_edit_attachment (BODY * a)
208 {
209   char type[STRING];
210   char command[STRING];
211   char newfile[_POSIX_PATH_MAX] = "";
212   rfc1524_entry *entry = rfc1524_entry_new();
213   short unlink_newfile = 0;
214   int rc = 0;
215
216   snprintf (type, sizeof (type), "%s/%s", TYPE (a), a->subtype);
217   if (rfc1524_mailcap_lookup (a, type, entry, M_EDIT)) {
218     if (entry->editcommand) {
219
220       m_strcpy(command, sizeof(command), entry->editcommand);
221       if (rfc1524_expand_filename (entry->nametemplate,
222                                    a->filename, newfile, sizeof (newfile))) {
223           if (safe_symlink (a->filename, newfile) == -1) {
224           if (mutt_yesorno (_("Can't match nametemplate, continue?"), M_YES)
225               != M_YES)
226             goto bailout;
227         }
228         else
229           unlink_newfile = 1;
230       }
231       else
232         m_strcpy(newfile, sizeof(newfile), a->filename);
233
234       if (rfc1524_expand_command (a, newfile, type,
235                                   command, sizeof (command))) {
236         /* For now, editing requires a file, no piping */
237         mutt_error _("Mailcap Edit entry requires %%s");
238         goto bailout;
239       }
240       else {
241         mutt_endwin (NULL);
242         if (mutt_system (command) == -1) {
243           mutt_error (_("Error running \"%s\"!"), command);
244           goto bailout;
245         }
246       }
247     }
248   }
249   else if (a->type == TYPETEXT) {
250     /* On text, default to editor */
251     mutt_edit_file (NONULL (Editor), a->filename);
252   }
253   else {
254     rfc1524_entry_delete(&entry);
255     mutt_error (_("No mailcap edit entry for %s"), type);
256     return 0;
257   }
258
259   rc = 1;
260
261 bailout:
262
263   if (unlink_newfile)
264     unlink (newfile);
265
266   rfc1524_entry_delete(&entry);
267   return rc;
268 }
269
270
271 /* for compatibility with metamail */
272 static int is_mmnoask (const char *buf)
273 {
274   char tmp[LONG_STRING], *p, *q;
275   int lng;
276
277   if ((p = getenv ("MM_NOASK")) != NULL && *p) {
278     if (m_strcmp(p, "1") == 0)
279       return (1);
280
281     m_strcpy(tmp, sizeof(tmp), p);
282     p = tmp;
283
284     while ((p = strtok (p, ",")) != NULL) {
285       if ((q = strrchr (p, '/')) != NULL) {
286         if (*(q + 1) == '*') {
287           if (ascii_strncasecmp (buf, p, q - p) == 0)
288             return (1);
289         }
290         else {
291           if (ascii_strcasecmp (buf, p) == 0)
292             return (1);
293         }
294       }
295       else {
296         lng = m_strlen(p);
297         if (buf[lng] == '/' && m_strncasecmp(buf, p, lng) == 0)
298           return (1);
299       }
300
301       p = NULL;
302     }
303   }
304
305   return (0);
306 }
307
308 void mutt_check_lookup_list (BODY * b, char *type, int len)
309 {
310   string_list_t *t = MimeLookupList;
311   int i;
312
313   for (; t; t = t->next) {
314     i = m_strlen(t->data) - 1;
315     if ((i > 0 && t->data[i - 1] == '/' && t->data[i] == '*' &&
316          ascii_strncasecmp (type, t->data, i) == 0) ||
317         ascii_strcasecmp (type, t->data) == 0) {
318
319       BODY tmp;
320       int n;
321
322       p_clear(&tmp, 1);
323
324       if ((n = mutt_lookup_mime_type (&tmp, b->filename)) != TYPEOTHER) {
325         snprintf (type, len, "%s/%s",
326                   n == TYPEAUDIO ? "audio" :
327                   n == TYPEAPPLICATION ? "application" :
328                   n == TYPEIMAGE ? "image" :
329                   n == TYPEMESSAGE ? "message" :
330                   n == TYPEMODEL ? "model" :
331                   n == TYPEMULTIPART ? "multipart" :
332                   n == TYPETEXT ? "text" :
333                   n == TYPEVIDEO ? "video" : "other", tmp.subtype);
334       }
335       if (tmp.subtype)
336         p_delete(&tmp.subtype);
337       if (tmp.xtype)
338         p_delete(&tmp.xtype);
339     }
340   }
341 }
342
343 int mutt_is_autoview (BODY * b, const char *type)
344 {
345   string_list_t *t = AutoViewList;
346   char _type[SHORT_STRING];
347   int i;
348
349   if (!type)
350     snprintf (_type, sizeof (_type), "%s/%s", TYPE (b), b->subtype);
351   else
352     m_strcpy(_type, sizeof(_type), type);
353
354   mutt_check_lookup_list (b, _type, sizeof (_type));
355   type = _type;
356
357   if (rfc1524_mailcap_isneeded(b)) {
358     if (option (OPTIMPLICITAUTOVIEW))
359       return 1;
360
361     if (is_mmnoask (type))
362       return 1;
363   }
364
365   for (; t; t = t->next) {
366     i = m_strlen(t->data) - 1;
367     if ((i > 0 && t->data[i - 1] == '/' && t->data[i] == '*' &&
368          ascii_strncasecmp (type, t->data, i) == 0) ||
369         ascii_strcasecmp (type, t->data) == 0)
370       return 1;
371   }
372
373   return 0;
374 }
375
376 /* returns -1 on error, 0 or the return code from mutt_do_pager() on success */
377 int mutt_view_attachment (FILE * fp, BODY * a, int flag, HEADER * hdr,
378                           ATTACHPTR ** idx, short idxlen)
379 {
380   char tempfile[_POSIX_PATH_MAX] = "";
381   char pagerfile[_POSIX_PATH_MAX] = "";
382   int is_message;
383   int use_mailcap;
384   int use_pipe = 0;
385   int use_pager = 1;
386   char type[STRING];
387   char command[STRING];
388   char descrip[STRING];
389   char *fname;
390   rfc1524_entry *entry = NULL;
391   int rc = -1;
392   int unlink_tempfile = 0;
393
394   is_message = mutt_is_message_type (a->type, a->subtype);
395   if (is_message && a->hdr && (a->hdr->security & ENCRYPT) &&
396       !crypt_valid_passphrase (a->hdr->security))
397     return (rc);
398   use_mailcap = (flag == M_MAILCAP ||
399                  (flag == M_REGULAR && rfc1524_mailcap_isneeded(a)));
400   snprintf (type, sizeof (type), "%s/%s", TYPE (a), a->subtype);
401
402   if (use_mailcap) {
403     entry = rfc1524_entry_new();
404     if (!rfc1524_mailcap_lookup (a, type, entry, 0)) {
405       if (flag == M_REGULAR) {
406         /* fallback to view as text */
407         rfc1524_entry_delete(&entry);
408         mutt_error _("No matching mailcap entry found.  Viewing as text.");
409
410         flag = M_AS_TEXT;
411         use_mailcap = 0;
412       }
413       else
414         goto return_error;
415     }
416   }
417
418   if (use_mailcap) {
419     if (!entry->command) {
420       mutt_error _("MIME type not defined.  Cannot view attachment.");
421
422       goto return_error;
423     }
424     m_strcpy(command, sizeof(command), entry->command);
425
426     if (fp) {
427       fname = m_strdup(a->filename);
428       mutt_sanitize_filename (fname, 1);
429     }
430     else
431       fname = a->filename;
432
433     if (rfc1524_expand_filename (entry->nametemplate, fname,
434                                  tempfile, sizeof (tempfile))) {
435       if (fp == NULL && m_strcmp(tempfile, a->filename)) {
436         /* send case: the file is already there */
437         if (safe_symlink (a->filename, tempfile) == -1) {
438           if (mutt_yesorno (_("Can't match nametemplate, continue?"), M_YES)
439               == M_YES)
440             m_strcpy(tempfile, sizeof(tempfile), a->filename);
441           else
442             goto return_error;
443         }
444         else
445           unlink_tempfile = 1;
446       }
447     }
448     else if (fp == NULL)        /* send case */
449       m_strcpy(tempfile, sizeof(tempfile), a->filename);
450
451     if (fp) {
452       /* recv case: we need to save the attachment to a file */
453       p_delete(&fname);
454       if (mutt_save_attachment (fp, a, tempfile, 0, NULL) == -1)
455         goto return_error;
456     }
457
458     use_pipe = rfc1524_expand_command (a, tempfile, type,
459                                        command, sizeof (command));
460     use_pager = entry->copiousoutput;
461   }
462
463   if (use_pager) {
464     if (fp && !use_mailcap && a->filename) {
465       /* recv case */
466       m_strcpy(pagerfile, sizeof(pagerfile), a->filename);
467       mutt_adv_mktemp (NULL, pagerfile, sizeof (pagerfile));
468     }
469     else
470       mutt_mktemp (pagerfile);
471   }
472
473   if (use_mailcap) {
474     pid_t thepid = 0;
475     int tempfd = -1, pagerfd = -1;
476
477     if (!use_pager)
478       mutt_endwin (NULL);
479
480     if (use_pager || use_pipe) {
481       if (use_pager
482           && ((pagerfd = safe_open (pagerfile, O_CREAT | O_EXCL | O_WRONLY))
483               == -1)) {
484         mutt_perror ("open");
485         goto return_error;
486       }
487       if (use_pipe && ((tempfd = open (tempfile, 0)) == -1)) {
488         if (pagerfd != -1)
489           close (pagerfd);
490         mutt_perror ("open");
491         goto return_error;
492       }
493
494       if ((thepid = mutt_create_filter_fd (command, NULL, NULL, NULL,
495                                            use_pipe ? tempfd : -1,
496                                            use_pager ? pagerfd : -1,
497                                            -1)) == -1) {
498         if (pagerfd != -1)
499           close (pagerfd);
500
501         if (tempfd != -1)
502           close (tempfd);
503
504         mutt_error _("Cannot create filter");
505
506         goto return_error;
507       }
508
509       if (use_pager) {
510         if (a->description)
511           snprintf (descrip, sizeof (descrip),
512                     "---Command: %-20.20s Description: %s",
513                     command, a->description);
514         else
515           snprintf (descrip, sizeof (descrip),
516                     "---Command: %-30.30s Attachment: %s", command, type);
517       }
518
519       if ((mutt_wait_filter (thepid) || (entry->needsterminal &&
520                                          option (OPTWAITKEY))) && !use_pager)
521         mutt_any_key_to_continue (NULL);
522
523       close (tempfd);
524       close (pagerfd);
525
526     }
527     else {
528       /* interactive command */
529       if (mutt_system (command) ||
530           (entry->needsterminal && option (OPTWAITKEY)))
531         mutt_any_key_to_continue (NULL);
532     }
533   }
534   else {
535     /* Don't use mailcap; the attachment is viewed in the pager */
536
537     if (flag == M_AS_TEXT) {
538       /* just let me see the raw data */
539       if (mutt_save_attachment (fp, a, pagerfile, 0, NULL))
540         goto return_error;
541     }
542     else {
543       /* Use built-in handler */
544       set_option (OPTVIEWATTACH);       /* disable the "use 'v' to view this part"
545                                          * message in case of error */
546       if (mutt_decode_save_attachment (fp, a, pagerfile, M_DISPLAY, 0)) {
547         unset_option (OPTVIEWATTACH);
548         goto return_error;
549       }
550       unset_option (OPTVIEWATTACH);
551     }
552
553     if (a->description)
554       m_strcpy(descrip, sizeof(descrip), a->description);
555     else if (a->filename)
556       snprintf (descrip, sizeof (descrip), "---Attachment: %s : %s",
557                 a->filename, type);
558     else
559       snprintf (descrip, sizeof (descrip), "---Attachment: %s", type);
560   }
561
562   /* We only reach this point if there have been no errors */
563
564   if (use_pager) {
565     pager_t info;
566     p_clear(&info, 1);
567
568     info.fp  = fp;
569     info.bdy = a;
570     info.ctx = Context;
571     info.idx = idx;
572     info.idxlen = idxlen;
573     info.hdr = hdr;
574
575     rc = mutt_do_pager(descrip, pagerfile,
576                        M_PAGER_ATTACHMENT | (is_message ? M_PAGER_MESSAGE : 0),
577                        &info);
578     *pagerfile = '\0';
579   }
580   else
581     rc = 0;
582
583 return_error:
584
585   if (entry)
586     rfc1524_entry_delete(&entry);
587   if (fp && tempfile[0])
588     mutt_unlink (tempfile);
589   else if (unlink_tempfile)
590     unlink (tempfile);
591
592   if (pagerfile[0])
593     mutt_unlink (pagerfile);
594
595   return rc;
596 }
597
598 /* returns 1 on success, 0 on error */
599 int mutt_pipe_attachment (FILE * fp, BODY * b, const char *path,
600                           char *outfile)
601 {
602   pid_t thepid;
603   int out = -1;
604   int rv = 0;
605
606   if (outfile && *outfile)
607     if ((out = safe_open (outfile, O_CREAT | O_EXCL | O_WRONLY)) < 0) {
608       mutt_perror ("open");
609       return 0;
610     }
611
612   mutt_endwin (NULL);
613
614   if (fp) {
615     /* recv case */
616     STATE s;
617     p_clear(&s, 1);
618
619     if (outfile && *outfile)
620       thepid = mutt_create_filter_fd(path, &s.fpout, NULL, NULL, -1, out, -1);
621     else
622       thepid = mutt_create_filter(path, &s.fpout, NULL, NULL);
623
624     if (thepid < 0) {
625       mutt_perror (_("Can't create filter"));
626
627       goto bail;
628     }
629
630     s.fpin = fp;
631     mutt_decode_attachment (b, &s);
632     safe_fclose (&s.fpout);
633   }
634   else {
635     /* send case */
636
637     FILE *ifp, *ofp;
638
639     if ((ifp = fopen (b->filename, "r")) == NULL) {
640       mutt_perror ("fopen");
641       if (outfile && *outfile) {
642         close (out);
643         unlink (outfile);
644       }
645       return 0;
646     }
647
648     if (outfile && *outfile)
649       thepid = mutt_create_filter_fd (path, &ofp, NULL, NULL, -1, out, -1);
650     else
651       thepid = mutt_create_filter (path, &ofp, NULL, NULL);
652
653     if (thepid < 0) {
654       mutt_perror (_("Can't create filter"));
655
656       safe_fclose (&ifp);
657       goto bail;
658     }
659
660     mutt_copy_stream (ifp, ofp);
661     safe_fclose (&ofp);
662     safe_fclose (&ifp);
663   }
664
665   rv = 1;
666
667 bail:
668
669   if (outfile && *outfile)
670     close (out);
671
672   /*
673    * check for error exit from child process
674    */
675   if (mutt_wait_filter (thepid) != 0)
676     rv = 0;
677
678   if (rv == 0 || option (OPTWAITKEY))
679     mutt_any_key_to_continue (NULL);
680   return rv;
681 }
682
683 static FILE *mutt_save_attachment_open (char *path, int flags)
684 {
685   if (flags == M_SAVE_APPEND)
686     return fopen (path, "a");
687   /* be sure not to change the following fopen to safe_fopen
688    * as safe_fopen returns w/ an error if path exists
689    */
690   if (flags == M_SAVE_OVERWRITE)
691     return fopen (path, "w");   /* __FOPEN_CHECKED__ */
692
693   return safe_fopen (path, "w");
694 }
695
696 /* returns 0 on success, -1 on error */
697 int mutt_save_attachment (FILE * fp, BODY * m, char *path, int flags,
698                           HEADER * hdr)
699 {
700   if (fp) {
701
702     /* recv mode */
703
704     if (hdr &&
705         m->hdr &&
706         m->encoding != ENCBASE64 &&
707         m->encoding != ENCQUOTEDPRINTABLE &&
708         mutt_is_message_type (m->type, m->subtype)) {
709       /* message type attachments are written to mail folders. */
710
711       char buf[HUGE_STRING];
712       HEADER *hn;
713       CONTEXT ctx;
714       MESSAGE *msg;
715       int chflags = 0;
716       int r = -1;
717
718       hn = m->hdr;
719       hn->msgno = hdr->msgno;   /* required for MH/maildir */
720       hn->read = 1;
721
722       fseeko (fp, m->offset, 0);
723       if (fgets (buf, sizeof (buf), fp) == NULL)
724         return -1;
725       if (mx_open_mailbox (path, M_APPEND | M_QUIET, &ctx) == NULL)
726         return -1;
727       if ((msg =
728            mx_open_new_message (&ctx, hn,
729                                 is_from (buf, NULL, 0,
730                                          NULL) ? 0 : M_ADD_FROM)) == NULL) {
731         mx_close_mailbox (&ctx, NULL);
732         return -1;
733       }
734       if (ctx.magic == M_MBOX || ctx.magic == M_MMDF)
735         chflags = CH_FROM;
736       chflags |= (ctx.magic == M_MAILDIR ? CH_NOSTATUS : CH_UPDATE);
737       if (_mutt_copy_message (msg->fp, fp, hn, hn->content, 0, chflags) == 0
738           && mx_commit_message (msg, &ctx) == 0)
739         r = 0;
740       else
741         r = -1;
742
743       mx_close_message (&msg);
744       mx_close_mailbox (&ctx, NULL);
745       return r;
746     }
747     else {
748       /* In recv mode, extract from folder and decode */
749
750       STATE s;
751       p_clear(&s, 1);
752
753       if ((s.fpout = mutt_save_attachment_open (path, flags)) == NULL) {
754         mutt_perror ("fopen");
755         return (-1);
756       }
757       fseeko ((s.fpin = fp), m->offset, 0);
758       mutt_decode_attachment (m, &s);
759
760       if (fclose (s.fpout) != 0) {
761         mutt_perror ("fclose");
762         return (-1);
763       }
764     }
765   }
766   else {
767     /* In send mode, just copy file */
768
769     FILE *ofp, *nfp;
770
771     if ((ofp = fopen (m->filename, "r")) == NULL) {
772       mutt_perror ("fopen");
773       return (-1);
774     }
775
776     if ((nfp = mutt_save_attachment_open (path, flags)) == NULL) {
777       mutt_perror ("fopen");
778       safe_fclose (&ofp);
779       return (-1);
780     }
781
782     if (mutt_copy_stream (ofp, nfp) == -1) {
783       mutt_error _("Write fault!");
784
785       safe_fclose (&ofp);
786       safe_fclose (&nfp);
787       return (-1);
788     }
789     safe_fclose (&ofp);
790     safe_fclose (&nfp);
791   }
792
793   return 0;
794 }
795
796 /* returns 0 on success, -1 on error */
797 int mutt_decode_save_attachment (FILE * fp, BODY * m, char *path,
798                                  int displaying, int flags)
799 {
800   STATE s;
801   unsigned int saved_encoding = 0;
802   BODY *saved_parts = NULL;
803   HEADER *saved_hdr = NULL;
804
805   p_clear(&s, 1);
806   s.flags = displaying;
807
808   if (flags == M_SAVE_APPEND)
809     s.fpout = fopen (path, "a");
810   else if (flags == M_SAVE_OVERWRITE)
811     s.fpout = safe_fopen (path, "w");   /* __FOPEN_CHECKED__ */
812   else
813     s.fpout = safe_fopen (path, "w");
814
815   if (s.fpout == NULL) {
816     mutt_perror ("fopen");
817     return (-1);
818   }
819
820   if (fp == NULL) {
821     /* When called from the compose menu, the attachment isn't parsed,
822      * so we need to do it here. */
823     struct stat st;
824
825     if (stat (m->filename, &st) == -1) {
826       mutt_perror ("stat");
827       fclose (s.fpout);
828       return (-1);
829     }
830
831     if ((s.fpin = fopen (m->filename, "r")) == NULL) {
832       mutt_perror ("fopen");
833       return (-1);
834     }
835
836     saved_encoding = m->encoding;
837     if (!is_multipart (m))
838       m->encoding = ENC8BIT;
839
840     m->length = st.st_size;
841     m->offset = 0;
842     saved_parts = m->parts;
843     saved_hdr = m->hdr;
844     mutt_parse_part (s.fpin, m);
845
846     if (m->noconv || is_multipart (m))
847       s.flags |= M_CHARCONV;
848   }
849   else {
850     s.fpin = fp;
851     s.flags |= M_CHARCONV;
852   }
853
854   mutt_body_handler (m, &s);
855
856   fclose (s.fpout);
857   if (fp == NULL) {
858     m->length = 0;
859     m->encoding = saved_encoding;
860     if (saved_parts) {
861       header_delete(&m->hdr);
862       m->parts = saved_parts;
863       m->hdr = saved_hdr;
864     }
865     fclose (s.fpin);
866   }
867
868   return (0);
869 }
870
871 /* Ok, the difference between send and receive:
872  * recv: BODY->filename is a suggested name, and Context|HEADER points
873  *       to the attachment in mailbox which is encooded
874  * send: BODY->filename points to the un-encoded file which contains the 
875  *       attachment
876  */
877
878 int mutt_print_attachment (FILE * fp, BODY * a)
879 {
880   char newfile[_POSIX_PATH_MAX] = "";
881   char type[STRING];
882   pid_t thepid;
883   FILE *ifp, *fpout;
884   short unlink_newfile = 0;
885
886   snprintf (type, sizeof (type), "%s/%s", TYPE (a), a->subtype);
887
888   if (rfc1524_mailcap_lookup (a, type, NULL, M_PRINT)) {
889     char command[_POSIX_PATH_MAX + STRING];
890     rfc1524_entry *entry;
891     int piped = FALSE;
892
893     entry = rfc1524_entry_new();
894     rfc1524_mailcap_lookup (a, type, entry, M_PRINT);
895     if (rfc1524_expand_filename (entry->nametemplate, a->filename,
896                                  newfile, sizeof (newfile))) {
897       if (!fp) {
898         if (safe_symlink (a->filename, newfile) == -1) {
899           if (mutt_yesorno (_("Can't match nametemplate, continue?"), M_YES)
900               != M_YES) {
901             rfc1524_entry_delete(&entry);
902             return 0;
903           }
904           m_strcpy(newfile, sizeof(newfile), a->filename);
905         }
906         else
907           unlink_newfile = 1;
908       }
909     }
910
911     /* in recv mode, save file to newfile first */
912     if (fp)
913       mutt_save_attachment (fp, a, newfile, 0, NULL);
914
915     m_strcpy(command, sizeof(command), entry->printcommand);
916     piped = rfc1524_expand_command(a, newfile, type, command,
917                                    sizeof(command));
918
919     mutt_endwin (NULL);
920
921     /* interactive program */
922     if (piped) {
923       if ((ifp = fopen (newfile, "r")) == NULL) {
924         mutt_perror ("fopen");
925         rfc1524_entry_delete(&entry);
926         return (0);
927       }
928
929       if ((thepid = mutt_create_filter (command, &fpout, NULL, NULL)) < 0) {
930         mutt_perror (_("Can't create filter"));
931
932         rfc1524_entry_delete(&entry);
933         safe_fclose (&ifp);
934         return 0;
935       }
936       mutt_copy_stream (ifp, fpout);
937       safe_fclose (&fpout);
938       safe_fclose (&ifp);
939       if (mutt_wait_filter (thepid) || option (OPTWAITKEY))
940         mutt_any_key_to_continue (NULL);
941     }
942     else {
943       if (mutt_system (command) || option (OPTWAITKEY))
944         mutt_any_key_to_continue (NULL);
945     }
946
947     if (fp)
948       mutt_unlink (newfile);
949     else if (unlink_newfile)
950       unlink (newfile);
951
952     rfc1524_entry_delete(&entry);
953     return (1);
954   }
955
956   if (!ascii_strcasecmp ("text/plain", type) ||
957       !ascii_strcasecmp ("application/postscript", type)) {
958     return (mutt_pipe_attachment (fp, a, NONULL (PrintCmd), NULL));
959   }
960   else if (mutt_can_decode (a)) {
961     /* decode and print */
962
963     int rc = 0;
964
965     ifp = NULL;
966     fpout = NULL;
967
968     mutt_mktemp (newfile);
969     if (mutt_decode_save_attachment (fp, a, newfile, M_PRINTING, 0) == 0) {
970
971       if ((ifp = fopen (newfile, "r")) == NULL) {
972         mutt_perror ("fopen");
973         goto bail0;
974       }
975
976       mutt_endwin (NULL);
977       if ((thepid =
978            mutt_create_filter (NONULL (PrintCmd), &fpout, NULL, NULL)) < 0) {
979         mutt_perror (_("Can't create filter"));
980
981         goto bail0;
982       }
983
984       mutt_copy_stream (ifp, fpout);
985
986       safe_fclose (&fpout);
987       safe_fclose (&ifp);
988
989       if (mutt_wait_filter (thepid) != 0 || option (OPTWAITKEY))
990         mutt_any_key_to_continue (NULL);
991       rc = 1;
992     }
993   bail0:
994     safe_fclose (&ifp);
995     safe_fclose (&fpout);
996     mutt_unlink (newfile);
997     return rc;
998   }
999   else {
1000     mutt_error _("I don't know how to print that!");
1001
1002     return 0;
1003   }
1004 }
1005
1006 int mutt_attach_check (HEADER* hdr) {
1007   int found = 0;
1008   char buf[LONG_STRING];
1009   char *p = NULL;
1010   FILE* fp = NULL;
1011   regmatch_t pmatch[1];
1012
1013   if (!hdr || !hdr->content || !((regex_t*) AttachRemindRegexp.rx) ||
1014       (fp = safe_fopen (hdr->content->filename, "r")) == NULL)
1015     return (0);
1016
1017   while (!found && fgets (buf, sizeof (buf), fp)) {
1018     p = buf;
1019     while (p && *p) {
1020       if (regexec ((regex_t*) AttachRemindRegexp.rx, p, 1,
1021                   pmatch, 0) == 0) {
1022         found = 1;
1023         break;
1024       }
1025       p++;
1026     }
1027   }
1028   fclose (fp);
1029
1030   return (found);
1031 }