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