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