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