tmp
[apps/madmutt.git] / lib-mime / rfc822parse.c
1 /*
2  *  This program is free software; you can redistribute it and/or modify
3  *  it under the terms of the GNU General Public License as published by
4  *  the Free Software Foundation; either version 2 of the License, or (at
5  *  your option) any later version.
6  *
7  *  This program is distributed in the hope that it will be useful, but
8  *  WITHOUT ANY WARRANTY; without even the implied warranty of
9  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
10  *  General Public License for more details.
11  *
12  *  You should have received a copy of the GNU General Public License
13  *  along with this program; if not, write to the Free Software
14  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
15  *  MA 02110-1301, USA.
16  *
17  *  Copyright © 2006 Pierre Habouzit
18  */
19
20 /*
21  * Copyright notice from original mutt:
22  * Copyright (C) 1996-2000 Michael R. Elkins <me@mutt.org>
23  *
24  * This file is part of mutt-ng, see http://www.muttng.org/.
25  * It's licensed under the GNU General Public License,
26  * please see the file GPL in the top level source directory.
27  */
28
29 #include <lib-lib/lib-lib.h>
30
31 #include "recvattach.h"
32 #include "charset.h"
33 #include "mime.h"
34
35 /* Reads an arbitrarily long header field, and looks ahead for continuation
36  * lines.  ``line'' must point to a dynamically allocated string; it is
37  * increased if more space is required to fit the whole line.
38  */
39 ssize_t mutt_read_rfc822_line(FILE *f, char **line, ssize_t *n)
40 {
41     ssize_t pos = 0;
42
43     for (;;) {
44         char *p = *line;
45
46         /* end of file or end of headers */
47         if (!fgets(p + pos, *n - pos, f) || (ISSPACE(*p) && pos == 0)) {
48             *p = '\0';
49             return 0;
50         }
51
52         pos += m_strlen(p + pos);
53         if (p[pos - 1] == '\n') {
54             int c;
55
56             /* remove trailing spaces. safe: p[0] is not a space */
57             do {
58                 p[--pos] = '\0';
59             } while (ISSPACE(p[pos]));
60
61             /* check to see if the next line is a continuation line */
62             c = fgetc(f);
63             if (c != ' ' && c != '\t') {
64                 /* next line is a separate header field or EOH */
65                 ungetc(c, f);
66                 return pos;
67             }
68
69             /* eat tabs and spaces from the beginning of the continuation line */
70             do {
71                 c = fgetc(f);
72             } while (c == ' ' || c == '\t');
73             ungetc(c, f);
74
75             /* string is still terminated because we removed at least one
76                whitespace char above */
77             p[pos++] = ' ';
78         }
79
80         if (*n < pos + STRING) {
81             /* grow the buffer */
82             *n += STRING;
83             p_realloc(line, *n);
84         }
85     }
86 }
87
88 /* TODO: Make that a string list somehow */
89 string_list_t *mutt_parse_references(char *s, int in_reply_to)
90 {
91     string_list_t *lst = NULL;
92     int n = 0;
93     char *o = NULL;
94
95     /* some mail clients add other garbage besides message-ids, so do a quick
96      * check to make sure this looks like a valid message-id
97      * some idiotic clients also break their message-ids between lines, deal
98      * with that too (give up if it's more than two lines, though)
99      */
100
101     for (s = strtok(s, " \t;"); s; s = strtok(NULL, " \t;")) {
102         char *new = NULL;
103
104         if (*s == '<') {
105             n = m_strlen(s);
106             if (s[n - 1] != '>') {
107                 o = s;
108                 continue;
109             }
110
111             new = m_strdup(s);
112         } else if (o) {
113             ssize_t m = m_strlen(s);
114
115             if (s[m - 1] != '>') {
116                 o = NULL;
117             } else {
118                 new = p_new(char, n + m + 1);
119                 m_strcpy(new, n + m + 1, o);
120                 m_strcpy(new + n, m + 1, s);
121             }
122         }
123
124         /* make sure that this really does look like a message-id.
125          * it should have exactly one @, and if we're looking at
126          * an in-reply-to header, make sure that the part before
127          * the @ has more than eight characters or it's probably
128          * an email address
129          */
130         if (new) {
131             char *at = strchr(new, '@');
132             string_list_t *tmp;
133
134             if (!at || strchr(at + 1, '@') || (in_reply_to && at - new <= 8)) {
135                 p_delete(&new);
136                 continue;
137             }
138
139             tmp = p_new(string_list_t, 1);
140             tmp->data = new;
141             tmp->next = lst;
142             lst = tmp;
143         }
144     }
145
146     return lst;
147 }
148
149 int mutt_check_encoding(const char *s)
150 {
151     int tok = mime_which_token(s, -1);
152     switch (tok) {
153       case MIME_7BIT:
154         return ENC7BIT;
155       case MIME_8BIT:
156         return ENC8BIT;
157       case MIME_BINARY:
158         return ENCBINARY;
159       case MIME_QUOTED_PRINTABLE:
160         return ENCQUOTEDPRINTABLE;
161       case MIME_BASE64:
162         return ENCBASE64;
163       case MIME_X_UUENCODE:
164         return ENCUUENCODED;
165       default:
166         return ENCOTHER;
167     }
168 }
169
170 int mutt_check_mime_type(const char *s)
171 {
172     int tok;
173
174     if (!m_strcmp(s, "*") || !m_strcmp(s, ".*"))
175         return TYPEANY;
176
177     tok = mime_which_token(s, -1);
178     switch (tok) {
179       case MIME_TEXT:        return TYPETEXT;
180       case MIME_MULTIPART:   return TYPEMULTIPART;
181       case MIME_APPLICATION: return TYPEAPPLICATION;
182       case MIME_MESSAGE:     return TYPEMESSAGE;
183       case MIME_IMAGE:       return TYPEIMAGE;
184       case MIME_AUDIO:       return TYPEAUDIO;
185       case MIME_VIDEO:       return TYPEVIDEO;
186       case MIME_MODEL:       return TYPEMODEL;
187       default:               return TYPEOTHER;
188     }
189 }
190
191 static parameters_t *parse_parameters(const char *s)
192 {
193     parameters_t *res = parameter_new();
194
195     while (*s) {
196         char *attr, *val;
197         const char *p;
198         int i;
199
200         s = skipspaces(s);
201         if (*s == '=')             /* parameters are fucked up, go away */
202             break;
203
204         p = strpbrk(s, "=;");
205         if (!p)
206             break;
207
208         if (*p == ';') {
209             /* if we hit a ; now the parameter has no value, just skip it */
210             s = p + 1;
211             continue;
212         }
213
214         i = p - s;
215         attr = p_dupstr(s, i);
216
217         while (--i >= 0 && ISSPACE(attr[i])) {
218             attr[i] = '\0';
219         }
220         s = skipspaces(p + 1);                      /* skip over the = */
221
222         if (*s == '"') {
223             char buffer[LONG_STRING];
224             int state_ascii = 1;
225
226             s++;
227             for (i = 0; *s && i < ssizeof(buffer) - 1; i++, s++) {
228                 /* As iso-2022-* has a characer of '"' with non-ascii state,
229                  * ignore it. */
230                 if (*s == 0x1b && i < ssizeof(buffer) - 2) {
231                     state_ascii = s[1] == '(' && (s[2] == 'B' || s[2] == 'J');
232                 }
233                 if (state_ascii && *s == '"')
234                     break;
235
236                 if (*s == '\\') {
237                     buffer[i] = *++s;
238                 } else {
239                     buffer[i] = *s;
240                 }
241             }
242
243             val = p_dupstr(buffer, i);
244         } else {
245             for (p = s; *p && *p != ' ' && *p != ';'; p++);
246             val = p_dupstr(s, p - s);
247         }
248
249         parameter_setval(res, attr, val);
250         p_delete(&attr);
251         p_delete(&val);
252         s = strchr(s, ';');           /* Find the next parameter */
253         if (!s)
254             break;                    /* no more parameters */
255     }
256
257     rfc2231_decode_parameters(res);
258     return res;
259 }
260
261 void mutt_parse_content_type(char *s, BODY *ct)
262 {
263     char *pc;
264     char *subtype;
265
266     p_delete(&ct->subtype);
267     ct->parameter = NULL;
268
269     /* First extract any existing parameters */
270     if ((pc = strchr(s, ';')) != NULL) {
271         *pc++ = '\0';
272         ct->parameter = parse_parameters(vskipspaces(pc));
273
274         /* Some pre-RFC1521 gateways still use the "name=filename" convention,
275          * but if a filename has already been set in the content-disposition,
276          * let that take precedence, and don't set it here */
277         pc = parameter_getval(ct->parameter, "name");
278         if (pc && !ct->filename)
279             ct->filename = m_strdup(pc);
280     }
281
282     /* Now get the subtype */
283     if ((subtype = strchr (s, '/'))) {
284         *subtype++ = '\0';
285         for (pc = subtype; *pc && !ISSPACE(*pc) && *pc != ';'; pc++);
286         ct->subtype = p_dupstr(subtype, pc - subtype);
287     }
288
289     /* Finally, get the major type */
290     ct->type = mutt_check_mime_type(s);
291
292     if (ct->type == TYPEOTHER) {
293         ct->xtype = m_strdup(s);
294     }
295
296     if (!ct->subtype) {
297         /* Some older non-MIME mailers (i.e., mailtool, elm) have a content-type
298          * field, so we can attempt to convert the type to BODY here.
299          */
300         switch (ct->type) {
301             char buffer[STRING];
302
303           case TYPETEXT:
304             ct->subtype = m_strdup("plain");
305             break;
306
307           case TYPEAUDIO:
308             ct->subtype = m_strdup("basic");
309             break;
310
311           case TYPEMESSAGE:
312             ct->subtype = m_strdup("rfc822");
313             break;
314
315           case TYPEOTHER:
316             ct->type = TYPEAPPLICATION;
317             snprintf(buffer, sizeof(buffer), "x-%s", s);
318             ct->subtype = m_strdup(buffer);
319             break;
320
321           default:
322             ct->subtype = m_strdup("x-unknown");
323             break;
324         }
325     }
326
327     /* Default character set for text types. */
328     if (ct->type == TYPETEXT) {
329         pc = parameter_getval(ct->parameter, "charset");
330         if (!pc) {
331             parameter_setval(ct->parameter, "charset",
332                              charset_getfirst(mod_cset.assumed_charset));
333         }
334     }
335 }
336
337 static void parse_content_disposition(const char *s, BODY *ct)
338 {
339     if (!ascii_strncasecmp(s, "inline", 6)) {
340         ct->disposition = DISPINLINE;
341     } else if (!ascii_strncasecmp(s, "form-data", 9)) {
342         ct->disposition = DISPFORMDATA;
343     } else {
344         ct->disposition = DISPATTACH;
345     }
346
347     /* Check to see if a default filename was given */
348     if ((s = strchr (s, ';'))) {
349         parameters_t *parms = parse_parameters(vskipspaces(s));
350
351         if ((s = parameter_getval(parms, "filename")))
352             m_strreplace(&ct->filename, s);
353         if ((s = parameter_getval(parms, "name")))
354             ct->form_name = m_strdup(s);
355     }
356 }
357
358 /* args:
359  *      fp      stream to read from
360  *
361  *      digest  1 if reading subparts of a multipart/digest, 0
362  *              otherwise
363  */
364 BODY *mutt_read_mime_header(FILE *fp, int digest)
365 {
366     BODY *body = body_new();
367     char *line = p_new(char, LONG_STRING);
368     ssize_t linelen = LONG_STRING;
369     char *p;
370
371     body->hdr_offset  = ftello(fp);
372     body->encoding    = ENC7BIT;    /* default from RFC1521 */
373     body->disposition = DISPINLINE;
374     body->type        = digest ? TYPEMESSAGE : TYPETEXT;
375
376     while (mutt_read_rfc822_line(fp, &line, &linelen)) {
377         /* Find the value of the current header */
378         if ((p = strchr(line, ':'))) {
379             *p++ = '\0';
380             p = vskipspaces(p);
381             if (!*p)
382                 continue;
383         } else {
384             break;
385         }
386
387         switch (mime_which_token(line, -1)) {
388           case MIME_CONTENT_TYPE:
389             mutt_parse_content_type (p, body);
390             break;
391
392           case MIME_CONTENT_TRANSFER_ENCODING:
393             body->encoding = mutt_check_encoding (p);
394             break;
395
396           case MIME_CONTENT_DISPOSITION:
397             parse_content_disposition(p, body);
398             break;
399
400           case MIME_CONTENT_DESCRIPTION:
401             m_strreplace(&body->description, p);
402             rfc2047_decode(&body->description);
403             break;
404
405           default: break;
406         }
407     }
408
409     body->offset = ftello(fp);       /* Mark the start of the real data */
410     if (!body->subtype) {
411         if (body->type == TYPETEXT)
412             body->subtype = m_strdup("plain");
413         if (body->type == TYPEMESSAGE)
414             body->subtype = m_strdup("rfc822");
415     }
416
417     p_delete(&line);
418     return body;
419 }
420
421 void mutt_parse_part(FILE *fp, BODY *b)
422 {
423     char *bound = 0;
424
425     switch (b->type) {
426       case TYPEMULTIPART:
427         bound = parameter_getval(b->parameter, "boundary");
428         fseeko(fp, b->offset, SEEK_SET);
429         b->parts = mutt_parse_multipart(fp, bound, b->offset + b->length,
430                                         mime_which_token(b->subtype, -1) == MIME_DIGEST);
431         break;
432
433       case TYPEMESSAGE:
434         if (b->subtype) {
435             fseeko(fp, b->offset, SEEK_SET);
436
437             if (mutt_is_message_type(b)) {
438                 b->parts = mutt_parse_messageRFC822(fp, b);
439             } else
440             if (mime_which_token(b->subtype, -1) == MIME_EXTERNAL_BODY) {
441                 b->parts = mutt_read_mime_header(fp, 0);
442             } else {
443                 return;
444             }
445         }
446         break;
447
448       default:
449         return;
450     }
451
452     /* try to recover from parsing error */
453     if (!b->parts) {
454         b->type = TYPETEXT;
455         m_strreplace(&b->subtype, "plain");
456     }
457 }
458
459 /* parse a MESSAGE/RFC822 body
460  *
461  * args:
462  *      fp              stream to read from
463  *
464  *      parent          structure which contains info about the message/rfc822
465  *                      body part
466  *
467  * NOTE: this assumes that `parent->length' has been set!
468  */
469 BODY *mutt_parse_messageRFC822(FILE * fp, BODY * parent)
470 {
471     BODY *msg;
472
473     parent->hdr = header_new();
474     parent->hdr->offset = ftello(fp);
475     parent->hdr->env    = mutt_read_rfc822_header(fp, parent->hdr, 0, 0);
476
477     msg = parent->hdr->content;
478
479     /* ignore the length given in the content-length since it could be wrong
480        and we already have the info to calculate the correct length */
481     /* if (msg->length == -1) */
482     /* if body of this message is empty, we can end up with a negative length */
483     msg->length = MAX(0, parent->length - (msg->offset - parent->offset));
484
485     mutt_parse_part(fp, msg);
486
487     return msg;
488 }
489
490 /* parse a multipart structure
491  *
492  * args:
493  *      fp              stream to read from
494  *
495  *      bound           body separator
496  *
497  *      end_off         length of the multipart body (used when the final
498  *                      boundary is missing to avoid reading too far)
499  *
500  *      digest          1 if reading a multipart/digest, 0 otherwise
501  */
502
503 BODY *
504 mutt_parse_multipart(FILE *fp, const char *bound, off_t end_off, int digest)
505 {
506     char buffer[LONG_STRING];
507     BODY *head = NULL;
508     BODY **last = &head;
509     int blen = m_strlen(bound);
510     int final = 0;                /* did we see the ending boundary? */
511
512     if (!blen) {
513         mutt_error _("multipart message has no boundary parameter!");
514         return NULL;
515     }
516
517     while (ftello(fp) < end_off && fgets(buffer, sizeof(buffer), fp)) {
518         int len, crlf, i;
519
520         len  = m_strlen(buffer);
521         crlf = len > 1 && buffer[len - 2] == '\r';
522
523         if (buffer[0] == '-' && buffer[1] == '-'
524         && !m_strncmp(buffer + 2, bound, blen))
525         {
526             if (*last) {
527                 BODY *b = *last;
528
529                 /* if the body is empty, we can end up with a -1 length */
530                 b->length = MAX(0, ftello(fp) - b->offset - len - 1 - crlf);
531                 if (b->parts && b->parts->length == 0) {
532                     b->parts->length = ftello(fp) - b->parts->offset
533                                      - len - 1 - crlf;
534                 }
535             }
536
537             /* Remove any trailing whitespace, up to the length of the boundary */
538             for (i = len - 1; ISSPACE(buffer[i]) && i >= blen + 2; i--)
539                 buffer[i] = '\0';
540
541             /* Check for the end boundary */
542             final = buffer[blen + 3] == '-' && buffer[blen + 4] == '-';
543             if (final)
544                 break;
545
546             if (buffer[2 + blen] == '\0') {
547                 BODY *new = mutt_read_mime_header(fp, digest);
548
549                 /*
550                  * Consistency checking - catch
551                  * bad attachment end boundaries
552                  */
553
554                 if (new->offset > end_off) {
555                     body_list_wipe(&new);
556                     break;
557                 }
558
559                 if (*last)
560                     last = &(*last)->next;
561                 *last = new;
562             }
563         }
564     }
565
566     /* in case of missing end boundary, set the length to something reasonable */
567     if (*last && (*last)->length == 0 && !final)
568         (*last)->length = end_off - (*last)->offset;
569
570     /* parse recursive MIME parts */
571     {
572         BODY *b;
573         for (b = head; b; b = b->next)
574             mutt_parse_part(fp, b);
575     }
576
577     return head;
578 }
579
580 /* parses a date string in RFC822 format:
581  *
582  * Date: [ weekday , ] day-of-month month year hour:minute:second timezone
583  *
584  * This routine assumes that `h' has been initialized to 0.  the `timezone'
585  * field is optional, defaulting to +0000 if missing.
586  */
587 time_t mutt_parse_date(const char *s, HEADER *h)
588 {
589     struct tm tm;
590     const char *loc;
591     time_t tz;
592
593     loc = setlocale(LC_ALL, "C");
594     p_clear(&tm, 1);
595     if (strptime(s, "%a, %d %b %Y %H:%M:%S %z", &tm))
596         goto ok;
597     p_clear(&tm, 1);
598     if (strptime(s, "%a, %d %b %Y %H:%M %z", &tm))
599         goto ok;
600     setlocale(LC_ALL, "");
601     return 0;
602
603   ok:
604     setlocale(LC_ALL, "");
605     tz = tm.tm_gmtoff;
606     return timegm(&tm) - tz;
607 }
608
609 string_list_t **mutt_parse_rfc822_line(ENVELOPE *e, HEADER *hdr, char *line, char *p,
610                               short weed, short do_2047, string_list_t **user_hdrs)
611 {
612     switch (mime_which_token(line, -1)) {
613       case MIME_APPARENTLY_FROM:
614         e->from = rfc822_parse_adrlist (e->from, p);
615         break;
616
617       case MIME_APPARENTLY_TO:
618         e->to = rfc822_parse_adrlist (e->to, p);
619         break;
620
621       case MIME_BCC:
622         e->bcc = rfc822_parse_adrlist (e->bcc, p);
623         break;
624
625       case MIME_CC:
626         e->cc = rfc822_parse_adrlist (e->cc, p);
627         break;
628
629       case MIME_CONTENT_DESCRIPTION:
630         if (hdr) {
631             m_strreplace(&hdr->content->description, p);
632             rfc2047_decode(&hdr->content->description);
633         }
634         break;
635
636       case MIME_CONTENT_DISPOSITION:
637         if (hdr)
638             parse_content_disposition(p, hdr->content);
639         break;
640
641       case MIME_CONTENT_LENGTH:
642         if (hdr) {
643             if ((hdr->content->length = atoi(p)) < 0)
644                 hdr->content->length = -1;
645         }
646         break;
647
648       case MIME_CONTENT_TRANSFER_ENCODING:
649         if (hdr)
650             hdr->content->encoding = mutt_check_encoding(p);
651         break;
652
653       case MIME_CONTENT_TYPE:
654         if (hdr)
655             mutt_parse_content_type (p, hdr->content);
656         break;
657
658       case MIME_DATE:
659         m_strreplace(&e->date, p);
660         if (hdr)
661             hdr->date_sent = mutt_parse_date (p, hdr);
662         break;
663
664       case MIME_EXPIRES:
665         if (hdr && mutt_parse_date (p, NULL) < time (NULL))
666             hdr->expired = 1;
667         break;
668
669       case MIME_FROM:
670         e->from = rfc822_parse_adrlist(e->from, p);
671         /* don't leave from info NULL if there's an invalid address (or
672          * whatever) in From: field; mutt would just display it as empty
673          * and mark mail/(esp.) news article as your own. aaargh! this
674          * bothered me for _years_ */
675         if (!e->from) {
676             e->from = address_new();
677             e->from->personal = m_strdup(p);
678         }
679         break;
680
681       case MIME_IN_REPLY_TO:
682         string_list_wipe(&e->in_reply_to);
683         e->in_reply_to = mutt_parse_references(p, 1);
684         break;
685
686       case MIME_LINES:
687         if (hdr) {
688             /* HACK - mutt has, for a very short time, produced negative
689                Lines header values.  Ignore them. */
690             hdr->lines = MAX(0, atoi(p));
691         }
692         break;
693
694       case MIME_LIST_POST:
695         /* RFC 2369.  FIXME: We should ignore whitespace, but don't. */
696         if (m_strncmp(p, "NO", 2)) {
697             char *beg, *end;
698
699             for (beg = strchr (p, '<'); beg; beg = strchr (end, ',')) {
700                 ++beg;
701                 if (!(end = strchr (beg, '>')))
702                     break;
703
704                 /* Take the first mailto URL */
705                 if (url_check_scheme (beg) == U_MAILTO) {
706                     p_delete(&e->list_post);
707                     e->list_post = p_dupstr(beg, end - beg);
708                     break;
709                 }
710             }
711         }
712         break;
713
714       case MIME_MAIL_FOLLOWUP_TO:
715         e->mail_followup_to = rfc822_parse_adrlist(e->mail_followup_to, p);
716         break;
717
718       case MIME_MAIL_REPLY_TO:
719         address_list_wipe(&e->reply_to);
720         e->reply_to = rfc822_parse_adrlist(e->reply_to, p);
721         break;
722
723       case MIME_MESSAGE_ID:
724         {
725             const char *beg, *end;
726
727             /* We add a new "Message-ID:" when building a message */
728             p_delete(&e->message_id);
729
730             if ((beg = strchr(p, '<')) && (end = strchr(beg, '>')))
731                 e->message_id = p_dupstr(beg, (end - beg) + 1);
732         }
733         break;
734
735       case MIME_MIME_VERSION:
736         if (hdr)
737             hdr->mime = 1;
738         break;
739
740       case MIME_ORGANIZATION:
741         if (!e->organization && mime_which_token(p, -1) == MIME_UNKNOWN)
742             e->organization = m_strdup(p);
743         break;
744
745       case MIME_RECEIVED:
746         if (hdr && !hdr->received) {
747             char *d = strchr(p, ';');
748             if (d)
749                 hdr->received = mutt_parse_date(d + 1, NULL);
750         }
751         break;
752
753       case MIME_REFERENCES:
754         string_list_wipe(&e->references);
755         e->references = mutt_parse_references(p, 0);
756         break;
757
758       case MIME_REPLY_TO:
759         e->reply_to = rfc822_parse_adrlist(e->reply_to, p);
760         break;
761
762       case MIME_RETURN_PATH:
763         e->return_path = rfc822_parse_adrlist(e->return_path, p);
764         break;
765
766       case MIME_SENDER:
767         e->sender = rfc822_parse_adrlist (e->sender, p);
768         break;
769
770       case MIME_STATUS:
771         if (hdr) {
772             while (*p) {
773                 switch (*p) {
774                   case 'r':
775                     hdr->replied = 1;
776                     break;
777                   case 'O':
778                     hdr->old = 1;
779                     break;
780                   case 'R':
781                     hdr->read = 1;
782                     break;
783                 }
784                 p++;
785             }
786         }
787         break;
788
789       case MIME_SUBJECT:
790         if (!e->subject)
791             e->subject = m_strdup(p);
792         break;
793
794       case MIME_SUPERCEDES:
795       case MIME_SUPERSEDES:
796         if (hdr)
797             e->supersedes = m_strdup(p);
798         break;
799
800       case MIME_TO:
801         e->to = rfc822_parse_adrlist(e->to, p);
802         break;
803
804       case MIME_X_LABEL:
805         e->x_label = m_strdup(p);
806         break;
807
808       case MIME_X_STATUS:
809         if (hdr) {
810             while (*p) {
811                 switch (*p) {
812                   case 'A':
813                     hdr->replied = 1;
814                     break;
815                   case 'D':
816                     hdr->deleted = 1;
817                     break;
818                   case 'F':
819                     hdr->flagged = 1;
820                     break;
821                   default:
822                     break;
823                 }
824                 p++;
825             }
826         }
827         break;
828
829       default:
830         if (!user_hdrs)
831             break;
832
833         /* restore the original line */
834         line[m_strlen(line)] = ':';
835
836         if (weed && string_list_contains(Ignore, line, "*")
837         && !string_list_contains(UnIgnore, line, "*")) {
838             break;
839         }
840
841         *user_hdrs = string_item_new();
842         (*user_hdrs)->data = m_strdup(line);
843         if (do_2047)
844             rfc2047_decode(&(*user_hdrs)->data);
845         return &(*user_hdrs)->next;
846     }
847
848     return user_hdrs;
849 }
850
851 /* mutt_read_rfc822_header() -- parses a RFC822 header
852  *
853  * Args:
854  *
855  * f            stream to read from
856  *
857  * hdr          header structure of current message (optional).
858  *
859  * user_hdrs    If set, store user headers.  Used for recall-message and
860  *              postpone modes.
861  *
862  * weed         If this parameter is set and the user has activated the
863  *              $weed option, honor the header weed list for user headers.
864  *              Used for recall-message.
865  *
866  * Returns:     newly allocated envelope structure.  You should free it by
867  *              envelope_delete() when envelope stay unneeded.
868  */
869 ENVELOPE *
870 mutt_read_rfc822_header(FILE *f, HEADER *hdr, short user_hdrs, short weed)
871 {
872     ENVELOPE *e = envelope_new();
873     string_list_t **last = user_hdrs ? &e->userhdrs : NULL;
874
875     char *line = p_new(char, LONG_STRING);
876     ssize_t linelen = LONG_STRING;
877     off_t loc;
878
879     if (hdr && !hdr->content) {
880         hdr->content = body_new();
881
882         /* set the defaults from RFC1521 */
883         hdr->content->type     = TYPETEXT;
884         hdr->content->subtype  = m_strdup("plain");
885         hdr->content->encoding = ENC7BIT;
886         hdr->content->length   = -1;
887
888         /* RFC 2183 says this is arbitrary */
889         hdr->content->disposition = DISPINLINE;
890     }
891
892     while ((loc = ftello(f)),
893            mutt_read_rfc822_line(f, &line, &linelen))
894     {
895         char buf[LONG_STRING + 1] = "";
896         char *p;
897
898         p = strpbrk(line, ": \t");
899         if (!p || *p != ':') {
900             /* some bogus MTAs will quote the original "From " line */
901             if (!m_strncmp(">From ", line, 6) || !m_strncmp("From ", line, 5))
902                 continue;               /* just ignore */
903
904             fseeko(f, loc, 0);
905             break;                    /* end of header */
906         }
907
908         if (rx_list_match2(SpamList, line, buf, sizeof(buf))
909         && !rx_list_match(NoSpamList, line))
910         {
911             /* if spam tag already exists, figure out how to amend it */
912             if (e->spam && *buf) {
913                 if (mod_mime.spam_separator) {
914                     mutt_buffer_addstr(e->spam, mod_mime.spam_separator);
915                 } else {
916                     mutt_buffer_reset(e->spam);
917                 }
918                 mutt_buffer_addstr(e->spam, buf);
919             }
920
921             if (!e->spam) {
922                 e->spam = mutt_buffer_from(NULL, buf);
923             }
924         }
925
926         *p++ = '\0';
927         p = vskipspaces(p);
928         if (!*p)
929             continue;                 /* skip empty header fields */
930
931         last = mutt_parse_rfc822_line(e, hdr, line, p, weed, 1, last);
932     }
933
934     p_delete(&line);
935
936     if (hdr) {
937         hdr->content->hdr_offset = hdr->offset;
938         hdr->content->offset     = ftello(f);
939         rfc2047_decode_envelope(e);
940         /* check for missing or invalid date */
941         if (hdr->date_sent <= 0) {
942             hdr->date_sent = hdr->received;
943         }
944     }
945
946     return e;
947 }
948
949 /* Compares mime types to the ok and except lists */
950 static int count_body_parts_check(string_list_t **checklist, BODY *b)
951 {
952     string_list_t *type;
953
954     for (type = *checklist; type; type = type->next) {
955         ATTACH_MATCH *a = (ATTACH_MATCH *)type->data;
956
957         if ((a->major_int == TYPEANY || a->major_int == b->type)
958         &&  !regexec(&a->minor_rx, b->subtype, 0, NULL, 0)) {
959             return 1;
960         }
961     }
962
963     return 0;
964 }
965
966 static int count_body_parts (BODY *body, int flags)
967 {
968     int count = 0;
969     BODY *bp;
970
971     if (!body)
972         return 0;
973
974     for (bp = body; bp != NULL; bp = bp->next) {
975         /* Initial disposition is to count and not to recurse this part. */
976         int shallcount, shallrecurse, iscontainer;
977         int tok = mime_which_token(bp->subtype, -1);
978
979         iscontainer  = bp->type == TYPEMESSAGE || bp->type == TYPEMULTIPART;
980
981         /* don't recurse in external bodies or multipart/alternatives */
982         shallrecurse = (bp->type == TYPEMESSAGE && tok != MIME_EXTERNAL_BODY)
983                     || (bp->type == TYPEMULTIPART && tok != MIME_ALTERNATIVE);
984
985         /* Don't count top level containers and fundamental inlines */
986         shallcount   = !(iscontainer && (flags & M_PARTS_TOPLEVEL))
987                     && !(!iscontainer && bp->disposition == DISPINLINE && bp == body);
988
989         if (shallcount) {
990             /* Turn off shallcount if message type is not in ok list,
991              * or if it is in except list. Check is done separately for
992              * inlines vs. attachments.
993              */
994
995             if (bp->disposition == DISPATTACH) {
996                 if (!count_body_parts_check(&AttachAllow, bp))
997                     shallcount = 0;
998                 if (count_body_parts_check(&AttachExclude, bp))
999                     shallcount = 0;
1000             } else {
1001                 if (!count_body_parts_check(&InlineAllow, bp))
1002                     shallcount = 0;
1003                 if (count_body_parts_check(&InlineExclude, bp))
1004                     shallcount = 0;
1005             }
1006         }
1007
1008         bp->attach_qualifies = shallcount;
1009         count += shallcount;
1010
1011         if (shallrecurse) {
1012             bp->attach_count = count_body_parts(bp->parts,
1013                                                 flags & ~M_PARTS_TOPLEVEL);
1014             count += bp->attach_count;
1015         }
1016     }
1017
1018     return count;
1019 }
1020
1021 int mutt_count_body_parts(HEADER *hdr, int flags)
1022 {
1023     if (hdr->attach_valid && !(flags & M_PARTS_RECOUNT))
1024         return hdr->attach_total;
1025
1026     if (AttachAllow || AttachExclude || InlineAllow || InlineExclude)
1027         hdr->attach_total = count_body_parts(hdr->content,
1028                                              flags | M_PARTS_TOPLEVEL);
1029     else
1030         hdr->attach_total = 0;
1031
1032     hdr->attach_valid = 1;
1033     return hdr->attach_total;
1034 }
1035
1036 /*
1037  * A valid message separator looks like:
1038  *
1039  * From [ <return-path> ] <weekday> <month> <day> <time> [ <timezone> ] <year>
1040  */
1041 bool is_from(const char *s, char *path, ssize_t pathlen, time_t *tp)
1042 {
1043     const char *p;
1044     struct tm tm;
1045     char *loc;
1046     int q = 0;
1047
1048     if (path)
1049         *path = 0;
1050
1051     if (m_strncmp("From ", s, 5) != 0)
1052         return false;
1053
1054     s = skipspaces(s + 5);         /* skip over the From part. */
1055     if (!*s)
1056         return false;
1057
1058     for (p = s; *p && (q || !ISSPACE(*p)); p++) {
1059         if (*p == '\\') {
1060             if (*++p == '\0')
1061                 return false;
1062         }
1063         else if (*p == '"') {
1064             q = !q;
1065         }
1066     }
1067
1068     if (q || !*p)
1069         return false;
1070
1071     if (path)
1072         m_strncpy(path, pathlen, s, p - s);
1073
1074     s = vskipspaces(p + 1);
1075     if (!*s)
1076         return false;
1077
1078     loc = setlocale(LC_TIME, "C");
1079     for (int i = 0; i < 4; i++) {
1080         static char const * const formats[] = {
1081             "%a %b %d %H:%M:%S %Y",
1082             "%a %b %d %H:%M:%S %z %Y",
1083             "%a %b %d %H:%M %Y",
1084             "%a %b %d %H:%M %z %Y",
1085         };
1086
1087         p_clear(&tm, 1);
1088         p = strptime(s, formats[i], &tm);
1089         if (p) {
1090             s = p;
1091             goto ok;
1092         }
1093     }
1094     setlocale(LC_TIME, loc);
1095     return false;
1096
1097   ok:
1098     if (tp) {
1099         *tp = tm.tm_gmtoff;
1100         *tp = timegm(&tm) - *tp;
1101     }
1102     return true;
1103 }