always build pgp support.
[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       if (WithCrypto)
931         cur->security = crypt_query (cur->content);
932
933       mx_close_message (&msg);
934     }
935   } while (0);
936   mutt_count_body_parts (cur, flags | M_PARTS_RECOUNT);
937 }
938
939 int mutt_parse_rfc822_line (ENVELOPE * e, HEADER * hdr, char *line, char *p,
940                             short user_hdrs, short weed, short do_2047,
941                             LIST ** lastp)
942 {
943   int matched = 0;
944   LIST *last = NULL;
945
946   if (lastp)
947     last = *lastp;
948
949   switch (ascii_tolower (line[0])) {
950   case 'a':
951     if (ascii_strcasecmp (line + 1, "pparently-to") == 0) {
952       e->to = rfc822_parse_adrlist (e->to, p);
953       matched = 1;
954     }
955     else if (ascii_strcasecmp (line + 1, "pparently-from") == 0) {
956       e->from = rfc822_parse_adrlist (e->from, p);
957       matched = 1;
958     }
959     break;
960
961   case 'b':
962     if (ascii_strcasecmp (line + 1, "cc") == 0) {
963       e->bcc = rfc822_parse_adrlist (e->bcc, p);
964       matched = 1;
965     }
966     break;
967
968   case 'c':
969     if (ascii_strcasecmp (line + 1, "c") == 0) {
970       e->cc = rfc822_parse_adrlist (e->cc, p);
971       matched = 1;
972     }
973     else if (ascii_strncasecmp (line + 1, "ontent-", 7) == 0) {
974       if (ascii_strcasecmp (line + 8, "type") == 0) {
975         if (hdr)
976           mutt_parse_content_type (p, hdr->content);
977         matched = 1;
978       }
979       else if (ascii_strcasecmp (line + 8, "transfer-encoding") == 0) {
980         if (hdr)
981           hdr->content->encoding = mutt_check_encoding (p);
982         matched = 1;
983       }
984       else if (ascii_strcasecmp (line + 8, "length") == 0) {
985         if (hdr) {
986           if ((hdr->content->length = atoi (p)) < 0)
987             hdr->content->length = -1;
988         }
989         matched = 1;
990       }
991       else if (ascii_strcasecmp (line + 8, "description") == 0) {
992         if (hdr) {
993           m_strreplace(&hdr->content->description, p);
994           rfc2047_decode (&hdr->content->description);
995         }
996         matched = 1;
997       }
998       else if (ascii_strcasecmp (line + 8, "disposition") == 0) {
999         if (hdr)
1000           parse_content_disposition (p, hdr->content);
1001         matched = 1;
1002       }
1003     }
1004     break;
1005
1006   case 'd':
1007     if (!ascii_strcasecmp ("ate", line + 1)) {
1008       m_strreplace(&e->date, p);
1009       if (hdr)
1010         hdr->date_sent = mutt_parse_date (p, hdr);
1011       matched = 1;
1012     }
1013     break;
1014
1015   case 'e':
1016     if (!ascii_strcasecmp ("xpires", line + 1) &&
1017         hdr && mutt_parse_date (p, NULL) < time (NULL))
1018       hdr->expired = 1;
1019     break;
1020
1021   case 'f':
1022     if (!ascii_strcasecmp ("rom", line + 1)) {
1023       e->from = rfc822_parse_adrlist (e->from, p);
1024       /* don't leave from info NULL if there's an invalid address (or
1025        * whatever) in From: field; mutt would just display it as empty
1026        * and mark mail/(esp.) news article as your own. aaargh! this
1027        * bothered me for _years_ */
1028       if (!e->from) {
1029         e->from = address_new ();
1030         e->from->personal = m_strdup(p);
1031       }
1032       matched = 1;
1033     }
1034 #ifdef USE_NNTP
1035     else if (!m_strcasecmp(line + 1, "ollowup-to")) {
1036       if (!e->followup_to) {
1037         m_strrtrim(p);
1038         e->followup_to = m_strdup(skipspaces(p));
1039       }
1040       matched = 1;
1041     }
1042 #endif
1043     break;
1044
1045   case 'i':
1046     if (!ascii_strcasecmp (line + 1, "n-reply-to")) {
1047       mutt_free_list (&e->in_reply_to);
1048       e->in_reply_to = mutt_parse_references (p, 1);
1049       matched = 1;
1050     }
1051     break;
1052
1053   case 'l':
1054     if (!ascii_strcasecmp (line + 1, "ines")) {
1055       if (hdr) {
1056         hdr->lines = atoi (p);
1057
1058         /*
1059          * HACK - mutt has, for a very short time, produced negative
1060          * Lines header values.  Ignore them.
1061          */
1062         if (hdr->lines < 0)
1063           hdr->lines = 0;
1064       }
1065
1066       matched = 1;
1067     }
1068     else if (!ascii_strcasecmp (line + 1, "ist-Post")) {
1069       /* RFC 2369.  FIXME: We should ignore whitespace, but don't. */
1070       if (strncmp (p, "NO", 2)) {
1071         char *beg, *end;
1072
1073         for (beg = strchr (p, '<'); beg; beg = strchr (end, ',')) {
1074           ++beg;
1075           if (!(end = strchr (beg, '>')))
1076             break;
1077
1078           /* Take the first mailto URL */
1079           if (url_check_scheme (beg) == U_MAILTO) {
1080             p_delete(&e->list_post);
1081             e->list_post = p_dupstr(beg, end - beg);
1082             break;
1083           }
1084         }
1085       }
1086       matched = 1;
1087     }
1088     break;
1089
1090   case 'm':
1091     if (!ascii_strcasecmp (line + 1, "ime-version")) {
1092       if (hdr)
1093         hdr->mime = 1;
1094       matched = 1;
1095     }
1096     else if (!ascii_strcasecmp (line + 1, "essage-id")) {
1097       /* We add a new "Message-ID:" when building a message */
1098       p_delete(&e->message_id);
1099       e->message_id = extract_message_id (p);
1100       matched = 1;
1101     }
1102     else if (!ascii_strncasecmp (line + 1, "ail-", 4)) {
1103       if (!ascii_strcasecmp (line + 5, "reply-to")) {
1104         /* override the Reply-To: field */
1105         address_delete (&e->reply_to);
1106         e->reply_to = rfc822_parse_adrlist (e->reply_to, p);
1107         matched = 1;
1108       }
1109       else if (!ascii_strcasecmp (line + 5, "followup-to")) {
1110         e->mail_followup_to = rfc822_parse_adrlist (e->mail_followup_to, p);
1111         matched = 1;
1112       }
1113     }
1114     break;
1115
1116 #ifdef USE_NNTP
1117   case 'n':
1118     if (!m_strcasecmp(line + 1, "ewsgroups")) {
1119       p_delete(&e->newsgroups);
1120       m_strrtrim(p);
1121       e->newsgroups = m_strdup(skipspaces(p));
1122       matched = 1;
1123     }
1124     break;
1125 #endif
1126
1127   case 'o':
1128     /* field `Organization:' saves only for pager! */
1129     if (!m_strcasecmp(line + 1, "rganization")) {
1130       if (!e->organization && m_strcasecmp(p, "unknown"))
1131         e->organization = m_strdup(p);
1132     }
1133     break;
1134
1135   case 'r':
1136     if (!ascii_strcasecmp (line + 1, "eferences")) {
1137       mutt_free_list (&e->references);
1138       e->references = mutt_parse_references (p, 0);
1139       matched = 1;
1140     }
1141     else if (!ascii_strcasecmp (line + 1, "eply-to")) {
1142       e->reply_to = rfc822_parse_adrlist (e->reply_to, p);
1143       matched = 1;
1144     }
1145     else if (!ascii_strcasecmp (line + 1, "eturn-path")) {
1146       e->return_path = rfc822_parse_adrlist (e->return_path, p);
1147       matched = 1;
1148     }
1149     else if (!ascii_strcasecmp (line + 1, "eceived")) {
1150       if (hdr && !hdr->received) {
1151         char *d = strchr (p, ';');
1152
1153         if (d)
1154           hdr->received = mutt_parse_date (d + 1, NULL);
1155       }
1156     }
1157     break;
1158
1159   case 's':
1160     if (!ascii_strcasecmp (line + 1, "ubject")) {
1161       if (!e->subject)
1162         e->subject = m_strdup(p);
1163       matched = 1;
1164     }
1165     else if (!ascii_strcasecmp (line + 1, "ender")) {
1166       e->sender = rfc822_parse_adrlist (e->sender, p);
1167       matched = 1;
1168     }
1169     else if (!ascii_strcasecmp (line + 1, "tatus")) {
1170       if (hdr) {
1171         while (*p) {
1172           switch (*p) {
1173           case 'r':
1174             hdr->replied = 1;
1175             break;
1176           case 'O':
1177             hdr->old = 1;
1178             break;
1179           case 'R':
1180             hdr->read = 1;
1181             break;
1182           }
1183           p++;
1184         }
1185       }
1186       matched = 1;
1187     }
1188     else if ((!ascii_strcasecmp ("upersedes", line + 1) ||
1189               !ascii_strcasecmp ("upercedes", line + 1)) && hdr)
1190       e->supersedes = m_strdup(p);
1191     break;
1192
1193   case 't':
1194     if (ascii_strcasecmp (line + 1, "o") == 0) {
1195       e->to = rfc822_parse_adrlist (e->to, p);
1196       matched = 1;
1197     }
1198     break;
1199
1200   case 'x':
1201     if (ascii_strcasecmp (line + 1, "-status") == 0) {
1202       if (hdr) {
1203         while (*p) {
1204           switch (*p) {
1205           case 'A':
1206             hdr->replied = 1;
1207             break;
1208           case 'D':
1209             hdr->deleted = 1;
1210             break;
1211           case 'F':
1212             hdr->flagged = 1;
1213             break;
1214           default:
1215             break;
1216           }
1217           p++;
1218         }
1219       }
1220       matched = 1;
1221     }
1222     else if (ascii_strcasecmp (line + 1, "-label") == 0) {
1223       e->x_label = m_strdup(p);
1224       matched = 1;
1225     }
1226 #ifdef USE_NNTP
1227     else if (!m_strcasecmp(line + 1, "-comment-to")) {
1228       if (!e->x_comment_to)
1229         e->x_comment_to = m_strdup(p);
1230       matched = 1;
1231     }
1232     else if (!m_strcasecmp(line + 1, "ref")) {
1233       if (!e->xref)
1234         e->xref = m_strdup(p);
1235       matched = 1;
1236     }
1237 #endif
1238
1239   default:
1240     break;
1241   }
1242
1243   /* Keep track of the user-defined headers */
1244   if (!matched && user_hdrs) {
1245     /* restore the original line */
1246     line[m_strlen(line)] = ':';
1247
1248     if (weed && option (OPTWEED) && mutt_matches_ignore (line, Ignore)
1249         && !mutt_matches_ignore (line, UnIgnore))
1250       goto done;
1251
1252     if (last) {
1253       last->next = mutt_new_list ();
1254       last = last->next;
1255     }
1256     else
1257       last = e->userhdrs = mutt_new_list ();
1258     last->data = m_strdup(line);
1259     if (do_2047)
1260       rfc2047_decode (&last->data);
1261   }
1262
1263 done:
1264
1265   *lastp = last;
1266   return matched;
1267 }
1268
1269
1270 /* mutt_read_rfc822_header() -- parses a RFC822 header
1271  *
1272  * Args:
1273  *
1274  * f            stream to read from
1275  *
1276  * hdr          header structure of current message (optional).
1277  *
1278  * user_hdrs    If set, store user headers.  Used for recall-message and
1279  *              postpone modes.
1280  *
1281  * weed         If this parameter is set and the user has activated the
1282  *              $weed option, honor the header weed list for user headers.
1283  *              Used for recall-message.
1284  *
1285  * Returns:     newly allocated envelope structure.  You should free it by
1286  *              mutt_free_envelope() when envelope stay unneeded.
1287  */
1288 ENVELOPE *mutt_read_rfc822_header (FILE * f, HEADER * hdr, short user_hdrs,
1289                                    short weed)
1290 {
1291   ENVELOPE *e = mutt_new_envelope ();
1292   LIST *last = NULL;
1293   char *line = p_new(char, LONG_STRING);
1294   char *p;
1295   off_t loc;
1296   int matched;
1297   size_t linelen = LONG_STRING;
1298   char buf[LONG_STRING + 1];
1299
1300   if (hdr) {
1301     if (hdr->content == NULL) {
1302       hdr->content = mutt_new_body ();
1303
1304       /* set the defaults from RFC1521 */
1305       hdr->content->type = TYPETEXT;
1306       hdr->content->subtype = m_strdup("plain");
1307       hdr->content->encoding = ENC7BIT;
1308       hdr->content->length = -1;
1309
1310       /* RFC 2183 says this is arbitrary */
1311       hdr->content->disposition = DISPINLINE;
1312     }
1313   }
1314
1315   while ((loc = ftello (f)),
1316          *(line = mutt_read_rfc822_line (f, line, &linelen)) != 0) {
1317     matched = 0;
1318
1319     if ((p = strpbrk (line, ": \t")) == NULL || *p != ':') {
1320       char return_path[LONG_STRING];
1321       time_t t;
1322
1323       /* some bogus MTAs will quote the original "From " line */
1324       if (m_strncmp(">From ", line, 6) == 0)
1325         continue;               /* just ignore */
1326       else if (is_from (line, return_path, sizeof (return_path), &t)) {
1327         /* MH somtimes has the From_ line in the middle of the header! */
1328         if (hdr && !hdr->received)
1329           hdr->received = t - mutt_local_tz (t);
1330         continue;
1331       }
1332
1333       fseeko (f, loc, 0);
1334       break;                    /* end of header */
1335     }
1336
1337     *buf = '\0';
1338
1339     if (mutt_match_spam_list (line, SpamList, buf, sizeof (buf))) {
1340       if (!rx_list_match (NoSpamList, line)) {
1341
1342         /* if spam tag already exists, figure out how to amend it */
1343         if (e->spam && *buf) {
1344           /* If SpamSep defined, append with separator */
1345           if (SpamSep) {
1346             mutt_buffer_addstr (e->spam, SpamSep);
1347             mutt_buffer_addstr (e->spam, buf);
1348           }
1349
1350           /* else overwrite */
1351           else {
1352             e->spam->dptr = e->spam->data;
1353             *e->spam->dptr = '\0';
1354             mutt_buffer_addstr (e->spam, buf);
1355           }
1356         }
1357
1358         /* spam tag is new, and match expr is non-empty; copy */
1359         else if (!e->spam && *buf) {
1360           e->spam = mutt_buffer_from (NULL, buf);
1361         }
1362
1363         /* match expr is empty; plug in null string if no existing tag */
1364         else if (!e->spam) {
1365           e->spam = mutt_buffer_from (NULL, "");
1366         }
1367
1368         if (e->spam && e->spam->data)
1369           debug_print (5, ("spam = %s\n", e->spam->data));
1370       }
1371     }
1372
1373     *p++ = 0;
1374     p = vskipspaces(p);
1375     if (!*p)
1376       continue;                 /* skip empty header fields */
1377
1378     matched =
1379       mutt_parse_rfc822_line (e, hdr, line, p, user_hdrs, weed, 1, &last);
1380
1381   }
1382
1383   p_delete(&line);
1384
1385   if (hdr) {
1386     hdr->content->hdr_offset = hdr->offset;
1387     hdr->content->offset = ftello (f);
1388     rfc2047_decode_envelope(e);
1389     /* check for missing or invalid date */
1390     if (hdr->date_sent <= 0) {
1391       debug_print (1, ("no date found, using received "
1392                        "time from msg separator\n"));
1393       hdr->date_sent = hdr->received;
1394     }
1395   }
1396
1397   return (e);
1398 }
1399
1400 address_t *mutt_parse_adrlist (address_t * p, const char *s)
1401 {
1402   const char *q;
1403
1404   /* check for a simple whitespace separated list of addresses */
1405   if ((q = strpbrk (s, "\"<>():;,\\")) == NULL) {
1406     char tmp[HUGE_STRING];
1407     char *r;
1408
1409     m_strcpy(tmp, sizeof(tmp), s);
1410     r = tmp;
1411     while ((r = strtok (r, " \t")) != NULL) {
1412       p = rfc822_parse_adrlist (p, r);
1413       r = NULL;
1414     }
1415   }
1416   else
1417     p = rfc822_parse_adrlist (p, s);
1418
1419   return p;
1420 }
1421
1422
1423 /* Compares mime types to the ok and except lists */
1424 int count_body_parts_check(LIST **checklist, BODY *b, int dflt) {
1425   LIST *type;
1426   ATTACH_MATCH *a;
1427
1428   /* If list is null, use default behavior. */
1429   if (! *checklist) {
1430     /*return dflt;*/
1431     return 0;
1432   }
1433
1434   for (type = *checklist; type; type = type->next) {
1435     a = (ATTACH_MATCH *)type->data;
1436     debug_print(5, ("cbpc: %s %d/%s ?? %s/%s [%d]... ",
1437                dflt ? "[OK] " : "[EXCL] ",
1438                b->type, b->subtype, a->major, a->minor, a->major_int));
1439     if ((a->major_int == TYPEANY || a->major_int == b->type) &&
1440         !regexec(&a->minor_rx, b->subtype, 0, NULL, 0)) {
1441       debug_print(5, ("yes\n"));
1442       return 1;
1443     } else {
1444       debug_print(5, ("no\n"));
1445     }
1446   }
1447   return 0;
1448 }
1449
1450 #define AT_COUNT(why) { shallcount = 1; }
1451 #define AT_NOCOUNT(why) { shallcount = 0; }
1452
1453 int count_body_parts (BODY *body, int flags) {
1454   int count = 0;
1455   int shallcount, shallrecurse;
1456   BODY *bp;
1457
1458   if (body == NULL)
1459     return 0;
1460
1461   for (bp = body; bp != NULL; bp = bp->next) {
1462     /* Initial disposition is to count and not to recurse this part. */
1463     AT_COUNT("default");
1464     shallrecurse = 0;
1465
1466     debug_print(5, ("bp: desc=\"%s\"; fn=\"%s\", type=\"%d/%s\"\n",
1467                bp->description ? bp->description : ("none"),
1468                bp->filename ? bp->filename :
1469                bp->d_filename ? bp->d_filename : "(none)",
1470                bp->type, bp->subtype ? bp->subtype : "*"));
1471
1472     if (bp->type == TYPEMESSAGE) {
1473       shallrecurse = 1;
1474
1475       /* If it's an external body pointer, don't recurse it. */
1476       if (!ascii_strcasecmp (bp->subtype, "external-body"))
1477         shallrecurse = 0;
1478
1479       /* Don't count containers if they're top-level. */
1480       if (flags & M_PARTS_TOPLEVEL)
1481         AT_NOCOUNT("top-level message/*");
1482     } else if (bp->type == TYPEMULTIPART) {
1483       /* Always recurse multiparts, except multipart/alternative. */
1484       shallrecurse = 1;
1485       if (!m_strcasecmp(bp->subtype, "alternative"))
1486         shallrecurse = 0;
1487
1488       /* Don't count containers if they're top-level. */
1489       if (flags & M_PARTS_TOPLEVEL)
1490         AT_NOCOUNT("top-level multipart");
1491     }
1492
1493     if (bp->disposition == DISPINLINE &&
1494         bp->type != TYPEMULTIPART && bp->type != TYPEMESSAGE && bp == body)
1495       AT_NOCOUNT("ignore fundamental inlines");
1496
1497     /* If this body isn't scheduled for enumeration already, don't bother
1498      * profiling it further. */
1499
1500     if (shallcount) {
1501       /* Turn off shallcount if message type is not in ok list,
1502        * or if it is in except list. Check is done separately for
1503        * inlines vs. attachments.
1504        */
1505
1506       if (bp->disposition == DISPATTACH) {
1507         if (!count_body_parts_check(&AttachAllow, bp, 1))
1508           AT_NOCOUNT("attach not allowed");
1509         if (count_body_parts_check(&AttachExclude, bp, 0))
1510           AT_NOCOUNT("attach excluded");
1511       } else {
1512         if (!count_body_parts_check(&InlineAllow, bp, 1))
1513           AT_NOCOUNT("inline not allowed");
1514         if (count_body_parts_check(&InlineExclude, bp, 0))
1515           AT_NOCOUNT("excluded");
1516       }
1517     }
1518
1519     if (shallcount)
1520       count++;
1521     bp->attach_qualifies = shallcount ? 1 : 0;
1522
1523     debug_print(5, ("cbp: %p shallcount = %d\n", bp, shallcount));
1524
1525     if (shallrecurse) {
1526       debug_print(5, ("cbp: %p pre count = %d\n", bp, count));
1527       bp->attach_count = count_body_parts(bp->parts, flags & ~M_PARTS_TOPLEVEL);
1528       count += bp->attach_count;
1529       debug_print(5, ("cbp: %p post count = %d\n", bp, count));
1530     }
1531   }
1532
1533   debug_print(5, ("bp: return %d\n", count < 0 ? 0 : count));
1534   return count < 0 ? 0 : count;
1535 }
1536
1537 int mutt_count_body_parts (HEADER *hdr, int flags) {
1538   if (!option (OPTCOUNTATTACH))
1539     return (0);
1540   if (hdr->attach_valid && !(flags & M_PARTS_RECOUNT))
1541     return hdr->attach_total;
1542
1543   if (AttachAllow || AttachExclude || InlineAllow || InlineExclude)
1544     hdr->attach_total = count_body_parts(hdr->content, flags | M_PARTS_TOPLEVEL);
1545   else
1546     hdr->attach_total = 0;
1547
1548   hdr->attach_valid = 1;
1549   return hdr->attach_total;
1550 }