Andreas Krennmair:
[apps/madmutt.git] / recvattach.c
1 /*
2  * Copyright (C) 1996-2000 Michael R. Elkins <me@mutt.org>
3  * Copyright (C) 1999-2000 Thomas Roessler <roessler@does-not-exist.org>
4  * 
5  *     This program is free software; you can redistribute it and/or modify
6  *     it under the terms of the GNU General Public License as published by
7  *     the Free Software Foundation; either version 2 of the License, or
8  *     (at your option) any later version.
9  * 
10  *     This program is distributed in the hope that it will be useful,
11  *     but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *     GNU General Public License for more details.
14  * 
15  *     You should have received a copy of the GNU General Public License
16  *     along with this program; if not, write to the Free Software
17  *     Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
18  */ 
19
20 #include "mutt.h"
21 #include "mutt_curses.h"
22 #include "mutt_menu.h"
23 #include "rfc1524.h"
24 #include "mime.h"
25 #include "mailbox.h"
26 #include "attach.h"
27 #include "mapping.h"
28 #include "mx.h"
29 #include "copy.h"
30 #include "mutt_crypt.h"
31
32 #include <ctype.h>
33 #include <stdlib.h>
34 #include <unistd.h>
35 #include <sys/wait.h>
36 #include <sys/stat.h>
37 #include <string.h>
38 #include <errno.h>
39
40 static const char *Mailbox_is_read_only = N_("Mailbox is read-only.");
41 static char LastSaveFolder[_POSIX_PATH_MAX] = "";
42
43 #define CHECK_READONLY if (Context->readonly) \
44 {\
45     mutt_flushinp (); \
46     mutt_error _(Mailbox_is_read_only); \
47     break; \
48 }
49
50 static struct mapping_t AttachHelp[] = {
51   { N_("Exit"),  OP_EXIT },
52   { N_("Save"),  OP_SAVE },
53   { N_("Pipe"),  OP_PIPE },
54   { N_("Print"), OP_PRINT },
55   { N_("Help"),  OP_HELP },
56   { NULL }
57 };
58
59 int mutt_extract_path(char *filename, char *path)
60 {
61   char *tmp=safe_malloc(sizeof(char) * _POSIX_PATH_MAX);
62   char *help_ptr;
63   
64   help_ptr = tmp;
65
66   while(*filename != '\0')
67   {
68     if (*filename == '/')
69     {
70       *help_ptr++=*filename++;
71       *help_ptr++='\0';
72       strcat(path, tmp);
73       help_ptr = tmp;
74     }
75     *help_ptr++=*filename++;
76   }
77   safe_free((void **) &tmp);
78     
79   return 0;
80 }
81
82 void mutt_update_tree (ATTACHPTR **idx, short idxlen)
83 {
84   char buf[STRING];
85   char *s;
86   int x;
87
88   for (x = 0; x < idxlen; x++)
89   {
90     idx[x]->num = x;
91     if (2 * (idx[x]->level + 2) < sizeof (buf))
92     {
93       if (idx[x]->level)
94       {
95         s = buf + 2 * (idx[x]->level - 1);
96         *s++ = (idx[x]->content->next) ? M_TREE_LTEE : M_TREE_LLCORNER;
97         *s++ = M_TREE_HLINE;
98         *s++ = M_TREE_RARROW;
99       }
100       else
101         s = buf;
102       *s = 0;
103     }
104
105     if (idx[x]->tree)
106     {
107       if (mutt_strcmp (idx[x]->tree, buf) != 0)
108         mutt_str_replace (&idx[x]->tree, buf);
109     }
110     else
111       idx[x]->tree = safe_strdup (buf);
112
113     if (2 * (idx[x]->level + 2) < sizeof (buf) && idx[x]->level)
114     {
115       s = buf + 2 * (idx[x]->level - 1);
116       *s++ = (idx[x]->content->next) ? '\005' : '\006';
117       *s++ = '\006';
118     }
119   }
120 }
121
122 ATTACHPTR **mutt_gen_attach_list (BODY *m,
123                                   int parent_type,
124                                   ATTACHPTR **idx,
125                                   short *idxlen,
126                                   short *idxmax,
127                                   int level,
128                                   int compose)
129 {
130   ATTACHPTR *new;
131   int i;
132   
133   for (; m; m = m->next)
134   {
135     if (*idxlen == *idxmax)
136     {
137       safe_realloc (&idx, sizeof (ATTACHPTR *) * ((*idxmax) += 5));
138       for (i = *idxlen; i < *idxmax; i++)
139         idx[i] = NULL;
140     }
141
142     if (m->type == TYPEMULTIPART && m->parts
143         && (compose || (parent_type == -1 && ascii_strcasecmp ("alternative", m->subtype)))
144         && (!(WithCrypto & APPLICATION_PGP) || !mutt_is_multipart_encrypted(m))
145         )
146     {
147       idx = mutt_gen_attach_list (m->parts, m->type, idx, idxlen, idxmax, level, compose);
148     }
149     else
150     {
151       if (!idx[*idxlen])
152         idx[*idxlen] = (ATTACHPTR *) safe_calloc (1, sizeof (ATTACHPTR));
153
154       new = idx[(*idxlen)++];
155       new->content = m;
156       m->aptr = new;
157       new->parent_type = parent_type;
158       new->level = level;
159
160       /* We don't support multipart messages in the compose menu yet */
161       if (!compose && !m->collapsed && 
162           ((m->type == TYPEMULTIPART
163             && (!(WithCrypto & APPLICATION_PGP)
164                 || !mutt_is_multipart_encrypted (m))
165             )
166            || mutt_is_message_type(m->type, m->subtype)))
167       {
168         idx = mutt_gen_attach_list (m->parts, m->type, idx, idxlen, idxmax, level + 1, compose);
169       }
170     }
171   }
172
173   if (level == 0)
174     mutt_update_tree (idx, *idxlen);
175
176   return (idx);
177 }
178
179 /* %c = character set: convert?
180  * %C = character set
181  * %D = deleted flag
182  * %d = description
183  * %e = MIME content-transfer-encoding
184  * %f = filename
185  * %I = content-disposition, either I (inline) or A (attachment)
186  * %t = tagged flag
187  * %T = tree chars
188  * %m = major MIME type
189  * %M = MIME subtype
190  * %n = attachment number
191  * %s = size
192  * %u = unlink 
193  */
194 const char *mutt_attach_fmt (char *dest,
195     size_t destlen,
196     char op,
197     const char *src,
198     const char *prefix,
199     const char *ifstring,
200     const char *elsestring,
201     unsigned long data,
202     format_flag flags)
203 {
204   char fmt[16];
205   char tmp[SHORT_STRING];
206   char charset[SHORT_STRING];
207   ATTACHPTR *aptr = (ATTACHPTR *) data;
208   int optional = (flags & M_FORMAT_OPTIONAL);
209   size_t l;
210   
211   switch (op)
212   {
213     case 'C':
214       if (!optional)
215       {
216         if (mutt_is_text_part (aptr->content) &&
217             mutt_get_body_charset (charset, sizeof (charset), aptr->content))
218           mutt_format_s (dest, destlen, prefix, charset);
219         else
220           mutt_format_s (dest, destlen, prefix, "");
221       }
222       else if (!mutt_is_text_part (aptr->content) ||
223                !mutt_get_body_charset (charset, sizeof (charset), aptr->content))
224         optional = 0;
225       break;
226     case 'c':
227       /* XXX */
228       if (!optional)
229       {
230         snprintf (fmt, sizeof (fmt), "%%%sc", prefix);
231         snprintf (dest, destlen, fmt, aptr->content->type != TYPETEXT ||
232                   aptr->content->noconv ? 'n' : 'c');
233       }
234       else if (aptr->content->type != TYPETEXT || aptr->content->noconv)
235         optional = 0;
236       break;
237     case 'd':
238       if(!optional)
239       {
240         if (aptr->content->description)
241         {
242           mutt_format_s (dest, destlen, prefix, aptr->content->description);
243           break;
244         }
245         if (mutt_is_message_type(aptr->content->type, aptr->content->subtype) &&
246             MsgFmt && aptr->content->hdr)
247         {
248           char s[SHORT_STRING];
249           _mutt_make_string (s, sizeof (s), MsgFmt, NULL, aptr->content->hdr,
250                              M_FORMAT_FORCESUBJ | M_FORMAT_MAKEPRINT | M_FORMAT_ARROWCURSOR);
251           if (*s)
252           {
253             mutt_format_s (dest, destlen, prefix, s);
254             break;
255           }
256         }
257         if (!aptr->content->filename)
258         {
259           mutt_format_s (dest, destlen, prefix, "<no description>");
260           break;
261         }
262       }
263       else if(aptr->content->description || 
264               (mutt_is_message_type (aptr->content->type, aptr->content->subtype)
265               && MsgFmt && aptr->content->hdr))
266         break;
267     /* FALLS THROUGH TO 'f' */
268     case 'f':
269       if(!optional)
270       {
271         if (aptr->content->filename && *aptr->content->filename == '/')
272         {
273           char path[_POSIX_PATH_MAX];
274           
275           strfcpy (path, aptr->content->filename, sizeof (path));
276           mutt_pretty_mailbox (path);
277           mutt_format_s (dest, destlen, prefix, path);
278         }
279         else
280           mutt_format_s (dest, destlen, prefix, NONULL (aptr->content->filename));
281       }
282       else if(!aptr->content->filename)
283         optional = 0;
284       break;
285     case 'D':
286       if(!optional)
287         snprintf (dest, destlen, "%c", aptr->content->deleted ? 'D' : ' ');
288       else if(!aptr->content->deleted)
289         optional = 0;
290       break;
291     case 'e':
292       if(!optional)
293         mutt_format_s (dest, destlen, prefix,
294                       ENCODING (aptr->content->encoding));
295       break;
296     case 'I':
297       if (!optional)
298       {
299           snprintf (dest, destlen, "%c",
300                   (aptr->content->disposition == DISPINLINE) ? 'I' : 'A');
301       }
302       break;
303     case 'm':
304       if(!optional)
305         mutt_format_s (dest, destlen, prefix, TYPE (aptr->content));
306       break;
307     case 'M':
308       if(!optional)
309         mutt_format_s (dest, destlen, prefix, aptr->content->subtype);
310       else if(!aptr->content->subtype)
311         optional = 0;
312       break;
313     case 'n':
314       if(!optional)
315       {
316         snprintf (fmt, sizeof (fmt), "%%%sd", prefix);
317         snprintf (dest, destlen, fmt, aptr->num + 1);
318       }
319       break;
320     case 's':
321       if (flags & M_FORMAT_STAT_FILE)
322       {
323         struct stat st;
324         stat (aptr->content->filename, &st);
325         l = st.st_size;
326       }
327       else
328         l = aptr->content->length;
329       
330       if(!optional)
331       {
332         mutt_pretty_size (tmp, sizeof(tmp), l);
333         mutt_format_s (dest, destlen, prefix, tmp);
334       }
335       else if (l == 0)
336         optional = 0;
337
338       break;
339     case 't':
340       if(!optional)
341         snprintf (dest, destlen, "%c", aptr->content->tagged ? '*' : ' ');
342       else if(!aptr->content->tagged)
343         optional = 0;
344       break;
345     case 'T':
346       if(!optional)
347         mutt_format_s_tree (dest, destlen, prefix, NONULL (aptr->tree));
348       else if (!aptr->tree)
349         optional = 0;
350       break;
351     case 'u':
352       if(!optional)
353         snprintf (dest, destlen, "%c", aptr->content->unlink ? '-' : ' ');
354       else if (!aptr->content->unlink)
355         optional = 0;
356       break;
357     default:
358       *dest = 0;
359   }
360   
361   if (optional)
362     mutt_FormatString (dest, destlen, ifstring, mutt_attach_fmt, data, 0);
363   else if (flags & M_FORMAT_OPTIONAL)
364     mutt_FormatString (dest, destlen, elsestring, mutt_attach_fmt, data, 0);
365   return (src);
366 }
367
368 void attach_entry (char *b, size_t blen, MUTTMENU *menu, int num)
369 {
370   mutt_FormatString (b, blen, NONULL (AttachFormat), mutt_attach_fmt, (unsigned long) (((ATTACHPTR **)menu->data)[num]), M_FORMAT_ARROWCURSOR);
371 }
372
373 int mutt_tag_attach (MUTTMENU *menu, int n, int m)
374 {
375   BODY *cur = ((ATTACHPTR **) menu->data)[n]->content;
376   int ot = cur->tagged;
377   
378   cur->tagged = (m >= 0 ? m : !cur->tagged);
379   return cur->tagged - ot;
380 }
381
382 int mutt_is_message_type (int type, const char *subtype)
383 {
384   if (type != TYPEMESSAGE)
385     return 0;
386
387   subtype = NONULL(subtype);
388   return (ascii_strcasecmp (subtype, "rfc822") == 0 || ascii_strcasecmp (subtype, "news") == 0);
389 }
390
391 static int mutt_query_save_attachment (FILE *fp, BODY *body, HEADER *hdr, char **directory)
392 {
393   char *prompt;
394   char buf[_POSIX_PATH_MAX], tfile[_POSIX_PATH_MAX];
395   char path[_POSIX_PATH_MAX]="";  
396   int is_message;
397   int append = 0;
398   int rc;
399   int ret = -1;
400   
401   if (body->filename) 
402   {
403     if (directory && *directory)
404       mutt_concat_path (buf, *directory, mutt_basename (body->filename), sizeof (buf));
405     else
406       strfcpy (buf, body->filename, sizeof (buf));
407   }
408   else if(body->hdr &&
409           body->encoding != ENCBASE64 &&
410           body->encoding != ENCQUOTEDPRINTABLE &&
411           mutt_is_message_type(body->type, body->subtype))
412     mutt_default_save(buf, sizeof(buf), body->hdr);
413   else
414     buf[0] = 0;
415
416   prompt = _("Save to file ('.' for last used folder): ");
417   while (prompt)
418   {
419     ret = mutt_get_field (prompt, buf, sizeof (buf), M_FILE | M_CLEAR);
420     if (((ret != 0) && (ret != 2)) || (!buf[0]))
421       return -1;
422
423     if (ret == 2)
424     {
425       strfcpy (buf, LastSaveFolder, sizeof (buf));
426       strcat(buf,body->filename);
427       ret = mutt_get_field (_("Save to file: ")
428                 , buf, sizeof (buf), M_FILE | M_CLEAR);
429       if ((ret != 0) || (!buf[0]))
430       return -1;
431     }  
432     else
433     {
434       mutt_extract_path(buf,path);
435       strfcpy (LastSaveFolder, path, sizeof (LastSaveFolder));
436     }
437     
438     prompt = NULL;
439     mutt_expand_path (buf, sizeof (buf));
440     
441     is_message = (fp && 
442                   body->hdr && 
443                   body->encoding != ENCBASE64 && 
444                   body->encoding != ENCQUOTEDPRINTABLE && 
445                   mutt_is_message_type (body->type, body->subtype));
446     
447     if (is_message)
448     {
449       struct stat st;
450       
451       /* check to make sure that this file is really the one the user wants */
452       if ((rc = mutt_save_confirm (buf, &st)) == 1)
453       {
454         prompt = _("Save to file: ");
455         continue;
456       } 
457       else if (rc == -1)
458         return -1;
459       strfcpy(tfile, buf, sizeof(tfile));
460     }
461     else
462     {
463       if ((rc = mutt_check_overwrite (body->filename, buf, tfile, sizeof (tfile), &append, directory)) == -1)
464         return -1;
465       else if (rc == 1)
466       {
467         prompt = _("Save to file: ");
468         continue;
469       }
470     }
471     
472     mutt_message _("Saving...");
473     if (mutt_save_attachment (fp, body, tfile, append, (hdr || !is_message) ? hdr : body->hdr) == 0)
474     {
475       mutt_message _("Attachment saved.");
476       return 0;
477     }
478     else
479     {
480       prompt = _("Save to file: ");
481       continue;
482     }
483   }
484   return 0;
485 }
486     
487 void mutt_save_attachment_list (FILE *fp, int tag, BODY *top, HEADER *hdr, MUTTMENU *menu)
488 {
489   char buf[_POSIX_PATH_MAX], tfile[_POSIX_PATH_MAX];
490   char *directory = NULL;
491   int rc = 1;
492   int last = menu ? menu->current : -1;
493   FILE *fpout;
494
495   buf[0] = 0;
496
497   for (; top; top = top->next)
498   {
499     if (!tag || top->tagged)
500     {
501       if (!option (OPTATTACHSPLIT))
502       {
503         if (!buf[0])
504         {
505           int append = 0;
506
507           strfcpy (buf, NONULL (top->filename), sizeof (buf));
508           if (mutt_get_field (_("Save to file: "), buf, sizeof (buf),
509                                     M_FILE | M_CLEAR) != 0 || !buf[0])
510             return;
511           mutt_expand_path (buf, sizeof (buf));
512           if (mutt_check_overwrite (top->filename, buf, tfile,
513                                     sizeof (tfile), &append, NULL))
514             return;
515           rc = mutt_save_attachment (fp, top, tfile, append, hdr);
516           if (rc == 0 && AttachSep && (fpout = fopen (tfile,"a")) != NULL)
517           {
518             fprintf(fpout, "%s", AttachSep);
519             fclose (fpout);
520           }
521         }
522         else
523         {
524           rc = mutt_save_attachment (fp, top, tfile, M_SAVE_APPEND, hdr);
525           if (rc == 0 && AttachSep && (fpout = fopen (tfile,"a")) != NULL)
526           {
527             fprintf(fpout, "%s", AttachSep);
528             fclose (fpout);
529           }
530         }
531       }
532       else 
533       {
534         if (tag && menu && top->aptr)
535         {
536           menu->oldcurrent = menu->current;
537           menu->current = top->aptr->num;
538           menu_check_recenter (menu);
539           menu->redraw |= REDRAW_MOTION;
540
541           menu_redraw (menu);
542         }
543         if (mutt_query_save_attachment (fp, top, hdr, &directory) == -1)
544           break;
545       }
546     }
547     else if (top->parts)
548       mutt_save_attachment_list (fp, 1, top->parts, hdr, menu);
549     if (!tag)
550       break;
551   }
552
553   FREE (&directory);
554
555   if (tag && menu)
556   {
557     menu->oldcurrent = menu->current;
558     menu->current = last;
559     menu_check_recenter (menu);
560     menu->redraw |= REDRAW_MOTION;
561   }
562   
563   if (!option (OPTATTACHSPLIT) && (rc == 0))
564     mutt_message _("Attachment saved.");
565 }
566
567 static void
568 mutt_query_pipe_attachment (char *command, FILE *fp, BODY *body, int filter)
569 {
570   char tfile[_POSIX_PATH_MAX];
571   char warning[STRING+_POSIX_PATH_MAX];
572
573   if (filter)
574   {
575     snprintf (warning, sizeof (warning),
576               _("WARNING!  You are about to overwrite %s, continue?"),
577               body->filename);
578     if (mutt_yesorno (warning, M_NO) != M_YES) {
579       CLEARLINE (LINES-1);
580       return;
581     }
582     mutt_mktemp (tfile);
583   }
584   else
585     tfile[0] = 0;
586
587   if (mutt_pipe_attachment (fp, body, command, tfile))
588   {
589     if (filter)
590     {
591       mutt_unlink (body->filename);
592       mutt_rename_file (tfile, body->filename);
593       mutt_update_encoding (body);
594       mutt_message _("Attachment filtered.");
595     }
596   }
597   else
598   {
599     if (filter && tfile[0])
600       mutt_unlink (tfile);
601   }
602 }
603
604 static void pipe_attachment (FILE *fp, BODY *b, STATE *state)
605 {
606   FILE *ifp;
607
608   if (fp)
609   {
610     state->fpin = fp;
611     mutt_decode_attachment (b, state);
612     if (AttachSep)
613       state_puts (AttachSep, state);
614   }
615   else
616   {
617     if ((ifp = fopen (b->filename, "r")) == NULL)
618     {
619       mutt_perror ("fopen");
620       return;
621     }
622     mutt_copy_stream (ifp, state->fpout);
623     fclose (ifp);
624     if (AttachSep)
625       state_puts (AttachSep, state);
626   }
627 }
628
629 static void
630 pipe_attachment_list (char *command, FILE *fp, int tag, BODY *top, int filter,
631                       STATE *state)
632 {
633   for (; top; top = top->next)
634   {
635     if (!tag || top->tagged)
636     {
637       if (!filter && !option (OPTATTACHSPLIT))
638         pipe_attachment (fp, top, state);
639       else
640         mutt_query_pipe_attachment (command, fp, top, filter);
641     }
642     else if (top->parts)
643       pipe_attachment_list (command, fp, tag, top->parts, filter, state);
644     if (!tag)
645       break;
646   }
647 }
648
649 void mutt_pipe_attachment_list (FILE *fp, int tag, BODY *top, int filter)
650 {
651   STATE state;
652   char buf[SHORT_STRING];
653   pid_t thepid;
654
655   if (fp)
656     filter = 0; /* sanity check: we can't filter in the recv case yet */
657
658   buf[0] = 0;
659   memset (&state, 0, sizeof (STATE));
660
661   if (mutt_get_field ((filter ? _("Filter through: ") : _("Pipe to: ")),
662                                   buf, sizeof (buf), M_CMD) != 0 || !buf[0])
663     return;
664
665   mutt_expand_path (buf, sizeof (buf));
666
667   if (!filter && !option (OPTATTACHSPLIT))
668   {
669     mutt_endwin (NULL);
670     thepid = mutt_create_filter (buf, &state.fpout, NULL, NULL);
671     pipe_attachment_list (buf, fp, tag, top, filter, &state);
672     fclose (state.fpout);
673     if (mutt_wait_filter (thepid) != 0 || option (OPTWAITKEY))
674       mutt_any_key_to_continue (NULL);
675   }
676   else
677     pipe_attachment_list (buf, fp, tag, top, filter, &state);
678 }
679
680 static int can_print (BODY *top, int tag)
681 {
682   char type [STRING];
683
684   for (; top; top = top->next)
685   {
686     snprintf (type, sizeof (type), "%s/%s", TYPE (top), top->subtype);
687     if (!tag || top->tagged)
688     {
689       if (!rfc1524_mailcap_lookup (top, type, NULL, M_PRINT))
690       {
691         if (ascii_strcasecmp ("text/plain", top->subtype) &&
692             ascii_strcasecmp ("application/postscript", top->subtype))
693         {
694           if (!mutt_can_decode (top))
695           {
696             mutt_error (_("I dont know how to print %s attachments!"), type);
697             return (0);
698           }
699         }
700       }
701     }
702     else if (top->parts)
703       return (can_print (top->parts, tag));
704     if (!tag)
705       break;
706   }
707   return (1);
708 }
709
710 static void print_attachment_list (FILE *fp, int tag, BODY *top, STATE *state)
711 {
712   char type [STRING];
713
714
715   for (; top; top = top->next)
716   {
717     if (!tag || top->tagged)
718     {
719       snprintf (type, sizeof (type), "%s/%s", TYPE (top), top->subtype);
720       if (!option (OPTATTACHSPLIT) && !rfc1524_mailcap_lookup (top, type, NULL, M_PRINT))
721       {
722         if (!ascii_strcasecmp ("text/plain", top->subtype) ||
723             !ascii_strcasecmp ("application/postscript", top->subtype))
724           pipe_attachment (fp, top, state);
725         else if (mutt_can_decode (top))
726         {
727           /* decode and print */
728
729           char newfile[_POSIX_PATH_MAX] = "";
730           FILE *ifp;
731
732           mutt_mktemp (newfile);
733           if (mutt_decode_save_attachment (fp, top, newfile, M_PRINTING, 0) == 0)
734           {
735             if ((ifp = fopen (newfile, "r")) != NULL)
736             {
737               mutt_copy_stream (ifp, state->fpout);
738               fclose (ifp);
739               if (AttachSep)
740                 state_puts (AttachSep, state);
741             }
742           }
743           mutt_unlink (newfile);
744         }
745       }
746       else
747         mutt_print_attachment (fp, top);
748     }
749     else if (top->parts)
750       print_attachment_list (fp, tag, top->parts, state);
751     if (!tag)
752       return;
753   }
754 }
755
756 void mutt_print_attachment_list (FILE *fp, int tag, BODY *top)
757 {
758   STATE state;
759   
760   pid_t thepid;
761   if (query_quadoption (OPT_PRINT, tag ? _("Print tagged attachment(s)?") : _("Print attachment?")) != M_YES)
762     return;
763
764   if (!option (OPTATTACHSPLIT))
765   {
766     if (!can_print (top, tag))
767       return;
768     mutt_endwin (NULL);
769     memset (&state, 0, sizeof (STATE));
770     thepid = mutt_create_filter (NONULL (PrintCmd), &state.fpout, NULL, NULL);
771     print_attachment_list (fp, tag, top, &state);
772     fclose (state.fpout);
773     if (mutt_wait_filter (thepid) != 0 || option (OPTWAITKEY))
774       mutt_any_key_to_continue (NULL);
775   }
776   else
777     print_attachment_list (fp, tag, top, &state);
778 }
779
780 void
781 mutt_update_attach_index (BODY *cur, ATTACHPTR ***idxp,
782                                       short *idxlen, short *idxmax,
783                                       MUTTMENU *menu)
784 {
785   ATTACHPTR **idx = *idxp;
786   while (--(*idxlen) >= 0)
787     idx[(*idxlen)]->content = NULL;
788   *idxlen = 0;
789
790   idx = *idxp = mutt_gen_attach_list (cur, -1, idx, idxlen, idxmax, 0, 0);
791   
792   menu->max  = *idxlen;
793   menu->data = *idxp;
794
795   if (menu->current >= menu->max)
796     menu->current = menu->max - 1;
797   menu_check_recenter (menu);
798   menu->redraw |= REDRAW_INDEX;
799   
800 }
801
802
803 int
804 mutt_attach_display_loop (MUTTMENU *menu, int op, FILE *fp, HEADER *hdr,
805                           BODY *cur, ATTACHPTR ***idxp, short *idxlen, short *idxmax,
806                           int recv)
807 {
808   ATTACHPTR **idx = *idxp;
809 #if 0
810   int old_optweed = option (OPTWEED);
811   set_option (OPTWEED);
812 #endif
813   
814   do
815   {
816     switch (op)
817     {
818       case OP_DISPLAY_HEADERS:
819         toggle_option (OPTWEED);
820         /* fall through */
821
822       case OP_VIEW_ATTACH:
823         op = mutt_view_attachment (fp, idx[menu->current]->content, M_REGULAR,
824                                    hdr, idx, *idxlen);
825         break;
826
827       case OP_NEXT_ENTRY:
828       case OP_MAIN_NEXT_UNDELETED: /* hack */
829         if (menu->current < menu->max - 1)
830         {
831           menu->current++;
832           op = OP_VIEW_ATTACH;
833         }
834         else
835           op = OP_NULL;
836         break;
837       case OP_PREV_ENTRY:
838       case OP_MAIN_PREV_UNDELETED: /* hack */
839         if (menu->current > 0)
840         {
841           menu->current--;
842           op = OP_VIEW_ATTACH;
843         }
844         else
845           op = OP_NULL;
846         break;
847       case OP_EDIT_TYPE:
848         /* when we edit the content-type, we should redisplay the attachment
849            immediately */
850         mutt_edit_content_type (hdr, idx[menu->current]->content, fp);
851         if (idxmax)
852         {
853           mutt_update_attach_index (cur, idxp, idxlen, idxmax, menu);
854           idx = *idxp;
855         }
856         op = OP_VIEW_ATTACH;
857         break;
858       /* functions which are passed through from the pager */
859       case OP_CHECK_TRADITIONAL:
860         if (!(WithCrypto & APPLICATION_PGP) || (hdr && hdr->security & PGP_TRADITIONAL_CHECKED))
861         {
862           op = OP_NULL;
863           break;
864         }
865         /* fall through */
866       case OP_ATTACH_COLLAPSE:
867         if (recv)
868           return op;
869       default:
870         op = OP_NULL;
871     }
872   }
873   while (op != OP_NULL);
874
875 #if 0
876   if (option (OPTWEED) != old_optweed)
877     toggle_option (OPTWEED);
878 #endif
879   return op;
880 }
881
882 static void attach_collapse (BODY *b, short collapse, short init, short just_one)
883 {
884   short i;
885   for (; b; b = b->next)
886   {
887     i = init || b->collapsed;
888     if (i && option (OPTDIGESTCOLLAPSE) && b->type == TYPEMULTIPART
889         && !ascii_strcasecmp (b->subtype, "digest"))
890       attach_collapse (b->parts, 1, 1, 0);
891     else if (b->type == TYPEMULTIPART || mutt_is_message_type (b->type, b->subtype))
892       attach_collapse (b->parts, collapse, i, 0);
893     b->collapsed = collapse;
894     if (just_one)
895       return;
896   }
897 }
898
899 void mutt_attach_init (BODY *b)
900 {
901   for (; b; b = b->next)
902   {
903     b->tagged = 0;
904     b->collapsed = 0;
905     if (b->parts) 
906       mutt_attach_init (b->parts);
907   }
908 }
909
910 static const char *Function_not_permitted = N_("Function not permitted in attach-message mode.");
911
912 #define CHECK_ATTACH if(option(OPTATTACHMSG)) \
913                      {\
914                         mutt_flushinp (); \
915                         mutt_error _(Function_not_permitted); \
916                         break; \
917                      }
918
919
920
921
922 void mutt_view_attachments (HEADER *hdr)
923 {
924   int secured = 0;
925   int need_secured = 0;
926
927   char helpstr[SHORT_STRING];
928   MUTTMENU *menu;
929   BODY *cur;
930   MESSAGE *msg;
931   FILE *fp;
932   ATTACHPTR **idx = NULL;
933   short idxlen = 0;
934   short idxmax = 0;
935   int flags = 0;
936   int op = OP_NULL;
937   
938   /* make sure we have parsed this message */
939   mutt_parse_mime_message (Context, hdr);
940
941   mutt_message_hook (Context, hdr, M_MESSAGEHOOK);
942   
943   if ((msg = mx_open_message (Context, hdr->msgno)) == NULL)
944     return;
945
946
947   if (WithCrypto && ((hdr->security & ENCRYPT) ||
948                      (mutt_is_application_smime(hdr->content) & SMIMEOPAQUE)))
949   {
950     need_secured  = 1;
951
952     if ((hdr->security & ENCRYPT) && !crypt_valid_passphrase(hdr->security))
953     {
954       mx_close_message (&msg);
955       return;
956     }
957     if ((WithCrypto & APPLICATION_SMIME) && (hdr->security & APPLICATION_SMIME))
958     {
959       if (hdr->env)
960           crypt_smime_getkeys (hdr->env);
961
962       if (mutt_is_application_smime(hdr->content))
963       {
964         secured = ! crypt_smime_decrypt_mime (msg->fp, &fp,
965                                               hdr->content, &cur);
966         
967         /* S/MIME nesting */
968         if ((mutt_is_application_smime (cur) & SMIMEOPAQUE))
969         {
970           BODY *_cur = cur;
971           FILE *_fp = fp;
972           
973           fp = NULL; cur = NULL;
974           secured = !crypt_smime_decrypt_mime (_fp, &fp, _cur, &cur);
975           
976           mutt_free_body (&_cur);
977           safe_fclose (&_fp);
978         }
979       }
980       else
981         need_secured = 0;
982     }
983     if ((WithCrypto & APPLICATION_PGP) && (hdr->security & APPLICATION_PGP))
984     {
985       if (mutt_is_multipart_encrypted(hdr->content))
986         secured = !crypt_pgp_decrypt_mime (msg->fp, &fp, hdr->content, &cur);
987       else
988         need_secured = 0;
989     }
990
991     if (need_secured && !secured)
992     {
993       mx_close_message (&msg);
994       mutt_error _("Can't decrypt encrypted message!");
995       return;
996     }
997   }
998   
999   if (!WithCrypto || !need_secured)
1000   {
1001     fp = msg->fp;
1002     cur = hdr->content;
1003   }
1004
1005   menu = mutt_new_menu ();
1006   menu->menu = MENU_ATTACH;
1007   menu->title = _("Attachments");
1008   menu->make_entry = attach_entry;
1009   menu->tag = mutt_tag_attach;
1010   menu->help = mutt_compile_help (helpstr, sizeof (helpstr), MENU_ATTACH, AttachHelp);
1011
1012   mutt_attach_init (cur);
1013   attach_collapse (cur, 0, 1, 0);
1014   mutt_update_attach_index (cur, &idx, &idxlen, &idxmax, menu);
1015
1016   FOREVER
1017   {
1018     if (op == OP_NULL)
1019       op = mutt_menuLoop (menu);
1020     switch (op)
1021     {
1022       case OP_ATTACH_VIEW_MAILCAP:
1023         mutt_view_attachment (fp, idx[menu->current]->content, M_MAILCAP,
1024                               hdr, idx, idxlen);
1025         menu->redraw = REDRAW_FULL;
1026         break;
1027
1028       case OP_ATTACH_VIEW_TEXT:
1029         mutt_view_attachment (fp, idx[menu->current]->content, M_AS_TEXT,
1030                               hdr, idx, idxlen);
1031         menu->redraw = REDRAW_FULL;
1032         break;
1033
1034       case OP_DISPLAY_HEADERS:
1035       case OP_VIEW_ATTACH:
1036         op = mutt_attach_display_loop (menu, op, fp, hdr, cur, &idx, &idxlen, &idxmax, 1);
1037         menu->redraw = REDRAW_FULL;
1038         continue;
1039
1040       case OP_ATTACH_COLLAPSE:
1041         if (!idx[menu->current]->content->parts)
1042         {
1043           mutt_error _("There are no subparts to show!");
1044           break;
1045         }
1046         if (!idx[menu->current]->content->collapsed)
1047           attach_collapse (idx[menu->current]->content, 1, 0, 1);
1048         else
1049           attach_collapse (idx[menu->current]->content, 0, 1, 1);
1050         mutt_update_attach_index (cur, &idx, &idxlen, &idxmax, menu);
1051         break;
1052       
1053       case OP_FORGET_PASSPHRASE:
1054         crypt_forget_passphrase ();
1055         break;
1056
1057       case OP_EXTRACT_KEYS:
1058         if ((WithCrypto & APPLICATION_PGP))
1059         {
1060           crypt_pgp_extract_keys_from_attachment_list (fp, menu->tagprefix, 
1061                     menu->tagprefix ? cur : idx[menu->current]->content);
1062           menu->redraw = REDRAW_FULL;
1063         }
1064         break;
1065       
1066       case OP_CHECK_TRADITIONAL:
1067         if ((WithCrypto & APPLICATION_PGP)
1068             && crypt_pgp_check_traditional (fp, menu->tagprefix ? cur
1069                                               : idx[menu->current]->content,
1070                                       menu->tagprefix))
1071         {
1072           hdr->security = crypt_query (cur);
1073           menu->redraw = REDRAW_FULL;
1074         }
1075         break;
1076
1077       case OP_PRINT:
1078         mutt_print_attachment_list (fp, menu->tagprefix, 
1079                   menu->tagprefix ? cur : idx[menu->current]->content);
1080         break;
1081
1082       case OP_PIPE:
1083         mutt_pipe_attachment_list (fp, menu->tagprefix, 
1084                   menu->tagprefix ? cur : idx[menu->current]->content, 0);
1085         break;
1086
1087       case OP_SAVE:
1088         mutt_save_attachment_list (fp, menu->tagprefix, 
1089                   menu->tagprefix ?  cur : idx[menu->current]->content, hdr, menu);
1090
1091         if (!menu->tagprefix && option (OPTRESOLVE) && menu->current < menu->max - 1)
1092           menu->current++;
1093       
1094         menu->redraw = REDRAW_MOTION_RESYNCH | REDRAW_FULL;
1095         break;
1096
1097       case OP_DELETE:
1098         CHECK_READONLY;
1099
1100 #ifdef USE_POP
1101         if (Context->magic == M_POP)
1102         {
1103           mutt_flushinp ();
1104           mutt_error _("Can't delete attachment from POP server.");
1105           break;
1106         }
1107 #endif
1108
1109 #ifdef USE_NNTP
1110         if (Context->magic == M_NNTP)
1111         {
1112           mutt_flushinp ();
1113           mutt_error _("Can't delete attachment from newsserver.");
1114           break;
1115         }
1116 #endif
1117
1118         if (WithCrypto && hdr->security)
1119         {
1120           mutt_message _(
1121             "Deletion of attachments from encrypted messages is unsupported.");
1122         }
1123         else
1124         {
1125           if (!menu->tagprefix)
1126           {
1127             if (idx[menu->current]->parent_type == TYPEMULTIPART)
1128             {
1129               idx[menu->current]->content->deleted = 1;
1130               if (option (OPTRESOLVE) && menu->current < menu->max - 1)
1131               {
1132                 menu->current++;
1133                 menu->redraw = REDRAW_MOTION_RESYNCH;
1134               }
1135               else
1136                 menu->redraw = REDRAW_CURRENT;
1137             }
1138             else
1139               mutt_message _(
1140                 "Only deletion of multipart attachments is supported.");
1141           }
1142           else
1143           {
1144             int x;
1145
1146             for (x = 0; x < menu->max; x++)
1147             {
1148               if (idx[x]->content->tagged)
1149               {
1150                 if (idx[x]->parent_type == TYPEMULTIPART)
1151                 {
1152                   idx[x]->content->deleted = 1;
1153                   menu->redraw = REDRAW_INDEX;
1154                 }
1155                 else
1156                   mutt_message _(
1157                     "Only deletion of multipart attachments is supported.");
1158               }
1159             }
1160           }
1161         }
1162         break;
1163
1164       case OP_UNDELETE:
1165        CHECK_READONLY;
1166        if (!menu->tagprefix)
1167        {
1168          idx[menu->current]->content->deleted = 0;
1169          if (option (OPTRESOLVE) && menu->current < menu->max - 1)
1170          {
1171            menu->current++;
1172            menu->redraw = REDRAW_MOTION_RESYNCH;
1173          }
1174          else
1175            menu->redraw = REDRAW_CURRENT;
1176        }
1177        else
1178        {
1179          int x;
1180
1181          for (x = 0; x < menu->max; x++)
1182          {
1183            if (idx[x]->content->tagged)
1184            {
1185              idx[x]->content->deleted = 0;
1186              menu->redraw = REDRAW_INDEX;
1187            }
1188          }
1189        }
1190        break;
1191
1192       case OP_RESEND:
1193         CHECK_ATTACH;
1194         mutt_attach_resend (fp, hdr, idx, idxlen,
1195                              menu->tagprefix ? NULL : idx[menu->current]->content);
1196         menu->redraw = REDRAW_FULL;
1197         break;
1198       
1199       case OP_BOUNCE_MESSAGE:
1200         CHECK_ATTACH;
1201         mutt_attach_bounce (fp, hdr, idx, idxlen,
1202                              menu->tagprefix ? NULL : idx[menu->current]->content);
1203         menu->redraw = REDRAW_FULL;
1204         break;
1205
1206       case OP_FORWARD_MESSAGE:
1207         CHECK_ATTACH;
1208         mutt_attach_forward (fp, hdr, idx, idxlen,
1209                              menu->tagprefix ? NULL : idx[menu->current]->content, 0);
1210         menu->redraw = REDRAW_FULL;
1211         break;
1212       
1213 #ifdef USE_NNTP
1214       case OP_FORWARD_TO_GROUP:
1215         CHECK_ATTACH;
1216         mutt_attach_forward (fp, hdr, idx, idxlen,
1217                 menu->tagprefix ? NULL : idx[menu->current]->content, SENDNEWS);
1218         menu->redraw = REDRAW_FULL;
1219         break;
1220
1221       case OP_FOLLOWUP:
1222         CHECK_ATTACH;
1223
1224         if (!idx[menu->current]->content->hdr->env->followup_to ||
1225             mutt_strcasecmp (idx[menu->current]->content->hdr->env->followup_to, "poster") ||
1226             query_quadoption (OPT_FOLLOWUPTOPOSTER,_("Reply by mail as poster prefers?")) != M_YES)
1227         {
1228           mutt_attach_reply (fp, hdr, idx, idxlen,
1229                 menu->tagprefix ? NULL : idx[menu->current]->content,
1230                 SENDNEWS|SENDREPLY);
1231           menu->redraw = REDRAW_FULL;
1232           break;
1233         }
1234 #endif
1235
1236       case OP_REPLY:
1237       case OP_GROUP_REPLY:
1238       case OP_LIST_REPLY:
1239
1240         CHECK_ATTACH;
1241       
1242         flags = SENDREPLY | 
1243           (op == OP_GROUP_REPLY ? SENDGROUPREPLY : 0) |
1244           (op == OP_LIST_REPLY ? SENDLISTREPLY : 0);
1245         mutt_attach_reply (fp, hdr, idx, idxlen, 
1246                            menu->tagprefix ? NULL : idx[menu->current]->content, flags);
1247         menu->redraw = REDRAW_FULL;
1248         break;
1249
1250       case OP_EDIT_TYPE:
1251         mutt_edit_content_type (hdr, idx[menu->current]->content, fp);
1252         mutt_update_attach_index (cur, &idx, &idxlen, &idxmax, menu);
1253         break;
1254
1255       case OP_EXIT:
1256         mx_close_message (&msg);
1257         hdr->attach_del = 0;
1258         while (idxmax-- > 0)
1259         {
1260           if (!idx[idxmax])
1261             continue;
1262           if (idx[idxmax]->content && idx[idxmax]->content->deleted)
1263             hdr->attach_del = 1;
1264           if (idx[idxmax]->content)
1265             idx[idxmax]->content->aptr = NULL;
1266           FREE (&idx[idxmax]->tree);
1267           FREE (&idx[idxmax]);
1268         }
1269         if (hdr->attach_del)
1270           hdr->changed = 1;
1271         FREE (&idx);
1272         idxmax = 0;
1273
1274         if (WithCrypto && need_secured && secured)
1275         {
1276           fclose (fp);
1277           mutt_free_body (&cur);
1278         }
1279
1280         mutt_menuDestroy  (&menu);
1281         return;
1282     }
1283
1284     op = OP_NULL;
1285   }
1286
1287   /* not reached */
1288 }