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