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