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