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