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