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