optimizations, remove horrors.
[apps/madmutt.git] / handler.c
1 /*
2  * Copyright notice from original mutt:
3  * Copyright (C) 1996-2000 Michael R. Elkins <me@mutt.org>
4  *
5  * This file is part of mutt-ng, see http://www.muttng.org/.
6  * It's licensed under the GNU General Public License,
7  * please see the file GPL in the top level source directory.
8  */
9
10 #include <lib-lib/lib-lib.h>
11
12 #include <lib-mime/mime.h>
13 #include <lib-mime/rfc3676.h>
14
15 #include <lib-ui/curses.h>
16
17 #include <lib-sys/unix.h>
18
19 #include "mutt.h"
20 #include "recvattach.h"
21 #include "handler.h"
22 #include "keymap.h"
23 #include "copy.h"
24 #include "charset.h"
25 #include <lib-crypt/crypt.h>
26 #include "state.h"
27 #include "attach.h"
28 #include "lib.h"
29
30
31 typedef int handler_f (BODY *, STATE *);
32 typedef handler_f *handler_t;
33
34 static void mutt_decode_xbit (STATE * s, long len, int istext, iconv_t cd)
35 {
36   int c, ch;
37   char bufi[BUFI_SIZE];
38   ssize_t l = 0;
39
40   if (istext) {
41     state_set_prefix (s);
42
43     while ((c = fgetc (s->fpin)) != EOF && len--) {
44       if (c == '\r' && len) {
45         if ((ch = fgetc (s->fpin)) == '\n') {
46           c = ch;
47           len--;
48         }
49         else
50           ungetc (ch, s->fpin);
51       }
52
53       bufi[l++] = c;
54       if (l == sizeof (bufi))
55         mutt_convert_to_state (cd, bufi, &l, s);
56     }
57
58     mutt_convert_to_state (cd, bufi, &l, s);
59     mutt_convert_to_state (cd, 0, 0, s);
60
61     state_reset_prefix (s);
62   }
63   else
64     mutt_copy_bytes (s->fpin, s->fpout, len);
65 }
66
67 static int qp_decode_triple (char *s, char *d)
68 {
69   /* soft line break */
70   if (*s == '=' && !(*(s + 1)))
71     return 1;
72
73   /* quoted-printable triple */
74   if (*s == '=' &&
75       isxdigit ((unsigned char) *(s + 1)) &&
76       isxdigit ((unsigned char) *(s + 2))) {
77     *d = (hexval (*(s + 1)) << 4) | hexval (*(s + 2));
78     return 0;
79   }
80
81   /* something else */
82   return -1;
83 }
84
85 static void qp_decode_line (char *dest, char *src, ssize_t * l, int last)
86 {
87   char *d, *s;
88   char c;
89
90   int kind;
91   int soft = 0;
92
93   /* decode the line */
94
95   for (d = dest, s = src; *s;) {
96     switch ((kind = qp_decode_triple (s, &c))) {
97     case 0:
98       *d++ = c;
99       s += 3;
100       break;                    /* qp triple */
101     case -1:
102       *d++ = *s++;
103       break;                    /* single character */
104     case 1:
105       soft = 1;
106       s++;
107       break;                    /* soft line break */
108     }
109   }
110
111   if (!soft && last == '\n')
112     *d++ = '\n';
113
114   *d = '\0';
115   *l = d - dest;
116 }
117
118 /* 
119  * Decode an attachment encoded with quoted-printable.
120  * 
121  * Why doesn't this overflow any buffers?  First, it's guaranteed
122  * that the length of a line grows when you _en_-code it to
123  * quoted-printable.  That means that we always can store the
124  * result in a buffer of at most the _same_ size.
125  * 
126  * Now, we don't special-case if the line we read with fgets()
127  * isn't terminated.  We don't care about this, since STRING > 78,
128  * so corrupted input will just be corrupted a bit more.  That
129  * implies that STRING+1 bytes are always sufficient to store the
130  * result of qp_decode_line.
131  * 
132  * Finally, at soft line breaks, some part of a multibyte character
133  * may have been left over by mutt_convert_to_state().  This shouldn't
134  * be more than 6 characters, so STRING + 7 should be sufficient
135  * memory to store the decoded data.
136  * 
137  * Just to make sure that I didn't make some off-by-one error
138  * above, we just use STRING*2 for the target buffer's size.
139  * 
140  */
141
142 static void mutt_decode_quoted (STATE * s, long len, int istext, iconv_t cd)
143 {
144   char line[STRING];
145   char decline[2 * STRING];
146   ssize_t l = 0;
147   ssize_t linelen;               /* number of input bytes in `line' */
148   ssize_t l3;
149
150   int last;                     /* store the last character in the input line */
151
152   if (istext)
153     state_set_prefix (s);
154
155   while (len > 0) {
156     last = 0;
157
158     /*
159      * It's ok to use a fixed size buffer for input, even if the line turns
160      * out to be longer than this.  Just process the line in chunks.  This
161      * really shouldn't happen according the MIME spec, since Q-P encoded
162      * lines are at most 76 characters, but we should be liberal about what
163      * we accept.
164      */
165     if (fgets (line, MIN ((ssize_t) sizeof (line), len + 1), s->fpin) == NULL)
166       break;
167
168     linelen = m_strlen(line);
169     len -= linelen;
170
171     /*
172      * inspect the last character we read so we can tell if we got the
173      * entire line.
174      */
175     last = linelen ? line[linelen - 1] : 0;
176
177     /* chop trailing whitespace if we got the full line */
178     if (last == '\n') {
179       while (linelen > 0 && ISSPACE (line[linelen - 1]))
180         linelen--;
181       line[linelen] = 0;
182     }
183
184     /* decode and do character set conversion */
185     qp_decode_line (decline + l, line, &l3, last);
186     l += l3;
187     mutt_convert_to_state (cd, decline, &l, s);
188   }
189
190   mutt_convert_to_state (cd, 0, 0, s);
191   state_reset_prefix (s);
192 }
193
194 void mutt_decode_base64 (STATE * s, long len, int istext, iconv_t cd)
195 {
196   char buf[5];
197   int c1, c2, c3, c4, ch, cr = 0, i;
198   char bufi[BUFI_SIZE];
199   ssize_t l = 0;
200
201   buf[4] = 0;
202
203   if (istext)
204     state_set_prefix (s);
205
206   while (len > 0) {
207     for (i = 0; i < 4 && len > 0; len--) {
208       if ((ch = fgetc (s->fpin)) == EOF)
209         break;
210       if (base64val(ch) >= 0 || ch == '=')
211         buf[i++] = ch;
212     }
213     if (i != 4) {
214       break;
215     }
216
217     c1 = base64val(buf[0]);
218     c2 = base64val(buf[1]);
219     ch = (c1 << 2) | (c2 >> 4);
220
221     if (cr && ch != '\n')
222       bufi[l++] = '\r';
223
224     cr = 0;
225
226     if (istext && ch == '\r')
227       cr = 1;
228     else
229       bufi[l++] = ch;
230
231     if (buf[2] == '=')
232       break;
233     c3 = base64val(buf[2]);
234     ch = ((c2 & 0xf) << 4) | (c3 >> 2);
235
236     if (cr && ch != '\n')
237       bufi[l++] = '\r';
238
239     cr = 0;
240
241     if (istext && ch == '\r')
242       cr = 1;
243     else
244       bufi[l++] = ch;
245
246     if (buf[3] == '=')
247       break;
248     c4 = base64val(buf[3]);
249     ch = ((c3 & 0x3) << 6) | c4;
250
251     if (cr && ch != '\n')
252       bufi[l++] = '\r';
253     cr = 0;
254
255     if (istext && ch == '\r')
256       cr = 1;
257     else
258       bufi[l++] = ch;
259
260     if (l + 8 >= ssizeof (bufi))
261       mutt_convert_to_state (cd, bufi, &l, s);
262   }
263
264   if (cr)
265     bufi[l++] = '\r';
266
267   mutt_convert_to_state (cd, bufi, &l, s);
268   mutt_convert_to_state (cd, 0, 0, s);
269
270   state_reset_prefix (s);
271 }
272
273 static unsigned char decode_byte(int ch)
274 {
275     return ch == 96 ? 0 : ch - 32;
276 }
277
278 static void mutt_decode_uuencoded (STATE * s, long len, int istext, iconv_t cd)
279 {
280   char tmps[STRING];
281   char linelen, c, l, out;
282   char *pt;
283   char bufi[BUFI_SIZE];
284   ssize_t k = 0;
285
286   if (istext)
287     state_set_prefix (s);
288
289   while (len > 0) {
290     if ((fgets (tmps, sizeof (tmps), s->fpin)) == NULL)
291       return;
292     len -= m_strlen(tmps);
293     if ((!m_strncmp(tmps, "begin", 5)) && ISSPACE (tmps[5]))
294       break;
295   }
296   while (len > 0) {
297     if ((fgets (tmps, sizeof (tmps), s->fpin)) == NULL)
298       return;
299     len -= m_strlen(tmps);
300     if (!m_strncmp(tmps, "end", 3))
301       break;
302     pt = tmps;
303     linelen = decode_byte(*pt);
304     pt++;
305     for (c = 0; c < linelen;) {
306       for (l = 2; l <= 6; l += 2) {
307         out = decode_byte(*pt) << l;
308         pt++;
309         out |= (decode_byte(*pt) >> (6 - l));
310         bufi[k++] = out;
311         c++;
312         if (c == linelen)
313           break;
314       }
315       mutt_convert_to_state (cd, bufi, &k, s);
316       pt++;
317     }
318   }
319
320   mutt_convert_to_state (cd, bufi, &k, s);
321   mutt_convert_to_state (cd, 0, 0, s);
322
323   state_reset_prefix (s);
324 }
325
326 /* ----------------------------------------------------------------------------
327  * A (not so) minimal implementation of RFC1563.
328  */
329
330 #define IndentSize (4)
331
332 enum { RICH_PARAM = 0, RICH_BOLD, RICH_UNDERLINE, RICH_ITALIC, RICH_NOFILL,
333   RICH_INDENT, RICH_INDENT_RIGHT, RICH_EXCERPT, RICH_CENTER, RICH_FLUSHLEFT,
334   RICH_FLUSHRIGHT, RICH_COLOR, RICH_LAST_TAG
335 };
336
337 static struct {
338   const char *tag_name;
339   int index;
340 } EnrichedTags[] = {
341   {"param", RICH_PARAM},
342   {"bold", RICH_BOLD},
343   {"italic", RICH_ITALIC},
344   {"underline", RICH_UNDERLINE},
345   {"nofill", RICH_NOFILL},
346   {"excerpt", RICH_EXCERPT},
347   {"indent", RICH_INDENT},
348   {"indentright", RICH_INDENT_RIGHT},
349   {"center", RICH_CENTER},
350   {"flushleft", RICH_FLUSHLEFT},
351   {"flushright", RICH_FLUSHRIGHT},
352   {"flushboth", RICH_FLUSHLEFT},
353   {"color", RICH_COLOR},
354   {"x-color", RICH_COLOR},
355   {NULL, -1}
356 };
357
358 struct enriched_state {
359   char *buffer;
360   char *line;
361   char *param;
362   ssize_t buff_len;
363   ssize_t line_len;
364   ssize_t line_used;
365   ssize_t line_max;
366   ssize_t indent_len;
367   ssize_t word_len;
368   ssize_t buff_used;
369   ssize_t param_used;
370   ssize_t param_len;
371   int tag_level[RICH_LAST_TAG];
372   int WrapMargin;
373   STATE *s;
374 };
375
376 static void enriched_wrap (struct enriched_state *stte)
377 {
378   int x;
379   int extra;
380
381   if (stte->line_len) {
382     if (stte->tag_level[RICH_CENTER] || stte->tag_level[RICH_FLUSHRIGHT]) {
383       /* Strip trailing white space */
384       ssize_t y = stte->line_used - 1;
385
386       while (y && ISSPACE (stte->line[y])) {
387         stte->line[y] = '\0';
388         y--;
389         stte->line_used--;
390         stte->line_len--;
391       }
392       if (stte->tag_level[RICH_CENTER]) {
393         /* Strip leading whitespace */
394         y = 0;
395
396         while (stte->line[y] && ISSPACE (stte->line[y]))
397           y++;
398         if (y) {
399           ssize_t z;
400
401           for (z = y; z <= stte->line_used; z++) {
402             stte->line[z - y] = stte->line[z];
403           }
404
405           stte->line_len -= y;
406           stte->line_used -= y;
407         }
408       }
409     }
410
411     extra = stte->WrapMargin - stte->line_len - stte->indent_len -
412       (stte->tag_level[RICH_INDENT_RIGHT] * IndentSize);
413     if (extra > 0) {
414       if (stte->tag_level[RICH_CENTER]) {
415         x = extra / 2;
416         while (x) {
417           state_putc (' ', stte->s);
418           x--;
419         }
420       }
421       else if (stte->tag_level[RICH_FLUSHRIGHT]) {
422         x = extra - 1;
423         while (x) {
424           state_putc (' ', stte->s);
425           x--;
426         }
427       }
428     }
429     state_puts (stte->line, stte->s);
430   }
431
432   state_putc ('\n', stte->s);
433   stte->line[0] = '\0';
434   stte->line_len = 0;
435   stte->line_used = 0;
436   stte->indent_len = 0;
437   if (stte->s->prefix) {
438     state_puts (stte->s->prefix, stte->s);
439     stte->indent_len += m_strlen(stte->s->prefix);
440   }
441
442   if (stte->tag_level[RICH_EXCERPT]) {
443     x = stte->tag_level[RICH_EXCERPT];
444     while (x) {
445       if (stte->s->prefix) {
446         state_puts (stte->s->prefix, stte->s);
447         stte->indent_len += m_strlen(stte->s->prefix);
448       }
449       else {
450         state_puts ("> ", stte->s);
451         stte->indent_len += m_strlen("> ");
452       }
453       x--;
454     }
455   }
456   else
457     stte->indent_len = 0;
458   if (stte->tag_level[RICH_INDENT]) {
459     x = stte->tag_level[RICH_INDENT] * IndentSize;
460     stte->indent_len += x;
461     while (x) {
462       state_putc (' ', stte->s);
463       x--;
464     }
465   }
466 }
467
468 static void enriched_flush (struct enriched_state *stte, int wrap)
469 {
470   if (!stte->tag_level[RICH_NOFILL] && (stte->line_len + stte->word_len >
471                                         (stte->WrapMargin -
472                                          (stte->tag_level[RICH_INDENT_RIGHT] *
473                                           IndentSize) - stte->indent_len)))
474     enriched_wrap (stte);
475
476   if (stte->buff_used) {
477     stte->buffer[stte->buff_used] = '\0';
478     stte->line_used += stte->buff_used;
479     if (stte->line_used > stte->line_max) {
480       stte->line_max = stte->line_used;
481       p_realloc(&stte->line, stte->line_max + 1);
482     }
483     m_strcat(stte->line, stte->line_max + 1, stte->buffer);
484     stte->line_len += stte->word_len;
485     stte->word_len = 0;
486     stte->buff_used = 0;
487   }
488   if (wrap)
489     enriched_wrap (stte);
490 }
491
492
493 static void enriched_putc (int c, struct enriched_state *stte)
494 {
495   if (stte->tag_level[RICH_PARAM]) {
496     if (stte->tag_level[RICH_COLOR]) {
497       if (stte->param_used + 1 >= stte->param_len)
498         p_realloc(&stte->param, (stte->param_len += STRING));
499
500       stte->param[stte->param_used++] = c;
501     }
502     return;                     /* nothing to do */
503   }
504
505   /* see if more space is needed (plus extra for possible rich characters) */
506   if (stte->buff_len < stte->buff_used + 3) {
507     stte->buff_len += LONG_STRING;
508     p_realloc(&stte->buffer, stte->buff_len + 1);
509   }
510
511   if ((!stte->tag_level[RICH_NOFILL] && ISSPACE (c)) || c == '\0') {
512     if (c == '\t')
513       stte->word_len += 8 - (stte->line_len + stte->word_len) % 8;
514     else
515       stte->word_len++;
516
517     stte->buffer[stte->buff_used++] = c;
518     enriched_flush (stte, 0);
519   }
520   else {
521     if (stte->s->flags & M_DISPLAY) {
522       if (stte->tag_level[RICH_BOLD]) {
523         stte->buffer[stte->buff_used++] = c;
524         stte->buffer[stte->buff_used++] = '\010';
525         stte->buffer[stte->buff_used++] = c;
526       }
527       else if (stte->tag_level[RICH_UNDERLINE]) {
528
529         stte->buffer[stte->buff_used++] = '_';
530         stte->buffer[stte->buff_used++] = '\010';
531         stte->buffer[stte->buff_used++] = c;
532       }
533       else if (stte->tag_level[RICH_ITALIC]) {
534         stte->buffer[stte->buff_used++] = c;
535         stte->buffer[stte->buff_used++] = '\010';
536         stte->buffer[stte->buff_used++] = '_';
537       }
538       else {
539         stte->buffer[stte->buff_used++] = c;
540       }
541     } else {
542       stte->buffer[stte->buff_used++] = c;
543     }
544     stte->word_len++;
545   }
546 }
547
548 static void enriched_puts (const char *s, struct enriched_state *stte)
549 {
550   const char *p;
551
552   if (stte->buff_len < stte->buff_used + m_strlen(s)) {
553     stte->buff_len += LONG_STRING;
554     p_realloc(&stte->buffer, stte->buff_len + 1);
555   }
556
557   p = s;
558   while (*p) {
559     stte->buffer[stte->buff_used++] = *p++;
560   }
561 }
562
563 static void enriched_set_flags (const char *tag, struct enriched_state *stte)
564 {
565   const char *tagptr = tag;
566   int i, j;
567
568   if (*tagptr == '/')
569     tagptr++;
570
571   for (i = 0, j = -1; EnrichedTags[i].tag_name; i++)
572     if (ascii_strcasecmp (EnrichedTags[i].tag_name, tagptr) == 0) {
573       j = EnrichedTags[i].index;
574       break;
575     }
576
577   if (j != -1) {
578     if (j == RICH_CENTER || j == RICH_FLUSHLEFT || j == RICH_FLUSHRIGHT)
579       enriched_flush (stte, 1);
580
581     if (*tag == '/') {
582       if (stte->tag_level[j])   /* make sure not to go negative */
583         stte->tag_level[j]--;
584       if ((stte->s->flags & M_DISPLAY) && j == RICH_PARAM
585           && stte->tag_level[RICH_COLOR]) {
586         stte->param[stte->param_used] = '\0';
587         if (!ascii_strcasecmp (stte->param, "black")) {
588           enriched_puts ("\033[30m", stte);
589         }
590         else if (!ascii_strcasecmp (stte->param, "red")) {
591           enriched_puts ("\033[31m", stte);
592         }
593         else if (!ascii_strcasecmp (stte->param, "green")) {
594           enriched_puts ("\033[32m", stte);
595         }
596         else if (!ascii_strcasecmp (stte->param, "yellow")) {
597           enriched_puts ("\033[33m", stte);
598         }
599         else if (!ascii_strcasecmp (stte->param, "blue")) {
600           enriched_puts ("\033[34m", stte);
601         }
602         else if (!ascii_strcasecmp (stte->param, "magenta")) {
603           enriched_puts ("\033[35m", stte);
604         }
605         else if (!ascii_strcasecmp (stte->param, "cyan")) {
606           enriched_puts ("\033[36m", stte);
607         }
608         else if (!ascii_strcasecmp (stte->param, "white")) {
609           enriched_puts ("\033[37m", stte);
610         }
611       }
612       if ((stte->s->flags & M_DISPLAY) && j == RICH_COLOR) {
613         enriched_puts ("\033[0m", stte);
614       }
615
616       /* flush parameter buffer when closing the tag */
617       if (j == RICH_PARAM) {
618         stte->param_used = 0;
619         stte->param[0] = '\0';
620       }
621     }
622     else
623       stte->tag_level[j]++;
624
625     if (j == RICH_EXCERPT)
626       enriched_flush (stte, 1);
627   }
628 }
629
630 static int text_enriched_handler (BODY * a, STATE * s)
631 {
632   enum {
633     TEXT, LANGLE, TAG, BOGUS_TAG, NEWLINE, ST_EOF, DONE
634   } state = TEXT;
635
636   long bytes = a->length;
637   struct enriched_state stte;
638   int c = 0;
639   int tag_len = 0;
640   char tag[LONG_STRING + 1];
641
642   p_clear(&stte, 1);
643   stte.s = s;
644   stte.WrapMargin =
645     ((s->flags & M_DISPLAY) ? (COLS - 4) : ((COLS - 4) <
646                                             72) ? (COLS - 4) : 72);
647   stte.line_max = stte.WrapMargin * 4;
648   stte.line = p_new(char, stte.line_max + 1);
649   stte.param = p_new(char, STRING);
650
651   stte.param_len = STRING;
652   stte.param_used = 0;
653
654   if (s->prefix) {
655     state_puts (s->prefix, s);
656     stte.indent_len += m_strlen(s->prefix);
657   }
658
659   while (state != DONE) {
660     if (state != ST_EOF) {
661       if (!bytes || (c = fgetc (s->fpin)) == EOF)
662         state = ST_EOF;
663       else
664         bytes--;
665     }
666
667     switch (state) {
668     case TEXT:
669       switch (c) {
670       case '<':
671         state = LANGLE;
672         break;
673
674       case '\n':
675         if (stte.tag_level[RICH_NOFILL]) {
676           enriched_flush (&stte, 1);
677         }
678         else {
679           enriched_putc (' ', &stte);
680           state = NEWLINE;
681         }
682         break;
683
684       default:
685         enriched_putc (c, &stte);
686       }
687       break;
688
689     case LANGLE:
690       if (c == '<') {
691         enriched_putc (c, &stte);
692         state = TEXT;
693         break;
694       }
695       else {
696         tag_len = 0;
697         state = TAG;
698       }
699       /* Yes, fall through (it wasn't a <<, so this char is first in TAG) */
700     case TAG:
701       if (c == '>') {
702         tag[tag_len] = '\0';
703         enriched_set_flags (tag, &stte);
704         state = TEXT;
705       }
706       else if (tag_len < LONG_STRING)   /* ignore overly long tags */
707         tag[tag_len++] = c;
708       else
709         state = BOGUS_TAG;
710       break;
711
712     case BOGUS_TAG:
713       if (c == '>')
714         state = TEXT;
715       break;
716
717     case NEWLINE:
718       if (c == '\n')
719         enriched_flush (&stte, 1);
720       else {
721         ungetc (c, s->fpin);
722         bytes++;
723         state = TEXT;
724       }
725       break;
726
727     case ST_EOF:
728       enriched_putc ('\0', &stte);
729       enriched_flush (&stte, 1);
730       state = DONE;
731       break;
732
733     case DONE:                 /* not reached, but gcc complains if this is absent */
734       break;
735     }
736   }
737
738   state_putc ('\n', s);         /* add a final newline */
739
740   p_delete(&(stte.buffer));
741   p_delete(&(stte.line));
742   p_delete(&(stte.param));
743
744   return (0);
745 }
746
747 #define TXTHTML     1
748 #define TXTPLAIN    2
749 #define TXTENRICHED 3
750
751 static int alternative_handler (BODY * a, STATE * s)
752 {
753   BODY *choice = NULL;
754   BODY *b;
755   string_list_t *t;
756   char buf[STRING];
757   int type = 0;
758   int mustfree = 0;
759   int rc = 0;
760
761   if (a->encoding == ENCBASE64 || a->encoding == ENCQUOTEDPRINTABLE ||
762       a->encoding == ENCUUENCODED) {
763     struct stat st;
764
765     mustfree = 1;
766     fstat (fileno (s->fpin), &st);
767     b = body_new();
768     b->length = (long) st.st_size;
769     b->parts = mutt_parse_multipart(s->fpin,
770                                     parameter_getval(a->parameter, "boundary"),
771                                     (long)st.st_size,
772                                     !ascii_strcasecmp("digest", a->subtype));
773   }
774   else
775     b = a;
776
777   a = b;
778
779   /* First, search list of prefered types */
780   t = AlternativeOrderList;
781   while (t && !choice) {
782     char *c;
783     int btlen;                  /* length of basetype */
784     int wild;                   /* do we have a wildcard to match all subtypes? */
785
786     c = strchr (t->data, '/');
787     if (c) {
788       wild = (c[1] == '*' && c[2] == 0);
789       btlen = c - t->data;
790     }
791     else {
792       wild = 1;
793       btlen = m_strlen(t->data);
794     }
795
796     if (a && a->parts)
797       b = a->parts;
798     else
799       b = a;
800     while (b) {
801       const char *bt = TYPE (b);
802
803       if (!ascii_strncasecmp (bt, t->data, btlen) && bt[btlen] == 0) {
804         /* the basetype matches */
805         if (wild || !ascii_strcasecmp (t->data + btlen + 1, b->subtype)) {
806           choice = b;
807         }
808       }
809       b = b->next;
810     }
811     t = t->next;
812   }
813
814   /* Next, look for an autoviewable type */
815   if (!choice) {
816     if (a && a->parts)
817       b = a->parts;
818     else
819       b = a;
820     while (b) {
821       snprintf (buf, sizeof (buf), "%s/%s", TYPE (b), b->subtype);
822       if (mutt_is_autoview (b, buf)) {
823         rfc1524_entry *entry = rfc1524_entry_new();
824
825         if (rfc1524_mailcap_lookup (b, buf, entry, M_AUTOVIEW)) {
826           choice = b;
827         }
828         rfc1524_entry_delete(&entry);
829       }
830       b = b->next;
831     }
832   }
833
834   /* Then, look for a text entry */
835   if (!choice) {
836     if (a && a->parts)
837       b = a->parts;
838     else
839       b = a;
840     while (b) {
841       if (b->type == TYPETEXT) {
842         if (!ascii_strcasecmp ("plain", b->subtype) && type <= TXTPLAIN) {
843           choice = b;
844           type = TXTPLAIN;
845         }
846         else if (!ascii_strcasecmp ("enriched", b->subtype)
847                  && type <= TXTENRICHED) {
848           choice = b;
849           type = TXTENRICHED;
850         }
851         else if (!ascii_strcasecmp ("html", b->subtype) && type <= TXTHTML) {
852           choice = b;
853           type = TXTHTML;
854         }
855       }
856       b = b->next;
857     }
858   }
859
860   /* Finally, look for other possibilities */
861   if (!choice) {
862     if (a && a->parts)
863       b = a->parts;
864     else
865       b = a;
866     while (b) {
867       if (mutt_can_decode (b))
868         choice = b;
869       b = b->next;
870     }
871   }
872
873   if (choice) {
874     if (s->flags & M_DISPLAY && !option (OPTWEED)) {
875       fseeko (s->fpin, choice->hdr_offset, 0);
876       mutt_copy_bytes (s->fpin, s->fpout,
877                        choice->offset - choice->hdr_offset);
878     }
879     mutt_body_handler (choice, s);
880   }
881   else if (s->flags & M_DISPLAY) {
882     /* didn't find anything that we could display! */
883     state_mark_attach (s);
884     state_puts (_("[-- Error:  Could not display any parts of Multipart/Alternative! --]\n"), s);
885     rc = -1;
886   }
887
888   if (mustfree)
889     body_list_wipe(&a);
890
891   return (rc);
892 }
893
894 /* handles message/rfc822 body parts */
895 static int message_handler (BODY * a, STATE * s)
896 {
897   struct stat st;
898   BODY *b;
899   off_t off_start;
900   int rc = 0;
901
902   off_start = ftello (s->fpin);
903   if (a->encoding == ENCBASE64 || a->encoding == ENCQUOTEDPRINTABLE ||
904       a->encoding == ENCUUENCODED) {
905     fstat (fileno (s->fpin), &st);
906     b = body_new();
907     b->length = (long) st.st_size;
908     b->parts = mutt_parse_messageRFC822 (s->fpin, b);
909   }
910   else
911     b = a;
912
913   if (b->parts) {
914     mutt_copy_hdr (s->fpin, s->fpout, off_start, b->parts->offset,
915                    (((s->flags & M_WEED)
916                      || ((s->flags & (M_DISPLAY | M_PRINTING))
917                          && option (OPTWEED))) ? (CH_WEED | CH_REORDER) : 0) |
918                    (s->prefix ? CH_PREFIX : 0) | CH_DECODE | CH_FROM,
919                    s->prefix);
920
921     if (s->prefix)
922       state_puts (s->prefix, s);
923     state_putc ('\n', s);
924
925     rc = mutt_body_handler (b->parts, s);
926   }
927
928   if (a->encoding == ENCBASE64 || a->encoding == ENCQUOTEDPRINTABLE ||
929       a->encoding == ENCUUENCODED)
930     body_list_wipe(&b);
931
932   return (rc);
933 }
934
935 /* returns 1 if decoding the attachment will produce output */
936 int mutt_can_decode (BODY * a)
937 {
938   char type[STRING];
939
940   snprintf (type, sizeof (type), "%s/%s", TYPE (a), a->subtype);
941   if (mutt_is_autoview (a, type))
942     return (rfc1524_mailcap_lookup (a, type, NULL, M_AUTOVIEW));
943   else if (a->type == TYPETEXT)
944     return (1);
945   else if (a->type == TYPEMESSAGE)
946     return (1);
947   else if (a->type == TYPEMULTIPART) {
948     BODY *p;
949
950     if (ascii_strcasecmp (a->subtype, "signed") == 0 ||
951         ascii_strcasecmp (a->subtype, "encrypted") == 0)
952       return (1);
953
954     for (p = a->parts; p; p = p->next) {
955       if (mutt_can_decode (p))
956         return (1);
957     }
958
959   }
960   else if (a->type == TYPEAPPLICATION) {
961     if (mutt_is_application_pgp(a))
962       return (1);
963     if (mutt_is_application_smime (a))
964       return (1);
965   }
966
967   return (0);
968 }
969
970 static int multipart_handler (BODY * a, STATE * s)
971 {
972   BODY *b, *p;
973   char length[5];
974   struct stat st;
975   int count;
976   int rc = 0;
977
978   if (a->encoding == ENCBASE64 || a->encoding == ENCQUOTEDPRINTABLE ||
979       a->encoding == ENCUUENCODED) {
980     fstat (fileno (s->fpin), &st);
981     b = body_new();
982     b->length = (long) st.st_size;
983     b->parts = mutt_parse_multipart(s->fpin,
984                                     parameter_getval(a->parameter, "boundary"),
985                                     (long)st.st_size,
986                                     !ascii_strcasecmp("digest", a->subtype));
987   }
988   else
989     b = a;
990
991   for (p = b->parts, count = 1; p; p = p->next, count++) {
992     if (s->flags & M_DISPLAY) {
993       state_mark_attach (s);
994       state_printf (s, _("[-- Attachment #%d"), count);
995       if (p->description || p->filename || p->form_name) {
996         state_puts (": ", s);
997         state_puts (p->description ? p->description :
998                     p->filename ? p->filename : p->form_name, s);
999       }
1000       state_puts (" --]\n", s);
1001
1002       mutt_pretty_size (length, sizeof (length), p->length);
1003
1004       state_mark_attach (s);
1005       state_printf (s, _("[-- Type: %s/%s, Encoding: %s, Size: %s --]\n"),
1006                     TYPE (p), p->subtype, ENCODING (p->encoding), length);
1007       if (!option (OPTWEED)) {
1008         fseeko (s->fpin, p->hdr_offset, 0);
1009         mutt_copy_bytes (s->fpin, s->fpout, p->offset - p->hdr_offset);
1010       }
1011       else
1012         state_putc ('\n', s);
1013     }
1014     else {
1015       if (p->description && mutt_can_decode (p))
1016         state_printf (s, "Content-Description: %s\n", p->description);
1017
1018       if (p->form_name)
1019         state_printf (s, "%s: \n", p->form_name);
1020
1021     }
1022     rc = mutt_body_handler (p, s);
1023     state_putc ('\n', s);
1024     if (rc || ((s->flags & M_REPLYING)
1025         && (option (OPTINCLUDEONLYFIRST)) && (s->flags & M_FIRSTDONE)))
1026       break;
1027   }
1028
1029   if (a->encoding == ENCBASE64 || a->encoding == ENCQUOTEDPRINTABLE ||
1030       a->encoding == ENCUUENCODED)
1031     body_list_wipe(&b);
1032
1033   return (rc);
1034 }
1035
1036 static int autoview_handler (BODY * a, STATE * s)
1037 {
1038   rfc1524_entry *entry = rfc1524_entry_new();
1039   char buffer[LONG_STRING];
1040   char type[STRING];
1041   char command[LONG_STRING];
1042   char tempfile[_POSIX_PATH_MAX] = "";
1043   char *fname;
1044   FILE *fpin = NULL;
1045   FILE *fpout = NULL;
1046   FILE *fperr = NULL;
1047   int piped = FALSE;
1048   pid_t thepid;
1049   int rc = 0;
1050
1051   snprintf (type, sizeof (type), "%s/%s", TYPE (a), a->subtype);
1052   rfc1524_mailcap_lookup (a, type, entry, M_AUTOVIEW);
1053
1054   fname = m_strdup(a->filename);
1055   mutt_sanitize_filename (fname, 1);
1056   rfc1524_expand_filename (entry->nametemplate, fname, tempfile,
1057                            sizeof (tempfile));
1058   p_delete(&fname);
1059
1060   if (entry->command) {
1061     m_strcpy(command, sizeof(command), entry->command);
1062
1063     /* rfc1524_expand_command returns 0 if the file is required */
1064     piped =
1065       rfc1524_expand_command (a, tempfile, type, command, sizeof (command));
1066
1067     if (s->flags & M_DISPLAY) {
1068       state_mark_attach (s);
1069       state_printf (s, _("[-- Autoview using %s --]\n"), command);
1070       mutt_message (_("Invoking autoview command: %s"), command);
1071     }
1072
1073     if ((fpin = safe_fopen (tempfile, "w+")) == NULL) {
1074       mutt_perror ("fopen");
1075       rfc1524_entry_delete(&entry);
1076       return (-1);
1077     }
1078
1079     mutt_copy_bytes (s->fpin, fpin, a->length);
1080
1081     if (!piped) {
1082       m_fclose(&fpin);
1083       thepid = mutt_create_filter (command, NULL, &fpout, &fperr);
1084     } else {
1085       unlink (tempfile);
1086       fflush (fpin);
1087       rewind (fpin);
1088       thepid = mutt_create_filter_fd (command, NULL, &fpout, &fperr,
1089                                       fileno (fpin), -1, -1);
1090     }
1091
1092     if (thepid < 0) {
1093       mutt_perror (_("Can't create filter"));
1094
1095       if (s->flags & M_DISPLAY) {
1096         state_mark_attach (s);
1097         state_printf (s, _("[-- Can't run %s. --]\n"), command);
1098       }
1099       rc = -1;
1100       goto bail;
1101     }
1102
1103     if (s->prefix) {
1104       while (fgets (buffer, sizeof (buffer), fpout) != NULL) {
1105         state_puts (s->prefix, s);
1106         state_puts (buffer, s);
1107       }
1108       /* check for data on stderr */
1109       if (fgets (buffer, sizeof (buffer), fperr)) {
1110         if (s->flags & M_DISPLAY) {
1111           state_mark_attach (s);
1112           state_printf (s, _("[-- Autoview stderr of %s --]\n"), command);
1113         }
1114
1115         state_puts (s->prefix, s);
1116         state_puts (buffer, s);
1117         while (fgets (buffer, sizeof (buffer), fperr) != NULL) {
1118           state_puts (s->prefix, s);
1119           state_puts (buffer, s);
1120         }
1121       }
1122     } else {
1123       mutt_copy_stream (fpout, s->fpout);
1124       /* Check for stderr messages */
1125       if (fgets (buffer, sizeof (buffer), fperr)) {
1126         if (s->flags & M_DISPLAY) {
1127           state_mark_attach (s);
1128           state_printf (s, _("[-- Autoview stderr of %s --]\n"), command);
1129         }
1130
1131         state_puts (buffer, s);
1132         mutt_copy_stream (fperr, s->fpout);
1133       }
1134     }
1135
1136   bail:
1137     m_fclose(&fpout);
1138     m_fclose(&fperr);
1139
1140     mutt_wait_filter (thepid);
1141     if (piped)
1142       m_fclose(&fpin);
1143     else
1144       mutt_unlink (tempfile);
1145
1146     if (s->flags & M_DISPLAY)
1147       mutt_clear_error ();
1148   }
1149   rfc1524_entry_delete(&entry);
1150   return (rc);
1151 }
1152
1153 static int external_body_handler (BODY * b, STATE * s)
1154 {
1155   const char *access_type;
1156   const char *expiration;
1157   time_t expire;
1158
1159   access_type = parameter_getval(b->parameter, "access-type");
1160   if (!access_type) {
1161     if (s->flags & M_DISPLAY) {
1162       state_mark_attach (s);
1163       state_puts (_("[-- Error: message/external-body has no access-type parameter --]\n"), s);
1164     }
1165     return (-1);
1166   }
1167
1168   expiration = parameter_getval(b->parameter, "expiration");
1169   if (expiration)
1170     expire = mutt_parse_date (expiration, NULL);
1171   else
1172     expire = -1;
1173
1174   if (!ascii_strcasecmp (access_type, "x-mutt-deleted")) {
1175     if (s->flags & (M_DISPLAY | M_PRINTING)) {
1176       char *length;
1177       char pretty_size[10];
1178
1179       state_mark_attach (s);
1180       state_printf (s, _("[-- This %s/%s attachment "),
1181                     TYPE (b->parts), b->parts->subtype);
1182       length = parameter_getval(b->parameter, "length");
1183       if (length) {
1184         mutt_pretty_size (pretty_size, sizeof (pretty_size),
1185                           strtol (length, NULL, 10));
1186         state_printf (s, _("(size %s bytes) "), pretty_size);
1187       }
1188       state_puts (_("has been deleted --]\n"), s);
1189
1190       if (expire != -1) {
1191         state_mark_attach (s);
1192         state_printf (s, _("[-- on %s --]\n"), expiration);
1193       }
1194       if (b->parts->filename) {
1195         state_mark_attach (s);
1196         state_printf (s, _("[-- name: %s --]\n"), b->parts->filename);
1197       }
1198
1199       mutt_copy_hdr (s->fpin, s->fpout, ftello (s->fpin), b->parts->offset,
1200                      (option (OPTWEED) ? (CH_WEED | CH_REORDER) : 0) |
1201                      CH_DECODE, NULL);
1202     }
1203   }
1204   else if (expiration && expire < time (NULL)) {
1205     if (s->flags & M_DISPLAY) {
1206       state_mark_attach (s);
1207       state_printf (s, _("[-- This %s/%s attachment is not included, --]\n"),
1208                     TYPE (b->parts), b->parts->subtype);
1209       state_attach_puts (_("[-- and the indicated external source has --]\n"
1210                            "[-- expired. --]\n"), s);
1211
1212       mutt_copy_hdr (s->fpin, s->fpout, ftello (s->fpin), b->parts->offset,
1213                      (option (OPTWEED) ? (CH_WEED | CH_REORDER) : 0) |
1214                      CH_DECODE, NULL);
1215     }
1216   } else {
1217     if (s->flags & M_DISPLAY) {
1218       state_mark_attach (s);
1219       state_printf (s,
1220                     _("[-- This %s/%s attachment is not included, --]\n"),
1221                     TYPE (b->parts), b->parts->subtype);
1222       state_mark_attach (s);
1223       state_printf (s,
1224                     _
1225                     ("[-- and the indicated access-type %s is unsupported --]\n"),
1226                     access_type);
1227       mutt_copy_hdr (s->fpin, s->fpout, ftello (s->fpin), b->parts->offset,
1228                      (option (OPTWEED) ? (CH_WEED | CH_REORDER) : 0) |
1229                      CH_DECODE, NULL);
1230     }
1231   }
1232   return (0);
1233 }
1234
1235 void mutt_decode_attachment (BODY * b, STATE * s)
1236 {
1237   int istext = mutt_is_text_part (b);
1238   iconv_t cd = MUTT_ICONV_ERROR;
1239
1240   Quotebuf[0] = '\0';
1241
1242   if (istext) {
1243     if (s->flags & M_CHARCONV) {
1244       const char *charset = parameter_getval(b->parameter, "charset");
1245
1246       if (!charset)
1247         charset = charset_getfirst(AssumedCharset);
1248       if (charset && Charset)
1249         cd = mutt_iconv_open (Charset, charset, M_ICONV_HOOK_FROM);
1250     } else {
1251       if (b->file_charset)
1252         cd = mutt_iconv_open (Charset, b->file_charset, M_ICONV_HOOK_FROM);
1253     }
1254   }
1255
1256   fseeko (s->fpin, b->offset, 0);
1257   switch (b->encoding) {
1258   case ENCQUOTEDPRINTABLE:
1259     mutt_decode_quoted(s, b->length,
1260                        istext || mutt_is_application_pgp(b), cd);
1261     break;
1262   case ENCBASE64:
1263     mutt_decode_base64(s, b->length,
1264                        istext || mutt_is_application_pgp(b), cd);
1265     break;
1266   case ENCUUENCODED:
1267     mutt_decode_uuencoded(s, b->length,
1268                           istext || mutt_is_application_pgp(b), cd);
1269     break;
1270   default:
1271     mutt_decode_xbit(s, b->length,
1272                      istext || mutt_is_application_pgp(b), cd);
1273     break;
1274   }
1275
1276   if (cd != MUTT_ICONV_ERROR)
1277     iconv_close (cd);
1278 }
1279
1280 int mutt_body_handler (BODY * b, STATE * s)
1281 {
1282   int decode = 0;
1283   int plaintext = 0;
1284   FILE *fp = NULL;
1285   char tempfile[_POSIX_PATH_MAX];
1286   handler_t handler = NULL;
1287   long tmpoffset = 0;
1288   ssize_t tmplength = 0;
1289   char type[STRING];
1290   int rc = 0;
1291
1292   int oflags = s->flags;
1293
1294   /* first determine which handler to use to process this part */
1295
1296   snprintf (type, sizeof (type), "%s/%s", TYPE (b), b->subtype);
1297   if (mutt_is_autoview (b, type)) {
1298     rfc1524_entry *entry = rfc1524_entry_new();
1299
1300     if (rfc1524_mailcap_lookup (b, type, entry, M_AUTOVIEW)) {
1301       handler = autoview_handler;
1302       s->flags &= ~M_CHARCONV;
1303     }
1304     rfc1524_entry_delete(&entry);
1305   }
1306   else if (b->type == TYPETEXT) {
1307     if (ascii_strcasecmp ("plain", b->subtype) == 0) {
1308       /* avoid copying this part twice since removing the transfer-encoding is
1309        * the only operation needed.
1310        */
1311       if (mutt_is_application_pgp (b))
1312         handler = crypt_pgp_application_pgp_handler;
1313       else
1314         if (!ascii_strcasecmp("flowed", parameter_getval(b->parameter, "format")))
1315           handler = rfc3676_handler;
1316       else
1317         plaintext = 1;
1318     }
1319     else if (ascii_strcasecmp ("enriched", b->subtype) == 0)
1320       handler = text_enriched_handler;
1321     else                        /* text body type without a handler */
1322       plaintext = 1;
1323   }
1324   else if (b->type == TYPEMESSAGE) {
1325     if (mutt_is_message_type (b))
1326       handler = message_handler;
1327     else if (!ascii_strcasecmp ("delivery-status", b->subtype))
1328       plaintext = 1;
1329     else if (!ascii_strcasecmp ("external-body", b->subtype))
1330       handler = external_body_handler;
1331   }
1332   else if (b->type == TYPEMULTIPART) {
1333     char *p;
1334
1335     if (ascii_strcasecmp ("alternative", b->subtype) == 0)
1336       handler = alternative_handler;
1337     else if (ascii_strcasecmp ("signed", b->subtype) == 0) {
1338       p = parameter_getval(b->parameter, "protocol");
1339
1340       if (!p)
1341         mutt_error (_("Error: multipart/signed has no protocol."));
1342
1343       else if (s->flags & M_VERIFY)
1344         handler = mutt_signed_handler;
1345     }
1346     else if (m_strcasecmp("encrypted", b->subtype) == 0) {
1347       p = parameter_getval(b->parameter, "protocol");
1348
1349       if (!p)
1350         mutt_error (_
1351                     ("Error: multipart/encrypted has no protocol parameter!"));
1352
1353       else if (ascii_strcasecmp ("application/pgp-encrypted", p) == 0)
1354         handler = crypt_pgp_encrypted_handler;
1355     }
1356
1357     if (!handler)
1358       handler = multipart_handler;
1359   }
1360   else if (b->type == TYPEAPPLICATION) {
1361     if (mutt_is_application_pgp (b))
1362       handler = crypt_pgp_application_pgp_handler;
1363     if (mutt_is_application_smime (b))
1364       handler = crypt_smime_application_smime_handler;
1365   }
1366
1367
1368   if (plaintext || handler) {
1369     fseeko (s->fpin, b->offset, 0);
1370
1371     /* see if we need to decode this part before processing it */
1372     if (b->encoding == ENCBASE64 || b->encoding == ENCQUOTEDPRINTABLE
1373     ||  b->encoding == ENCUUENCODED || plaintext || mutt_is_text_part (b)) {
1374         /* text subtypes may require character set conversion even with 8bit
1375            encoding.  */
1376       int origType = b->type;
1377       char *savePrefix = NULL;
1378
1379       if (!plaintext) {
1380         /* decode to a tempfile, saving the original destination */
1381         fp = s->fpout;
1382         s->fpout = m_tempfile(tempfile, sizeof(tempfile), NONULL(Tempdir), NULL);
1383         if (!s->fpout) {
1384           mutt_error _("Unable to open temporary file!");
1385           goto bail;
1386         }
1387         /* decoding the attachment changes the size and offset, so save a copy
1388          * of the "real" values now, and restore them after processing
1389          */
1390         tmplength = b->length;
1391         tmpoffset = b->offset;
1392
1393         /* if we are decoding binary bodies, we don't want to prefix each
1394          * line with the prefix or else the data will get corrupted.
1395          */
1396         savePrefix = s->prefix;
1397         s->prefix = NULL;
1398
1399         decode = 1;
1400       } else {
1401         b->type = TYPETEXT;
1402       }
1403
1404       mutt_decode_attachment (b, s);
1405
1406       if (decode) {
1407         b->length = ftello (s->fpout);
1408         b->offset = 0;
1409         m_fclose(&s->fpout);
1410
1411         /* restore final destination and substitute the tempfile for input */
1412         s->fpout = fp;
1413         fp = s->fpin;
1414         s->fpin = safe_fopen (tempfile, "r");
1415         unlink (tempfile);
1416
1417         /* restore the prefix */
1418         s->prefix = savePrefix;
1419       }
1420
1421       b->type = origType;
1422     }
1423
1424     /* process the (decoded) body part */
1425     if (handler) {
1426       rc = handler (b, s);
1427
1428       if (decode) {
1429         b->length = tmplength;
1430         b->offset = tmpoffset;
1431
1432         /* restore the original source stream */
1433         m_fclose(&s->fpin);
1434         s->fpin = fp;
1435       }
1436     }
1437     s->flags |= M_FIRSTDONE;
1438   }
1439   else if (s->flags & M_DISPLAY) {
1440     state_mark_attach (s);
1441     state_printf (s, _("[-- %s/%s is unsupported "), TYPE (b), b->subtype);
1442     if (!option (OPTVIEWATTACH)) {
1443       if (km_expand_key
1444           (type, sizeof (type),
1445            km_find_func (MENU_PAGER, OP_VIEW_ATTACHMENTS)))
1446         fprintf (s->fpout, _("(use '%s' to view this part)"), type);
1447       else
1448         fputs (_("(need 'view-attachments' bound to key!)"), s->fpout);
1449     }
1450     fputs (" --]\n", s->fpout);
1451   }
1452
1453 bail:
1454   s->flags = oflags | (s->flags & M_FIRSTDONE);
1455
1456   return (rc);
1457 }