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