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