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