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