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