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