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