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