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