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