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