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