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