d043331d8d1b3c76033ad37b95534411704aac08
[apps/madmutt.git] / parse.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 <lib-lib/mem.h>
15 #include <lib-lib/str.h>
16 #include <lib-lib/ascii.h>
17 #include <lib-lib/macros.h>
18 #include <lib-lib/buffer.h>
19
20 #include <lib-mime/mime.h>
21
22 #include "mutt.h"
23 #include "enter.h"
24 #include "recvattach.h"
25 #include "mx.h"
26 #include "mutt_crypt.h"
27 #include "url.h"
28
29 #include "lib/rx.h"
30 #include "lib/debug.h"
31
32 #include <string.h>
33 #include <ctype.h>
34 #include <sys/stat.h>
35 #include <stdlib.h>
36
37 /* Reads an arbitrarily long header field, and looks ahead for continuation
38  * lines.  ``line'' must point to a dynamically allocated string; it is
39  * increased if more space is required to fit the whole line.
40  */
41 char *mutt_read_rfc822_line (FILE * f, char *line, size_t * linelen)
42 {
43   char *buf = line;
44   char ch;
45   size_t offset = 0;
46
47   for (;;) {
48     if (fgets (buf, *linelen - offset, f) == NULL ||    /* end of file or */
49         (ISSPACE (*line) && !offset)) { /* end of headers */
50       *line = 0;
51       return (line);
52     }
53
54     buf += m_strlen(buf) - 1;
55     if (*buf == '\n') {
56       /* we did get a full line. remove trailing space */
57       while (ISSPACE (*buf))
58         *buf-- = 0;             /* we cannot come beyond line's beginning because
59                                  * it begins with a non-space */
60
61       /* check to see if the next line is a continuation line */
62       if ((ch = fgetc (f)) != ' ' && ch != '\t') {
63         ungetc (ch, f);
64         return (line);          /* next line is a separate header field or EOH */
65       }
66
67       /* eat tabs and spaces from the beginning of the continuation line */
68       while ((ch = fgetc (f)) == ' ' || ch == '\t');
69       ungetc (ch, f);
70       *++buf = ' ';             /* string is still terminated because we removed
71                                    at least one whitespace char above */
72     }
73
74     buf++;
75     offset = buf - line;
76     if (*linelen < offset + STRING) {
77       /* grow the buffer */
78       *linelen += STRING;
79       p_realloc(&line, *linelen);
80       buf = line + offset;
81     }
82   }
83   /* not reached */
84 }
85
86 LIST *mutt_parse_references (char *s, int in_reply_to)
87 {
88   LIST *t, *lst = NULL;
89   int m, n = 0;
90   char *o = NULL, *new, *at;
91
92   while ((s = strtok (s, " \t;")) != NULL) {
93     /*
94      * some mail clients add other garbage besides message-ids, so do a quick
95      * check to make sure this looks like a valid message-id
96      * some idiotic clients also break their message-ids between lines, deal
97      * with that too (give up if it's more than two lines, though)
98      */
99     t = NULL;
100     new = NULL;
101
102     if (*s == '<') {
103       n = m_strlen(s);
104       if (s[n - 1] != '>') {
105         o = s;
106         s = NULL;
107         continue;
108       }
109
110       new = m_strdup(s);
111     }
112     else if (o) {
113       m = m_strlen(s);
114       if (s[m - 1] == '>') {
115         new = p_new(char, n + m + 1);
116         strcpy (new, o);        /* __STRCPY_CHECKED__ */
117         strcpy (new + n, s);    /* __STRCPY_CHECKED__ */
118       }
119     }
120     if (new) {
121       /* make sure that this really does look like a message-id.
122        * it should have exactly one @, and if we're looking at
123        * an in-reply-to header, make sure that the part before
124        * the @ has more than eight characters or it's probably
125        * an email address
126        */
127       if (!(at = strchr (new, '@')) || strchr (at + 1, '@')
128           || (in_reply_to && at - new <= 8))
129         p_delete(&new);
130       else {
131         t = p_new(LIST, 1);
132         t->data = new;
133         t->next = lst;
134         lst = t;
135       }
136     }
137     o = NULL;
138     s = NULL;
139   }
140
141   return (lst);
142 }
143
144 int mutt_check_encoding (const char *c)
145 {
146   if (ascii_strncasecmp ("7bit", c, sizeof ("7bit") - 1) == 0)
147     return (ENC7BIT);
148   else if (ascii_strncasecmp ("8bit", c, sizeof ("8bit") - 1) == 0)
149     return (ENC8BIT);
150   else if (ascii_strncasecmp ("binary", c, sizeof ("binary") - 1) == 0)
151     return (ENCBINARY);
152   else
153     if (ascii_strncasecmp
154         ("quoted-printable", c, sizeof ("quoted-printable") - 1) == 0)
155     return (ENCQUOTEDPRINTABLE);
156   else if (ascii_strncasecmp ("base64", c, sizeof ("base64") - 1) == 0)
157     return (ENCBASE64);
158   else if (ascii_strncasecmp ("x-uuencode", c, sizeof ("x-uuencode") - 1) ==
159            0)
160     return (ENCUUENCODED);
161 #ifdef SUN_ATTACHMENT
162   else if (ascii_strncasecmp ("uuencode", c, sizeof ("uuencode") - 1) == 0)
163     return (ENCUUENCODED);
164 #endif
165   else
166     return (ENCOTHER);
167 }
168
169 static PARAMETER *parse_parameters (const char *s)
170 {
171   PARAMETER *head = 0, *cur = 0, *new;
172   char buffer[LONG_STRING];
173   const char *p;
174   size_t i;
175
176   debug_print (2, ("`%s'\n", s));
177
178   while (*s) {
179     if ((p = strpbrk (s, "=;")) == NULL) {
180       debug_print (1, ("malformed parameter: %s\n", s));
181       goto bail;
182     }
183
184     /* if we hit a ; now the parameter has no value, just skip it */
185     if (*p != ';') {
186       i = p - s;
187
188       new = mutt_new_parameter ();
189
190       new->attribute = p_dupstr(s, i);
191
192       /* remove whitespace from the end of the attribute name */
193       while (ISSPACE (new->attribute[--i]))
194         new->attribute[i] = 0;
195
196       s = vskipspaces(p + 1);     /* skip over the = */
197
198       if (*s == '"') {
199         int state_ascii = 1;
200
201         s++;
202         for (i = 0; *s && i < sizeof (buffer) - 1; i++, s++) {
203           if (!option (OPTSTRICTMIME)) {
204             /* As iso-2022-* has a characer of '"' with non-ascii state,
205              * ignore it. */
206             if (*s == 0x1b && i < sizeof (buffer) - 2) {
207               if (s[1] == '(' && (s[2] == 'B' || s[2] == 'J'))
208                 state_ascii = 1;
209               else
210                 state_ascii = 0;
211             }
212           }
213           if (state_ascii && *s == '"')
214             break;
215           if (*s == '\\') {
216             /* Quote the next character */
217             buffer[i] = s[1];
218             if (!*++s)
219               break;
220           }
221           else
222             buffer[i] = *s;
223         }
224         buffer[i] = 0;
225         if (*s)
226           s++;                  /* skip over the " */
227       }
228       else {
229         for (i = 0; *s && *s != ' ' && *s != ';' && i < sizeof (buffer) - 1;
230              i++, s++)
231           buffer[i] = *s;
232         buffer[i] = 0;
233       }
234
235       new->value = m_strdup(buffer);
236
237       debug_print (2, ("`%s' = `%s'\n", new->attribute ? new->attribute : "",
238                   new->value ? new->value : ""));
239
240       /* Add this parameter to the list */
241       if (head) {
242         cur->next = new;
243         cur = cur->next;
244       }
245       else
246         head = cur = new;
247     }
248     else {
249       debug_print (1, ("parameter with no value: %s\n", s));
250       s = p;
251     }
252
253     /* Find the next parameter */
254     if (*s != ';' && (s = strchr (s, ';')) == NULL)
255       break;                    /* no more parameters */
256
257     do {
258       /* Move past any leading whitespace */
259       s = vskipspaces(s + 1);
260     }
261     while (*s == ';');          /* skip empty parameters */
262   }
263
264 bail:
265
266   rfc2231_decode_parameters (&head);
267   return (head);
268 }
269
270 int mutt_check_mime_type (const char *s)
271 {
272   if (ascii_strcasecmp ("text", s) == 0)
273     return TYPETEXT;
274   else if (ascii_strcasecmp ("multipart", s) == 0)
275     return TYPEMULTIPART;
276 #ifdef SUN_ATTACHMENT
277   else if (ascii_strcasecmp ("x-sun-attachment", s) == 0)
278     return TYPEMULTIPART;
279 #endif
280   else if (ascii_strcasecmp ("application", s) == 0)
281     return TYPEAPPLICATION;
282   else if (ascii_strcasecmp ("message", s) == 0)
283     return TYPEMESSAGE;
284   else if (ascii_strcasecmp ("image", s) == 0)
285     return TYPEIMAGE;
286   else if (ascii_strcasecmp ("audio", s) == 0)
287     return TYPEAUDIO;
288   else if (ascii_strcasecmp ("video", s) == 0)
289     return TYPEVIDEO;
290   else if (ascii_strcasecmp ("model", s) == 0)
291     return TYPEMODEL;
292   else if (ascii_strcasecmp ("*", s) == 0)
293     return TYPEANY;
294   else if (ascii_strcasecmp (".*", s) == 0)
295     return TYPEANY;
296   else
297     return TYPEOTHER;
298 }
299
300 void mutt_parse_content_type (char *s, BODY * ct)
301 {
302   char *pc;
303   char *subtype;
304
305   p_delete(&ct->subtype);
306   mutt_free_parameter (&ct->parameter);
307
308   /* First extract any existing parameters */
309   if ((pc = strchr (s, ';')) != NULL) {
310     *pc++ = 0;
311     while (*pc && ISSPACE (*pc))
312       pc++;
313     ct->parameter = parse_parameters (pc);
314
315     /* Some pre-RFC1521 gateways still use the "name=filename" convention,
316      * but if a filename has already been set in the content-disposition,
317      * let that take precedence, and don't set it here */
318     if ((pc = mutt_get_parameter ("name", ct->parameter)) != 0
319         && !ct->filename)
320       ct->filename = m_strdup(pc);
321
322 #ifdef SUN_ATTACHMENT
323     /* this is deep and utter perversion */
324     if ((pc = mutt_get_parameter ("conversions", ct->parameter)) != 0)
325       ct->encoding = mutt_check_encoding (pc);
326 #endif
327
328   }
329
330   /* Now get the subtype */
331   if ((subtype = strchr (s, '/'))) {
332     *subtype++ = '\0';
333     for (pc = subtype; *pc && !ISSPACE (*pc) && *pc != ';'; pc++);
334     *pc = '\0';
335     ct->subtype = m_strdup(subtype);
336   }
337
338   /* Finally, get the major type */
339   ct->type = mutt_check_mime_type (s);
340
341 #ifdef SUN_ATTACHMENT
342   if (ascii_strcasecmp ("x-sun-attachment", s) == 0)
343     ct->subtype = m_strdup("x-sun-attachment");
344 #endif
345
346   if (ct->type == TYPEOTHER) {
347     ct->xtype = m_strdup(s);
348   }
349
350   if (ct->subtype == NULL) {
351     /* Some older non-MIME mailers (i.e., mailtool, elm) have a content-type
352      * field, so we can attempt to convert the type to BODY here.
353      */
354     if (ct->type == TYPETEXT)
355       ct->subtype = m_strdup("plain");
356     else if (ct->type == TYPEAUDIO)
357       ct->subtype = m_strdup("basic");
358     else if (ct->type == TYPEMESSAGE)
359       ct->subtype = m_strdup("rfc822");
360     else if (ct->type == TYPEOTHER) {
361       char buffer[SHORT_STRING];
362
363       ct->type = TYPEAPPLICATION;
364       snprintf (buffer, sizeof (buffer), "x-%s", s);
365       ct->subtype = m_strdup(buffer);
366     }
367     else
368       ct->subtype = m_strdup("x-unknown");
369   }
370
371   /* Default character set for text types. */
372   if (ct->type == TYPETEXT) {
373     if (!(pc = mutt_get_parameter ("charset", ct->parameter)))
374       mutt_set_parameter ("charset", option (OPTSTRICTMIME) ? "us-ascii" :
375                           (const char *)
376                           mutt_get_first_charset (AssumedCharset),
377                           &ct->parameter);
378   }
379
380 }
381
382 static void parse_content_disposition (char *s, BODY * ct)
383 {
384   PARAMETER *parms;
385
386   if (!ascii_strncasecmp ("inline", s, 6))
387     ct->disposition = DISPINLINE;
388   else if (!ascii_strncasecmp ("form-data", s, 9))
389     ct->disposition = DISPFORMDATA;
390   else
391     ct->disposition = DISPATTACH;
392
393   /* Check to see if a default filename was given */
394   if ((s = strchr (s, ';')) != NULL) {
395     s = vskipspaces(s + 1);
396     if ((s = mutt_get_parameter("filename",
397                                 (parms = parse_parameters (s)))) != 0)
398       m_strreplace(&ct->filename, s);
399     if ((s = mutt_get_parameter ("name", parms)) != 0)
400       ct->form_name = m_strdup(s);
401     mutt_free_parameter (&parms);
402   }
403 }
404
405 /* args:
406  *      fp      stream to read from
407  *
408  *      digest  1 if reading subparts of a multipart/digest, 0
409  *              otherwise
410  */
411
412 BODY *mutt_read_mime_header (FILE * fp, int digest)
413 {
414   BODY *p = mutt_new_body ();
415   char *c;
416   char *line = p_new(char, LONG_STRING);
417   size_t linelen = LONG_STRING;
418
419   p->hdr_offset = ftello (fp);
420
421   p->encoding = ENC7BIT;        /* default from RFC1521 */
422   p->type = digest ? TYPEMESSAGE : TYPETEXT;
423   p->disposition = DISPINLINE;
424
425   while (*(line = mutt_read_rfc822_line (fp, line, &linelen)) != 0) {
426     /* Find the value of the current header */
427     if ((c = strchr (line, ':'))) {
428       *c++ = 0;
429       c = vskipspaces(c);
430       if (!*c) {
431         debug_print (1, ("skipping empty header field: %s\n", line));
432         continue;
433       }
434     }
435     else {
436       debug_print (1, ("bogus MIME header: %s\n", line));
437       break;
438     }
439
440     if (!ascii_strncasecmp ("content-", line, 8)) {
441       if (!ascii_strcasecmp ("type", line + 8))
442         mutt_parse_content_type (c, p);
443       else if (!ascii_strcasecmp ("transfer-encoding", line + 8))
444         p->encoding = mutt_check_encoding (c);
445       else if (!ascii_strcasecmp ("disposition", line + 8))
446         parse_content_disposition (c, p);
447       else if (!ascii_strcasecmp ("description", line + 8)) {
448         m_strreplace(&p->description, c);
449         rfc2047_decode (&p->description);
450       }
451     }
452 #ifdef SUN_ATTACHMENT
453     else if (!ascii_strncasecmp ("x-sun-", line, 6)) {
454       if (!ascii_strcasecmp ("data-type", line + 6))
455         mutt_parse_content_type (c, p);
456       else if (!ascii_strcasecmp ("encoding-info", line + 6))
457         p->encoding = mutt_check_encoding (c);
458       else if (!ascii_strcasecmp ("content-lines", line + 6))
459         mutt_set_parameter ("content-lines", c, &(p->parameter));
460       else if (!ascii_strcasecmp ("data-description", line + 6)) {
461         m_strreplace(&p->description, c);
462         rfc2047_decode (&p->description);
463       }
464     }
465 #endif
466   }
467   p->offset = ftello (fp);       /* Mark the start of the real data */
468   if (p->type == TYPETEXT && !p->subtype)
469     p->subtype = m_strdup("plain");
470   else if (p->type == TYPEMESSAGE && !p->subtype)
471     p->subtype = m_strdup("rfc822");
472
473   p_delete(&line);
474
475   return (p);
476 }
477
478 void mutt_parse_part (FILE * fp, BODY * b)
479 {
480   char *bound = 0;
481
482   switch (b->type) {
483   case TYPEMULTIPART:
484 #ifdef SUN_ATTACHMENT
485     if (!ascii_strcasecmp (b->subtype, "x-sun-attachment"))
486       bound = "--------";
487     else
488 #endif
489       bound = mutt_get_parameter ("boundary", b->parameter);
490
491     fseeko (fp, b->offset, SEEK_SET);
492     b->parts = mutt_parse_multipart (fp, bound,
493                                      b->offset + b->length,
494                                      ascii_strcasecmp ("digest",
495                                                        b->subtype) == 0);
496     break;
497
498   case TYPEMESSAGE:
499     if (b->subtype) {
500       fseeko (fp, b->offset, SEEK_SET);
501       if (mutt_is_message_type (b->type, b->subtype))
502         b->parts = mutt_parse_messageRFC822 (fp, b);
503       else if (ascii_strcasecmp (b->subtype, "external-body") == 0)
504         b->parts = mutt_read_mime_header (fp, 0);
505       else
506         return;
507     }
508     break;
509
510   default:
511     return;
512   }
513
514   /* try to recover from parsing error */
515   if (!b->parts) {
516     b->type = TYPETEXT;
517     m_strreplace(&b->subtype, "plain");
518   }
519 }
520
521 /* parse a MESSAGE/RFC822 body
522  *
523  * args:
524  *      fp              stream to read from
525  *
526  *      parent          structure which contains info about the message/rfc822
527  *                      body part
528  *
529  * NOTE: this assumes that `parent->length' has been set!
530  */
531
532 BODY *mutt_parse_messageRFC822 (FILE * fp, BODY * parent)
533 {
534   BODY *msg;
535
536   parent->hdr = mutt_new_header ();
537   parent->hdr->offset = ftello (fp);
538   parent->hdr->env = mutt_read_rfc822_header (fp, parent->hdr, 0, 0);
539   msg = parent->hdr->content;
540
541   /* ignore the length given in the content-length since it could be wrong
542      and we already have the info to calculate the correct length */
543   /* if (msg->length == -1) */
544   msg->length = parent->length - (msg->offset - parent->offset);
545
546   /* if body of this message is empty, we can end up with a negative length */
547   if (msg->length < 0)
548     msg->length = 0;
549
550   mutt_parse_part (fp, msg);
551   return (msg);
552 }
553
554 /* parse a multipart structure
555  *
556  * args:
557  *      fp              stream to read from
558  *
559  *      boundary        body separator
560  *
561  *      end_off         length of the multipart body (used when the final
562  *                      boundary is missing to avoid reading too far)
563  *
564  *      digest          1 if reading a multipart/digest, 0 otherwise
565  */
566
567 BODY *mutt_parse_multipart (FILE * fp, const char *boundary, off_t end_off,
568                             int digest)
569 {
570 #ifdef SUN_ATTACHMENT
571   int lines;
572 #endif
573   int blen, len, crlf = 0;
574   char buffer[LONG_STRING];
575   BODY *head = 0, *last = 0, *new = 0;
576   int i;
577   int final = 0;                /* did we see the ending boundary? */
578
579   if (!boundary) {
580     mutt_error _("multipart message has no boundary parameter!");
581
582     return (NULL);
583   }
584
585   blen = m_strlen(boundary);
586   while (ftello (fp) < end_off && fgets (buffer, LONG_STRING, fp) != NULL) {
587     len = m_strlen(buffer);
588
589     crlf = (len > 1 && buffer[len - 2] == '\r') ? 1 : 0;
590
591     if (buffer[0] == '-' && buffer[1] == '-' &&
592         m_strncmp(buffer + 2, boundary, blen) == 0) {
593       if (last) {
594         last->length = ftello (fp) - last->offset - len - 1 - crlf;
595         if (last->parts && last->parts->length == 0)
596           last->parts->length =
597             ftello (fp) - last->parts->offset - len - 1 - crlf;
598         /* if the body is empty, we can end up with a -1 length */
599         if (last->length < 0)
600           last->length = 0;
601       }
602
603       /* Remove any trailing whitespace, up to the length of the boundary */
604       for (i = len - 1; ISSPACE (buffer[i]) && i >= blen + 2; i--)
605         buffer[i] = 0;
606
607       /* Check for the end boundary */
608       if (m_strcmp(buffer + blen + 2, "--") == 0) {
609         final = 1;
610         break;                  /* done parsing */
611       }
612       else if (buffer[2 + blen] == 0) {
613         new = mutt_read_mime_header (fp, digest);
614
615 #ifdef SUN_ATTACHMENT
616         if (mutt_get_parameter ("content-lines", new->parameter)) {
617           for (lines =
618                atoi (mutt_get_parameter ("content-lines", new->parameter));
619                lines; lines--)
620             if (ftello (fp) >= end_off
621                 || fgets (buffer, LONG_STRING, fp) == NULL)
622               break;
623         }
624 #endif
625
626         /*
627          * Consistency checking - catch
628          * bad attachment end boundaries
629          */
630
631         if (new->offset > end_off) {
632           mutt_free_body (&new);
633           break;
634         }
635         if (head) {
636           last->next = new;
637           last = new;
638         }
639         else
640           last = head = new;
641       }
642     }
643   }
644
645   /* in case of missing end boundary, set the length to something reasonable */
646   if (last && last->length == 0 && !final)
647     last->length = end_off - last->offset;
648
649   /* parse recursive MIME parts */
650   for (last = head; last; last = last->next)
651     mutt_parse_part (fp, last);
652
653   return (head);
654 }
655
656 static const char *uncomment_timezone (char *buf, size_t buflen,
657                                        const char *tz)
658 {
659   char *p;
660   size_t len;
661
662   if (*tz != '(')
663     return tz;                  /* no need to do anything */
664   tz = vskipspaces(tz + 1);
665   if ((p = strpbrk (tz, " )")) == NULL)
666     return tz;
667   len = p - tz;
668   if (len > buflen - 1)
669     len = buflen - 1;
670   memcpy (buf, tz, len);
671   buf[len] = 0;
672   return buf;
673 }
674
675 static struct tz_t {
676   char tzname[5];
677   unsigned char zhours;
678   unsigned char zminutes;
679   unsigned char zoccident;      /* west of UTC? */
680 } TimeZones[] = {
681   {
682   "aat", 1, 0, 1},              /* Atlantic Africa Time */
683   {
684   "adt", 4, 0, 0},              /* Arabia DST */
685   {
686   "ast", 3, 0, 0},              /* Arabia */
687     /*{ "ast",   4,  0, 1 }, *//* Atlantic */
688   {
689   "bst", 1, 0, 0},              /* British DST */
690   {
691   "cat", 1, 0, 0},              /* Central Africa */
692   {
693   "cdt", 5, 0, 1}, {
694   "cest", 2, 0, 0},             /* Central Europe DST */
695   {
696   "cet", 1, 0, 0},              /* Central Europe */
697   {
698   "cst", 6, 0, 1},
699     /*{ "cst",   8,  0, 0 }, *//* China */
700     /*{ "cst",   9, 30, 0 }, *//* Australian Central Standard Time */
701   {
702   "eat", 3, 0, 0},              /* East Africa */
703   {
704   "edt", 4, 0, 1}, {
705   "eest", 3, 0, 0},             /* Eastern Europe DST */
706   {
707   "eet", 2, 0, 0},              /* Eastern Europe */
708   {
709   "egst", 0, 0, 0},             /* Eastern Greenland DST */
710   {
711   "egt", 1, 0, 1},              /* Eastern Greenland */
712   {
713   "est", 5, 0, 1}, {
714   "gmt", 0, 0, 0}, {
715   "gst", 4, 0, 0},              /* Presian Gulf */
716   {
717   "hkt", 8, 0, 0},              /* Hong Kong */
718   {
719   "ict", 7, 0, 0},              /* Indochina */
720   {
721   "idt", 3, 0, 0},              /* Israel DST */
722   {
723   "ist", 2, 0, 0},              /* Israel */
724     /*{ "ist",   5, 30, 0 }, *//* India */
725   {
726   "jst", 9, 0, 0},              /* Japan */
727   {
728   "kst", 9, 0, 0},              /* Korea */
729   {
730   "mdt", 6, 0, 1}, {
731   "met", 1, 0, 0},              /* this is now officially CET */
732   {
733   "msd", 4, 0, 0},              /* Moscow DST */
734   {
735   "msk", 3, 0, 0},              /* Moscow */
736   {
737   "mst", 7, 0, 1}, {
738   "nzdt", 13, 0, 0},            /* New Zealand DST */
739   {
740   "nzst", 12, 0, 0},            /* New Zealand */
741   {
742   "pdt", 7, 0, 1}, {
743   "pst", 8, 0, 1}, {
744   "sat", 2, 0, 0},              /* South Africa */
745   {
746   "smt", 4, 0, 0},              /* Seychelles */
747   {
748   "sst", 11, 0, 1},             /* Samoa */
749     /*{ "sst",   8,  0, 0 }, *//* Singapore */
750   {
751   "utc", 0, 0, 0}, {
752   "wat", 0, 0, 0},              /* West Africa */
753   {
754   "west", 1, 0, 0},             /* Western Europe DST */
755   {
756   "wet", 0, 0, 0},              /* Western Europe */
757   {
758   "wgst", 2, 0, 1},             /* Western Greenland DST */
759   {
760   "wgt", 3, 0, 1},              /* Western Greenland */
761   {
762   "wst", 8, 0, 0},              /* Western Australia */
763 };
764
765 /* parses a date string in RFC822 format:
766  *
767  * Date: [ weekday , ] day-of-month month year hour:minute:second timezone
768  *
769  * This routine assumes that `h' has been initialized to 0.  the `timezone'
770  * field is optional, defaulting to +0000 if missing.
771  */
772 time_t mutt_parse_date (const char *s, HEADER * h)
773 {
774   int count = 0;
775   char *t;
776   int hour, min, sec;
777   struct tm tm;
778   int i;
779   int tz_offset = 0;
780   int zhours = 0;
781   int zminutes = 0;
782   int zoccident = 0;
783   const char *ptz;
784   char tzstr[SHORT_STRING];
785   char scratch[SHORT_STRING];
786
787   /* Don't modify our argument. Fixed-size buffer is ok here since
788    * the date format imposes a natural limit.
789    */
790
791   m_strcpy(scratch, sizeof(scratch), s);
792
793   /* kill the day of the week, if it exists. */
794   if ((t = strchr (scratch, ',')))
795     t++;
796   else
797     t = scratch;
798   t = vskipspaces(t);
799
800   p_clear(&tm, 1);
801
802   while ((t = strtok (t, " \t")) != NULL) {
803     switch (count) {
804     case 0:                    /* day of the month */
805       if (!isdigit ((unsigned char) *t))
806         return (-1);
807       tm.tm_mday = atoi (t);
808       if (tm.tm_mday > 31)
809         return (-1);
810       break;
811
812     case 1:                    /* month of the year */
813       if ((i = mutt_check_month (t)) < 0)
814         return (-1);
815       tm.tm_mon = i;
816       break;
817
818     case 2:                    /* year */
819       tm.tm_year = atoi (t);
820       if (tm.tm_year < 50)
821         tm.tm_year += 100;
822       else if (tm.tm_year >= 1900)
823         tm.tm_year -= 1900;
824       break;
825
826     case 3:                    /* time of day */
827       if (sscanf (t, "%d:%d:%d", &hour, &min, &sec) == 3);
828       else if (sscanf (t, "%d:%d", &hour, &min) == 2)
829         sec = 0;
830       else {
831         debug_print (1, ("could not process time format: %s\n", t));
832         return (-1);
833       }
834       tm.tm_hour = hour;
835       tm.tm_min = min;
836       tm.tm_sec = sec;
837       break;
838
839     case 4:                    /* timezone */
840       /* sometimes we see things like (MST) or (-0700) so attempt to
841        * compensate by uncommenting the string if non-RFC822 compliant
842        */
843       ptz = uncomment_timezone (tzstr, sizeof (tzstr), t);
844
845       if (*ptz == '+' || *ptz == '-') {
846         if (ptz[1] && ptz[2] && ptz[3] && ptz[4]
847             && isdigit ((unsigned char) ptz[1])
848             && isdigit ((unsigned char) ptz[2])
849             && isdigit ((unsigned char) ptz[3])
850             && isdigit ((unsigned char) ptz[4])) {
851           zhours = (ptz[1] - '0') * 10 + (ptz[2] - '0');
852           zminutes = (ptz[3] - '0') * 10 + (ptz[4] - '0');
853
854           if (ptz[0] == '-')
855             zoccident = 1;
856         }
857       }
858       else {
859         struct tz_t *tz;
860
861         tz = bsearch (ptz, TimeZones, sizeof TimeZones / sizeof (struct tz_t),
862                       sizeof (struct tz_t),
863                       (int (*)(const void *, const void *)) ascii_strcasecmp
864                       /* This is safe to do: A pointer to a struct equals
865                        * a pointer to its first element*/ );
866
867         if (tz) {
868           zhours = tz->zhours;
869           zminutes = tz->zminutes;
870           zoccident = tz->zoccident;
871         }
872
873         /* ad hoc support for the European MET (now officially CET) TZ */
874         if (ascii_strcasecmp (t, "MET") == 0) {
875           if ((t = strtok (NULL, " \t")) != NULL) {
876             if (!ascii_strcasecmp (t, "DST"))
877               zhours++;
878           }
879         }
880       }
881       tz_offset = zhours * 3600 + zminutes * 60;
882       if (!zoccident)
883         tz_offset = -tz_offset;
884       break;
885     }
886     count++;
887     t = 0;
888   }
889
890   if (count < 4) {              /* don't check for missing timezone */
891     debug_print (1, ("error parsing date format, using received time\n"));
892     return (-1);
893   }
894
895   if (h) {
896     h->zhours = zhours;
897     h->zminutes = zminutes;
898     h->zoccident = zoccident;
899   }
900
901   return (mutt_mktime (&tm, 0) + tz_offset);
902 }
903
904 /* extract the first substring that looks like a message-id */
905 static char *extract_message_id(const char *s)
906 {
907     const char *p;
908
909     if ((s = strchr(s, '<')) == NULL || (p = strchr(s, '>')) == NULL)
910         return NULL;
911     return p_dupstr(s, (p - s) + 1);
912 }
913
914 void mutt_parse_mime_message (CONTEXT * ctx, HEADER * cur)
915 {
916   MESSAGE *msg;
917   int flags = 0;
918
919   do {
920     if (cur->content->type != TYPEMESSAGE
921         && cur->content->type != TYPEMULTIPART)
922       break;                     /* nothing to do */
923
924     if (cur->content->parts)
925       break;                     /* The message was parsed earlier. */
926
927     if ((msg = mx_open_message (ctx, cur->msgno))) {
928       mutt_parse_part (msg->fp, cur->content);
929
930       cur->security = crypt_query (cur->content);
931
932       mx_close_message (&msg);
933     }
934   } while (0);
935   mutt_count_body_parts (cur, flags | M_PARTS_RECOUNT);
936 }
937
938 int mutt_parse_rfc822_line (ENVELOPE * e, HEADER * hdr, char *line, char *p,
939                             short user_hdrs, short weed, short do_2047,
940                             LIST ** lastp)
941 {
942   int matched = 0;
943   LIST *last = NULL;
944
945   if (lastp)
946     last = *lastp;
947
948   switch (ascii_tolower (line[0])) {
949   case 'a':
950     if (ascii_strcasecmp (line + 1, "pparently-to") == 0) {
951       e->to = rfc822_parse_adrlist (e->to, p);
952       matched = 1;
953     }
954     else if (ascii_strcasecmp (line + 1, "pparently-from") == 0) {
955       e->from = rfc822_parse_adrlist (e->from, p);
956       matched = 1;
957     }
958     break;
959
960   case 'b':
961     if (ascii_strcasecmp (line + 1, "cc") == 0) {
962       e->bcc = rfc822_parse_adrlist (e->bcc, p);
963       matched = 1;
964     }
965     break;
966
967   case 'c':
968     if (ascii_strcasecmp (line + 1, "c") == 0) {
969       e->cc = rfc822_parse_adrlist (e->cc, p);
970       matched = 1;
971     }
972     else if (ascii_strncasecmp (line + 1, "ontent-", 7) == 0) {
973       if (ascii_strcasecmp (line + 8, "type") == 0) {
974         if (hdr)
975           mutt_parse_content_type (p, hdr->content);
976         matched = 1;
977       }
978       else if (ascii_strcasecmp (line + 8, "transfer-encoding") == 0) {
979         if (hdr)
980           hdr->content->encoding = mutt_check_encoding (p);
981         matched = 1;
982       }
983       else if (ascii_strcasecmp (line + 8, "length") == 0) {
984         if (hdr) {
985           if ((hdr->content->length = atoi (p)) < 0)
986             hdr->content->length = -1;
987         }
988         matched = 1;
989       }
990       else if (ascii_strcasecmp (line + 8, "description") == 0) {
991         if (hdr) {
992           m_strreplace(&hdr->content->description, p);
993           rfc2047_decode (&hdr->content->description);
994         }
995         matched = 1;
996       }
997       else if (ascii_strcasecmp (line + 8, "disposition") == 0) {
998         if (hdr)
999           parse_content_disposition (p, hdr->content);
1000         matched = 1;
1001       }
1002     }
1003     break;
1004
1005   case 'd':
1006     if (!ascii_strcasecmp ("ate", line + 1)) {
1007       m_strreplace(&e->date, p);
1008       if (hdr)
1009         hdr->date_sent = mutt_parse_date (p, hdr);
1010       matched = 1;
1011     }
1012     break;
1013
1014   case 'e':
1015     if (!ascii_strcasecmp ("xpires", line + 1) &&
1016         hdr && mutt_parse_date (p, NULL) < time (NULL))
1017       hdr->expired = 1;
1018     break;
1019
1020   case 'f':
1021     if (!ascii_strcasecmp ("rom", line + 1)) {
1022       e->from = rfc822_parse_adrlist (e->from, p);
1023       /* don't leave from info NULL if there's an invalid address (or
1024        * whatever) in From: field; mutt would just display it as empty
1025        * and mark mail/(esp.) news article as your own. aaargh! this
1026        * bothered me for _years_ */
1027       if (!e->from) {
1028         e->from = address_new ();
1029         e->from->personal = m_strdup(p);
1030       }
1031       matched = 1;
1032     }
1033 #ifdef USE_NNTP
1034     else if (!m_strcasecmp(line + 1, "ollowup-to")) {
1035       if (!e->followup_to) {
1036         m_strrtrim(p);
1037         e->followup_to = m_strdup(skipspaces(p));
1038       }
1039       matched = 1;
1040     }
1041 #endif
1042     break;
1043
1044   case 'i':
1045     if (!ascii_strcasecmp (line + 1, "n-reply-to")) {
1046       mutt_free_list (&e->in_reply_to);
1047       e->in_reply_to = mutt_parse_references (p, 1);
1048       matched = 1;
1049     }
1050     break;
1051
1052   case 'l':
1053     if (!ascii_strcasecmp (line + 1, "ines")) {
1054       if (hdr) {
1055         hdr->lines = atoi (p);
1056
1057         /*
1058          * HACK - mutt has, for a very short time, produced negative
1059          * Lines header values.  Ignore them.
1060          */
1061         if (hdr->lines < 0)
1062           hdr->lines = 0;
1063       }
1064
1065       matched = 1;
1066     }
1067     else if (!ascii_strcasecmp (line + 1, "ist-Post")) {
1068       /* RFC 2369.  FIXME: We should ignore whitespace, but don't. */
1069       if (strncmp (p, "NO", 2)) {
1070         char *beg, *end;
1071
1072         for (beg = strchr (p, '<'); beg; beg = strchr (end, ',')) {
1073           ++beg;
1074           if (!(end = strchr (beg, '>')))
1075             break;
1076
1077           /* Take the first mailto URL */
1078           if (url_check_scheme (beg) == U_MAILTO) {
1079             p_delete(&e->list_post);
1080             e->list_post = p_dupstr(beg, end - beg);
1081             break;
1082           }
1083         }
1084       }
1085       matched = 1;
1086     }
1087     break;
1088
1089   case 'm':
1090     if (!ascii_strcasecmp (line + 1, "ime-version")) {
1091       if (hdr)
1092         hdr->mime = 1;
1093       matched = 1;
1094     }
1095     else if (!ascii_strcasecmp (line + 1, "essage-id")) {
1096       /* We add a new "Message-ID:" when building a message */
1097       p_delete(&e->message_id);
1098       e->message_id = extract_message_id (p);
1099       matched = 1;
1100     }
1101     else if (!ascii_strncasecmp (line + 1, "ail-", 4)) {
1102       if (!ascii_strcasecmp (line + 5, "reply-to")) {
1103         /* override the Reply-To: field */
1104         address_delete (&e->reply_to);
1105         e->reply_to = rfc822_parse_adrlist (e->reply_to, p);
1106         matched = 1;
1107       }
1108       else if (!ascii_strcasecmp (line + 5, "followup-to")) {
1109         e->mail_followup_to = rfc822_parse_adrlist (e->mail_followup_to, p);
1110         matched = 1;
1111       }
1112     }
1113     break;
1114
1115 #ifdef USE_NNTP
1116   case 'n':
1117     if (!m_strcasecmp(line + 1, "ewsgroups")) {
1118       p_delete(&e->newsgroups);
1119       m_strrtrim(p);
1120       e->newsgroups = m_strdup(skipspaces(p));
1121       matched = 1;
1122     }
1123     break;
1124 #endif
1125
1126   case 'o':
1127     /* field `Organization:' saves only for pager! */
1128     if (!m_strcasecmp(line + 1, "rganization")) {
1129       if (!e->organization && m_strcasecmp(p, "unknown"))
1130         e->organization = m_strdup(p);
1131     }
1132     break;
1133
1134   case 'r':
1135     if (!ascii_strcasecmp (line + 1, "eferences")) {
1136       mutt_free_list (&e->references);
1137       e->references = mutt_parse_references (p, 0);
1138       matched = 1;
1139     }
1140     else if (!ascii_strcasecmp (line + 1, "eply-to")) {
1141       e->reply_to = rfc822_parse_adrlist (e->reply_to, p);
1142       matched = 1;
1143     }
1144     else if (!ascii_strcasecmp (line + 1, "eturn-path")) {
1145       e->return_path = rfc822_parse_adrlist (e->return_path, p);
1146       matched = 1;
1147     }
1148     else if (!ascii_strcasecmp (line + 1, "eceived")) {
1149       if (hdr && !hdr->received) {
1150         char *d = strchr (p, ';');
1151
1152         if (d)
1153           hdr->received = mutt_parse_date (d + 1, NULL);
1154       }
1155     }
1156     break;
1157
1158   case 's':
1159     if (!ascii_strcasecmp (line + 1, "ubject")) {
1160       if (!e->subject)
1161         e->subject = m_strdup(p);
1162       matched = 1;
1163     }
1164     else if (!ascii_strcasecmp (line + 1, "ender")) {
1165       e->sender = rfc822_parse_adrlist (e->sender, p);
1166       matched = 1;
1167     }
1168     else if (!ascii_strcasecmp (line + 1, "tatus")) {
1169       if (hdr) {
1170         while (*p) {
1171           switch (*p) {
1172           case 'r':
1173             hdr->replied = 1;
1174             break;
1175           case 'O':
1176             hdr->old = 1;
1177             break;
1178           case 'R':
1179             hdr->read = 1;
1180             break;
1181           }
1182           p++;
1183         }
1184       }
1185       matched = 1;
1186     }
1187     else if ((!ascii_strcasecmp ("upersedes", line + 1) ||
1188               !ascii_strcasecmp ("upercedes", line + 1)) && hdr)
1189       e->supersedes = m_strdup(p);
1190     break;
1191
1192   case 't':
1193     if (ascii_strcasecmp (line + 1, "o") == 0) {
1194       e->to = rfc822_parse_adrlist (e->to, p);
1195       matched = 1;
1196     }
1197     break;
1198
1199   case 'x':
1200     if (ascii_strcasecmp (line + 1, "-status") == 0) {
1201       if (hdr) {
1202         while (*p) {
1203           switch (*p) {
1204           case 'A':
1205             hdr->replied = 1;
1206             break;
1207           case 'D':
1208             hdr->deleted = 1;
1209             break;
1210           case 'F':
1211             hdr->flagged = 1;
1212             break;
1213           default:
1214             break;
1215           }
1216           p++;
1217         }
1218       }
1219       matched = 1;
1220     }
1221     else if (ascii_strcasecmp (line + 1, "-label") == 0) {
1222       e->x_label = m_strdup(p);
1223       matched = 1;
1224     }
1225 #ifdef USE_NNTP
1226     else if (!m_strcasecmp(line + 1, "-comment-to")) {
1227       if (!e->x_comment_to)
1228         e->x_comment_to = m_strdup(p);
1229       matched = 1;
1230     }
1231     else if (!m_strcasecmp(line + 1, "ref")) {
1232       if (!e->xref)
1233         e->xref = m_strdup(p);
1234       matched = 1;
1235     }
1236 #endif
1237
1238   default:
1239     break;
1240   }
1241
1242   /* Keep track of the user-defined headers */
1243   if (!matched && user_hdrs) {
1244     /* restore the original line */
1245     line[m_strlen(line)] = ':';
1246
1247     if (weed && option (OPTWEED) && mutt_matches_ignore (line, Ignore)
1248         && !mutt_matches_ignore (line, UnIgnore))
1249       goto done;
1250
1251     if (last) {
1252       last->next = mutt_new_list ();
1253       last = last->next;
1254     }
1255     else
1256       last = e->userhdrs = mutt_new_list ();
1257     last->data = m_strdup(line);
1258     if (do_2047)
1259       rfc2047_decode (&last->data);
1260   }
1261
1262 done:
1263
1264   *lastp = last;
1265   return matched;
1266 }
1267
1268
1269 /* mutt_read_rfc822_header() -- parses a RFC822 header
1270  *
1271  * Args:
1272  *
1273  * f            stream to read from
1274  *
1275  * hdr          header structure of current message (optional).
1276  *
1277  * user_hdrs    If set, store user headers.  Used for recall-message and
1278  *              postpone modes.
1279  *
1280  * weed         If this parameter is set and the user has activated the
1281  *              $weed option, honor the header weed list for user headers.
1282  *              Used for recall-message.
1283  *
1284  * Returns:     newly allocated envelope structure.  You should free it by
1285  *              mutt_free_envelope() when envelope stay unneeded.
1286  */
1287 ENVELOPE *mutt_read_rfc822_header (FILE * f, HEADER * hdr, short user_hdrs,
1288                                    short weed)
1289 {
1290   ENVELOPE *e = mutt_new_envelope ();
1291   LIST *last = NULL;
1292   char *line = p_new(char, LONG_STRING);
1293   char *p;
1294   off_t loc;
1295   int matched;
1296   size_t linelen = LONG_STRING;
1297   char buf[LONG_STRING + 1];
1298
1299   if (hdr) {
1300     if (hdr->content == NULL) {
1301       hdr->content = mutt_new_body ();
1302
1303       /* set the defaults from RFC1521 */
1304       hdr->content->type = TYPETEXT;
1305       hdr->content->subtype = m_strdup("plain");
1306       hdr->content->encoding = ENC7BIT;
1307       hdr->content->length = -1;
1308
1309       /* RFC 2183 says this is arbitrary */
1310       hdr->content->disposition = DISPINLINE;
1311     }
1312   }
1313
1314   while ((loc = ftello (f)),
1315          *(line = mutt_read_rfc822_line (f, line, &linelen)) != 0) {
1316     matched = 0;
1317
1318     if ((p = strpbrk (line, ": \t")) == NULL || *p != ':') {
1319       char return_path[LONG_STRING];
1320       time_t t;
1321
1322       /* some bogus MTAs will quote the original "From " line */
1323       if (m_strncmp(">From ", line, 6) == 0)
1324         continue;               /* just ignore */
1325       else if (is_from (line, return_path, sizeof (return_path), &t)) {
1326         /* MH somtimes has the From_ line in the middle of the header! */
1327         if (hdr && !hdr->received)
1328           hdr->received = t - mutt_local_tz (t);
1329         continue;
1330       }
1331
1332       fseeko (f, loc, 0);
1333       break;                    /* end of header */
1334     }
1335
1336     *buf = '\0';
1337
1338     if (mutt_match_spam_list (line, SpamList, buf, sizeof (buf))) {
1339       if (!rx_list_match (NoSpamList, line)) {
1340
1341         /* if spam tag already exists, figure out how to amend it */
1342         if (e->spam && *buf) {
1343           /* If SpamSep defined, append with separator */
1344           if (SpamSep) {
1345             mutt_buffer_addstr (e->spam, SpamSep);
1346             mutt_buffer_addstr (e->spam, buf);
1347           }
1348
1349           /* else overwrite */
1350           else {
1351             e->spam->dptr = e->spam->data;
1352             *e->spam->dptr = '\0';
1353             mutt_buffer_addstr (e->spam, buf);
1354           }
1355         }
1356
1357         /* spam tag is new, and match expr is non-empty; copy */
1358         else if (!e->spam && *buf) {
1359           e->spam = mutt_buffer_from (NULL, buf);
1360         }
1361
1362         /* match expr is empty; plug in null string if no existing tag */
1363         else if (!e->spam) {
1364           e->spam = mutt_buffer_from (NULL, "");
1365         }
1366
1367         if (e->spam && e->spam->data)
1368           debug_print (5, ("spam = %s\n", e->spam->data));
1369       }
1370     }
1371
1372     *p++ = 0;
1373     p = vskipspaces(p);
1374     if (!*p)
1375       continue;                 /* skip empty header fields */
1376
1377     matched =
1378       mutt_parse_rfc822_line (e, hdr, line, p, user_hdrs, weed, 1, &last);
1379
1380   }
1381
1382   p_delete(&line);
1383
1384   if (hdr) {
1385     hdr->content->hdr_offset = hdr->offset;
1386     hdr->content->offset = ftello (f);
1387     rfc2047_decode_envelope(e);
1388     /* check for missing or invalid date */
1389     if (hdr->date_sent <= 0) {
1390       debug_print (1, ("no date found, using received "
1391                        "time from msg separator\n"));
1392       hdr->date_sent = hdr->received;
1393     }
1394   }
1395
1396   return (e);
1397 }
1398
1399 address_t *mutt_parse_adrlist (address_t * p, const char *s)
1400 {
1401   const char *q;
1402
1403   /* check for a simple whitespace separated list of addresses */
1404   if ((q = strpbrk (s, "\"<>():;,\\")) == NULL) {
1405     char tmp[HUGE_STRING];
1406     char *r;
1407
1408     m_strcpy(tmp, sizeof(tmp), s);
1409     r = tmp;
1410     while ((r = strtok (r, " \t")) != NULL) {
1411       p = rfc822_parse_adrlist (p, r);
1412       r = NULL;
1413     }
1414   }
1415   else
1416     p = rfc822_parse_adrlist (p, s);
1417
1418   return p;
1419 }
1420
1421
1422 /* Compares mime types to the ok and except lists */
1423 int count_body_parts_check(LIST **checklist, BODY *b, int dflt) {
1424   LIST *type;
1425   ATTACH_MATCH *a;
1426
1427   /* If list is null, use default behavior. */
1428   if (! *checklist) {
1429     /*return dflt;*/
1430     return 0;
1431   }
1432
1433   for (type = *checklist; type; type = type->next) {
1434     a = (ATTACH_MATCH *)type->data;
1435     debug_print(5, ("cbpc: %s %d/%s ?? %s/%s [%d]... ",
1436                dflt ? "[OK] " : "[EXCL] ",
1437                b->type, b->subtype, a->major, a->minor, a->major_int));
1438     if ((a->major_int == TYPEANY || a->major_int == b->type) &&
1439         !regexec(&a->minor_rx, b->subtype, 0, NULL, 0)) {
1440       debug_print(5, ("yes\n"));
1441       return 1;
1442     } else {
1443       debug_print(5, ("no\n"));
1444     }
1445   }
1446   return 0;
1447 }
1448
1449 #define AT_COUNT(why) { shallcount = 1; }
1450 #define AT_NOCOUNT(why) { shallcount = 0; }
1451
1452 int count_body_parts (BODY *body, int flags) {
1453   int count = 0;
1454   int shallcount, shallrecurse;
1455   BODY *bp;
1456
1457   if (body == NULL)
1458     return 0;
1459
1460   for (bp = body; bp != NULL; bp = bp->next) {
1461     /* Initial disposition is to count and not to recurse this part. */
1462     AT_COUNT("default");
1463     shallrecurse = 0;
1464
1465     debug_print(5, ("bp: desc=\"%s\"; fn=\"%s\", type=\"%d/%s\"\n",
1466                bp->description ? bp->description : ("none"),
1467                bp->filename ? bp->filename :
1468                bp->d_filename ? bp->d_filename : "(none)",
1469                bp->type, bp->subtype ? bp->subtype : "*"));
1470
1471     if (bp->type == TYPEMESSAGE) {
1472       shallrecurse = 1;
1473
1474       /* If it's an external body pointer, don't recurse it. */
1475       if (!ascii_strcasecmp (bp->subtype, "external-body"))
1476         shallrecurse = 0;
1477
1478       /* Don't count containers if they're top-level. */
1479       if (flags & M_PARTS_TOPLEVEL)
1480         AT_NOCOUNT("top-level message/*");
1481     } else if (bp->type == TYPEMULTIPART) {
1482       /* Always recurse multiparts, except multipart/alternative. */
1483       shallrecurse = 1;
1484       if (!m_strcasecmp(bp->subtype, "alternative"))
1485         shallrecurse = 0;
1486
1487       /* Don't count containers if they're top-level. */
1488       if (flags & M_PARTS_TOPLEVEL)
1489         AT_NOCOUNT("top-level multipart");
1490     }
1491
1492     if (bp->disposition == DISPINLINE &&
1493         bp->type != TYPEMULTIPART && bp->type != TYPEMESSAGE && bp == body)
1494       AT_NOCOUNT("ignore fundamental inlines");
1495
1496     /* If this body isn't scheduled for enumeration already, don't bother
1497      * profiling it further. */
1498
1499     if (shallcount) {
1500       /* Turn off shallcount if message type is not in ok list,
1501        * or if it is in except list. Check is done separately for
1502        * inlines vs. attachments.
1503        */
1504
1505       if (bp->disposition == DISPATTACH) {
1506         if (!count_body_parts_check(&AttachAllow, bp, 1))
1507           AT_NOCOUNT("attach not allowed");
1508         if (count_body_parts_check(&AttachExclude, bp, 0))
1509           AT_NOCOUNT("attach excluded");
1510       } else {
1511         if (!count_body_parts_check(&InlineAllow, bp, 1))
1512           AT_NOCOUNT("inline not allowed");
1513         if (count_body_parts_check(&InlineExclude, bp, 0))
1514           AT_NOCOUNT("excluded");
1515       }
1516     }
1517
1518     if (shallcount)
1519       count++;
1520     bp->attach_qualifies = shallcount ? 1 : 0;
1521
1522     debug_print(5, ("cbp: %p shallcount = %d\n", bp, shallcount));
1523
1524     if (shallrecurse) {
1525       debug_print(5, ("cbp: %p pre count = %d\n", bp, count));
1526       bp->attach_count = count_body_parts(bp->parts, flags & ~M_PARTS_TOPLEVEL);
1527       count += bp->attach_count;
1528       debug_print(5, ("cbp: %p post count = %d\n", bp, count));
1529     }
1530   }
1531
1532   debug_print(5, ("bp: return %d\n", count < 0 ? 0 : count));
1533   return count < 0 ? 0 : count;
1534 }
1535
1536 int mutt_count_body_parts (HEADER *hdr, int flags) {
1537   if (!option (OPTCOUNTATTACH))
1538     return (0);
1539   if (hdr->attach_valid && !(flags & M_PARTS_RECOUNT))
1540     return hdr->attach_total;
1541
1542   if (AttachAllow || AttachExclude || InlineAllow || InlineExclude)
1543     hdr->attach_total = count_body_parts(hdr->content, flags | M_PARTS_TOPLEVEL);
1544   else
1545     hdr->attach_total = 0;
1546
1547   hdr->attach_valid = 1;
1548   return hdr->attach_total;
1549 }