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