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