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