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