Nico Golde:
[apps/madmutt.git] / parse.c
1 /*
2  * Copyright (C) 1996-2000 Michael R. Elkins <me@mutt.org>
3  * 
4  *     This program is free software; you can redistribute it and/or modify
5  *     it under the terms of the GNU General Public License as published by
6  *     the Free Software Foundation; either version 2 of the License, or
7  *     (at your option) any later version.
8  * 
9  *     This program is distributed in the hope that it will be useful,
10  *     but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *     GNU General Public License for more details.
13  * 
14  *     You should have received a copy of the GNU General Public License
15  *     along with this program; if not, write to the Free Software
16  *     Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
17  */ 
18
19 #if HAVE_CONFIG_H
20 # include "config.h"
21 #endif
22
23 #include "mutt.h"
24 #include "mutt_regex.h"
25 #include "mailbox.h"
26 #include "mime.h"
27 #include "rfc2047.h"
28 #include "rfc2231.h"
29 #include "mutt_crypt.h"
30 #include "url.h"
31
32 #include <string.h>
33 #include <ctype.h>
34 #include <sys/stat.h>
35 #include <stdlib.h>
36
37 /* Reads an arbitrarily long header field, and looks ahead for continuation
38  * lines.  ``line'' must point to a dynamically allocated string; it is
39  * increased if more space is required to fit the whole line.
40  */
41 static char *read_rfc822_line (FILE *f, char *line, size_t *linelen)
42 {
43   char *buf = line;
44   char ch;
45   size_t offset = 0;
46
47   FOREVER
48   {
49     if (fgets (buf, *linelen - offset, f) == NULL ||    /* end of file or */
50         (ISSPACE (*line) && !offset))                   /* end of headers */ 
51     {
52       *line = 0;
53       return (line);
54     }
55
56     buf += strlen (buf) - 1;
57     if (*buf == '\n')
58     {
59       /* we did get a full line. remove trailing space */
60       while (ISSPACE (*buf))
61         *buf-- = 0;     /* we cannot come beyond line's beginning because
62                          * it begins with a non-space */
63
64       /* check to see if the next line is a continuation line */
65       if ((ch = fgetc (f)) != ' ' && ch != '\t')
66       {
67         ungetc (ch, f);
68         return (line); /* next line is a separate header field or EOH */
69       }
70
71       /* eat tabs and spaces from the beginning of the continuation line */
72       while ((ch = fgetc (f)) == ' ' || ch == '\t')
73         ;
74       ungetc (ch, f);
75       *++buf = ' '; /* string is still terminated because we removed
76                        at least one whitespace char above */
77     }
78
79     buf++;
80     offset = buf - line;
81     if (*linelen < offset + STRING)
82     {
83       /* grow the buffer */
84       *linelen += STRING;
85       safe_realloc (&line, *linelen);
86       buf = line + offset;
87     }
88   }
89   /* not reached */
90 }
91
92 LIST *mutt_parse_references (char *s, int in_reply_to)
93 {
94   LIST *t, *lst = NULL;
95   int m, n = 0;
96   char *o = NULL, *new, *at;
97
98   while ((s = strtok (s, " \t;")) != NULL)
99   {
100     /*
101      * some mail clients add other garbage besides message-ids, so do a quick
102      * check to make sure this looks like a valid message-id
103      * some idiotic clients also break their message-ids between lines, deal
104      * with that too (give up if it's more than two lines, though)
105      */
106     t = NULL;
107     new = NULL;
108
109     if (*s == '<')
110     {
111       n = strlen (s);
112       if (s[n-1] != '>')
113       {
114         o = s;
115         s = NULL;
116         continue;
117       }
118
119       new = safe_strdup (s);
120     }
121     else if (o)
122     {
123       m = strlen (s);
124       if (s[m - 1] == '>')
125       {
126         new = safe_malloc (sizeof (char) * (n + m + 1));
127         strcpy (new, o);        /* __STRCPY_CHECKED__ */
128         strcpy (new + n, s);    /* __STRCPY_CHECKED__ */
129       }
130     }
131     if (new)
132     {
133       /* make sure that this really does look like a message-id.
134        * it should have exactly one @, and if we're looking at
135        * an in-reply-to header, make sure that the part before
136        * the @ has more than eight characters or it's probably
137        * an email address
138        */
139       if (!(at = strchr (new, '@')) || strchr (at + 1, '@')
140           || (in_reply_to && at - new <= 8))
141         FREE (&new);
142       else
143       {
144         t = (LIST *) safe_malloc (sizeof (LIST));
145         t->data = new;
146         t->next = lst;
147         lst = t;
148       }
149     }
150     o = NULL;
151     s = NULL;
152   }
153
154   return (lst);
155 }
156
157 int mutt_check_encoding (const char *c)
158 {
159   if (ascii_strncasecmp ("7bit", c, sizeof ("7bit")-1) == 0)
160     return (ENC7BIT);
161   else if (ascii_strncasecmp ("8bit", c, sizeof ("8bit")-1) == 0)
162     return (ENC8BIT);
163   else if (ascii_strncasecmp ("binary", c, sizeof ("binary")-1) == 0)
164     return (ENCBINARY);
165   else if (ascii_strncasecmp ("quoted-printable", c, sizeof ("quoted-printable")-1) == 0)
166     return (ENCQUOTEDPRINTABLE);
167   else if (ascii_strncasecmp ("base64", c, sizeof("base64")-1) == 0)
168     return (ENCBASE64);
169   else if (ascii_strncasecmp ("x-uuencode", c, sizeof("x-uuencode")-1) == 0)
170     return (ENCUUENCODED);
171 #ifdef SUN_ATTACHMENT
172   else if (ascii_strncasecmp ("uuencode", c, sizeof("uuencode")-1) == 0)
173     return (ENCUUENCODED);
174 #endif
175   else
176     return (ENCOTHER);
177 }
178
179 static PARAMETER *parse_parameters (const char *s)
180 {
181   PARAMETER *head = 0, *cur = 0, *new;
182   char buffer[LONG_STRING];
183   const char *p;
184   size_t i;
185
186   dprint (2, (debugfile, "parse_parameters: `%s'\n", s));
187   
188   while (*s)
189   {
190     if ((p = strpbrk (s, "=;")) == NULL)
191     {
192       dprint(1, (debugfile, "parse_parameters: malformed parameter: %s\n", s));
193       goto bail;
194     }
195
196     /* if we hit a ; now the parameter has no value, just skip it */
197     if (*p != ';')
198     {
199       i = p - s;
200
201       new = mutt_new_parameter ();
202
203       new->attribute = safe_malloc (i + 1);
204       memcpy (new->attribute, s, i);
205       new->attribute[i] = 0;
206
207       /* remove whitespace from the end of the attribute name */
208       while (ISSPACE (new->attribute[--i]))
209         new->attribute[i] = 0;
210
211       s = p + 1; /* skip over the = */
212       SKIPWS (s);
213
214       if (*s == '"')
215       {
216         s++;
217         for (i=0; *s && *s != '"' && i < sizeof (buffer) - 1; i++, s++)
218         {
219           if (*s == '\\')
220           {
221             /* Quote the next character */
222             buffer[i] = s[1];
223             if (!*++s)
224               break;
225           }
226           else
227             buffer[i] = *s;
228         }
229         buffer[i] = 0;
230         if (*s)
231           s++; /* skip over the " */
232       }
233       else
234       {
235         for (i=0; *s && *s != ' ' && *s != ';' && i < sizeof (buffer) - 1; i++, s++)
236           buffer[i] = *s;
237         buffer[i] = 0;
238       }
239
240       new->value = safe_strdup (buffer);
241
242       dprint (2, (debugfile, "parse_parameter: `%s' = `%s'\n",
243                   new->attribute ? new->attribute : "",
244                   new->value ? new->value : ""));
245       
246       /* Add this parameter to the list */
247       if (head)
248       {
249         cur->next = new;
250         cur = cur->next;
251       }
252       else
253         head = cur = new;
254     }
255     else
256     {
257       dprint (1, (debugfile, "parse_parameters(): parameter with no value: %s\n", s));
258       s = p;
259     }
260
261     /* Find the next parameter */
262     if (*s != ';' && (s = strchr (s, ';')) == NULL)
263         break; /* no more parameters */
264
265     do
266     {
267       s++;
268
269       /* Move past any leading whitespace */
270       SKIPWS (s);
271     }
272     while (*s == ';'); /* skip empty parameters */
273   }    
274
275   bail:
276
277   rfc2231_decode_parameters (&head);
278   return (head);
279 }
280
281 int mutt_check_mime_type (const char *s)
282 {
283   if (ascii_strcasecmp ("text", s) == 0)
284     return TYPETEXT;
285   else if (ascii_strcasecmp ("multipart", s) == 0)
286     return TYPEMULTIPART;
287 #ifdef SUN_ATTACHMENT 
288   else if (ascii_strcasecmp ("x-sun-attachment", s) == 0)
289     return TYPEMULTIPART;
290 #endif
291   else if (ascii_strcasecmp ("application", s) == 0)
292     return TYPEAPPLICATION;
293   else if (ascii_strcasecmp ("message", s) == 0)
294     return TYPEMESSAGE;
295   else if (ascii_strcasecmp ("image", s) == 0)
296     return TYPEIMAGE;
297   else if (ascii_strcasecmp ("audio", s) == 0)
298     return TYPEAUDIO;
299   else if (ascii_strcasecmp ("video", s) == 0)
300     return TYPEVIDEO;
301   else if (ascii_strcasecmp ("model", s) == 0)
302     return TYPEMODEL;
303   else
304     return TYPEOTHER;
305 }
306
307 void mutt_parse_content_type (char *s, BODY *ct)
308 {
309   char *pc;
310   char *subtype;
311
312   FREE (&ct->subtype);
313   mutt_free_parameter(&ct->parameter);
314
315   /* First extract any existing parameters */
316   if ((pc = strchr(s, ';')) != NULL)
317   {
318     *pc++ = 0;
319     while (*pc && ISSPACE (*pc))
320       pc++;
321     ct->parameter = parse_parameters(pc);
322
323     /* Some pre-RFC1521 gateways still use the "name=filename" convention,
324      * but if a filename has already been set in the content-disposition,
325      * let that take precedence, and don't set it here */
326     if ((pc = mutt_get_parameter( "name", ct->parameter)) != 0 && !ct->filename)
327       ct->filename = safe_strdup(pc);
328     
329 #ifdef SUN_ATTACHMENT
330     /* this is deep and utter perversion */
331     if ((pc = mutt_get_parameter ("conversions", ct->parameter)) != 0)
332       ct->encoding = mutt_check_encoding (pc);
333 #endif
334     
335   }
336   
337   /* Now get the subtype */
338   if ((subtype = strchr(s, '/')))
339   {
340     *subtype++ = '\0';
341     for(pc = subtype; *pc && !ISSPACE(*pc) && *pc != ';'; pc++)
342       ;
343     *pc = '\0';
344     ct->subtype = safe_strdup (subtype);
345   }
346
347   /* Finally, get the major type */
348   ct->type = mutt_check_mime_type (s);
349
350 #ifdef SUN_ATTACHMENT
351   if (ascii_strcasecmp ("x-sun-attachment", s) == 0)
352       ct->subtype = safe_strdup ("x-sun-attachment");
353 #endif
354
355   if (ct->type == TYPEOTHER)
356   {
357     ct->xtype = safe_strdup (s);
358   }
359
360   if (ct->subtype == NULL)
361   {
362     /* Some older non-MIME mailers (i.e., mailtool, elm) have a content-type
363      * field, so we can attempt to convert the type to BODY here.
364      */
365     if (ct->type == TYPETEXT)
366       ct->subtype = safe_strdup ("plain");
367     else if (ct->type == TYPEAUDIO)
368       ct->subtype = safe_strdup ("basic");
369     else if (ct->type == TYPEMESSAGE)
370       ct->subtype = safe_strdup ("rfc822");
371     else if (ct->type == TYPEOTHER)
372     {
373       char buffer[SHORT_STRING];
374
375       ct->type = TYPEAPPLICATION;
376       snprintf (buffer, sizeof (buffer), "x-%s", s);
377       ct->subtype = safe_strdup (buffer);
378     }
379     else
380       ct->subtype = safe_strdup ("x-unknown");
381   }
382
383   /* Default character set for text types. */
384   if (ct->type == TYPETEXT)
385   {
386     if (!(pc = mutt_get_parameter ("charset", ct->parameter)))
387       mutt_set_parameter ("charset", "us-ascii", &ct->parameter);
388   }
389
390 }
391
392 static void parse_content_disposition (char *s, BODY *ct)
393 {
394   PARAMETER *parms;
395
396   if (!ascii_strncasecmp ("inline", s, 6))
397     ct->disposition = DISPINLINE;
398   else if (!ascii_strncasecmp ("form-data", s, 9))
399     ct->disposition = DISPFORMDATA;
400   else
401     ct->disposition = DISPATTACH;
402
403   /* Check to see if a default filename was given */
404   if ((s = strchr (s, ';')) != NULL)
405   {
406     s++;
407     SKIPWS (s);
408     if ((s = mutt_get_parameter ("filename", (parms = parse_parameters (s)))) != 0)
409       mutt_str_replace (&ct->filename, s);
410     if ((s = mutt_get_parameter ("name", parms)) != 0)
411       ct->form_name = safe_strdup (s);
412     mutt_free_parameter (&parms);
413   }
414 }
415
416 /* args:
417  *      fp      stream to read from
418  *
419  *      digest  1 if reading subparts of a multipart/digest, 0
420  *              otherwise
421  */
422
423 BODY *mutt_read_mime_header (FILE *fp, int digest)
424 {
425   BODY *p = mutt_new_body();
426   char *c;
427   char *line = safe_malloc (LONG_STRING);
428   size_t linelen = LONG_STRING;
429   
430   p->hdr_offset  = ftell(fp);
431
432   p->encoding    = ENC7BIT; /* default from RFC1521 */
433   p->type        = digest ? TYPEMESSAGE : TYPETEXT;
434   p->disposition = DISPINLINE;
435   
436   while (*(line = read_rfc822_line (fp, line, &linelen)) != 0)
437   {
438     /* Find the value of the current header */
439     if ((c = strchr (line, ':')))
440     {
441       *c = 0;
442       c++;
443       SKIPWS (c);
444       if (!*c)
445       {
446         dprint (1, (debugfile, "mutt_read_mime_header(): skipping empty header field: %s\n", line));
447         continue;
448       }
449     }
450     else
451     {
452       dprint (1, (debugfile, "read_mime_header: bogus MIME header: %s\n", line));
453       break;
454     }
455
456     if (!ascii_strncasecmp ("content-", line, 8))
457     {
458       if (!ascii_strcasecmp ("type", line + 8))
459         mutt_parse_content_type (c, p);
460       else if (!ascii_strcasecmp ("transfer-encoding", line + 8))
461         p->encoding = mutt_check_encoding (c);
462       else if (!ascii_strcasecmp ("disposition", line + 8))
463         parse_content_disposition (c, p);
464       else if (!ascii_strcasecmp ("description", line + 8))
465       {
466         mutt_str_replace (&p->description, c);
467         rfc2047_decode (&p->description);
468       }
469     } 
470 #ifdef SUN_ATTACHMENT
471     else if (!ascii_strncasecmp ("x-sun-", line, 6))
472     {
473       if (!ascii_strcasecmp ("data-type", line + 6))
474         mutt_parse_content_type (c, p);
475       else if (!ascii_strcasecmp ("encoding-info", line + 6))
476         p->encoding = mutt_check_encoding (c);
477       else if (!ascii_strcasecmp ("content-lines", line + 6))
478         mutt_set_parameter ("content-lines", c, &(p->parameter));
479       else if (!ascii_strcasecmp ("data-description", line + 6))
480       {
481         mutt_str_replace (&p->description, c);
482         rfc2047_decode (&p->description);
483       }
484     }
485 #endif
486   }
487   p->offset = ftell (fp); /* Mark the start of the real data */
488   if (p->type == TYPETEXT && !p->subtype)
489     p->subtype = safe_strdup ("plain");
490   else if (p->type == TYPEMESSAGE && !p->subtype)
491     p->subtype = safe_strdup ("rfc822");
492
493   FREE (&line);
494
495   return (p);
496 }
497
498 void mutt_parse_part (FILE *fp, BODY *b)
499 {
500   char *bound = 0;
501
502   switch (b->type)
503   {
504     case TYPEMULTIPART:
505 #ifdef SUN_ATTACHMENT
506       if ( !ascii_strcasecmp (b->subtype, "x-sun-attachment") )
507           bound = "--------";
508       else
509 #endif
510           bound = mutt_get_parameter ("boundary", b->parameter);
511
512       fseek (fp, b->offset, SEEK_SET);
513       b->parts =  mutt_parse_multipart (fp, bound, 
514                                         b->offset + b->length,
515                                         ascii_strcasecmp ("digest", b->subtype) == 0);
516       break;
517
518     case TYPEMESSAGE:
519       if (b->subtype)
520       {
521         fseek (fp, b->offset, SEEK_SET);
522         if (mutt_is_message_type(b->type, b->subtype))
523           b->parts = mutt_parse_messageRFC822 (fp, b);
524         else if (ascii_strcasecmp (b->subtype, "external-body") == 0)
525           b->parts = mutt_read_mime_header (fp, 0);
526         else
527           return;
528       }
529       break;
530
531     default:
532       return;
533   }
534
535   /* try to recover from parsing error */
536   if (!b->parts)
537   {
538     b->type = TYPETEXT;
539     mutt_str_replace (&b->subtype, "plain");
540   }
541 }
542
543 /* parse a MESSAGE/RFC822 body
544  *
545  * args:
546  *      fp              stream to read from
547  *
548  *      parent          structure which contains info about the message/rfc822
549  *                      body part
550  *
551  * NOTE: this assumes that `parent->length' has been set!
552  */
553
554 BODY *mutt_parse_messageRFC822 (FILE *fp, BODY *parent)
555 {
556   BODY *msg;
557
558   parent->hdr = mutt_new_header ();
559   parent->hdr->offset = ftell (fp);
560   parent->hdr->env = mutt_read_rfc822_header (fp, parent->hdr, 0, 0);
561   msg = parent->hdr->content;
562
563   /* ignore the length given in the content-length since it could be wrong
564      and we already have the info to calculate the correct length */
565   /* if (msg->length == -1) */
566   msg->length = parent->length - (msg->offset - parent->offset);
567
568   /* if body of this message is empty, we can end up with a negative length */
569   if (msg->length < 0)
570     msg->length = 0;
571
572   mutt_parse_part(fp, msg);
573   return (msg);
574 }
575
576 /* parse a multipart structure
577  *
578  * args:
579  *      fp              stream to read from
580  *
581  *      boundary        body separator
582  *
583  *      end_off         length of the multipart body (used when the final
584  *                      boundary is missing to avoid reading too far)
585  *
586  *      digest          1 if reading a multipart/digest, 0 otherwise
587  */
588
589 BODY *mutt_parse_multipart (FILE *fp, const char *boundary, long end_off, int digest)
590 {
591 #ifdef SUN_ATTACHMENT
592   int lines;
593 #endif
594   int blen, len, crlf = 0;
595   char buffer[LONG_STRING];
596   BODY *head = 0, *last = 0, *new = 0;
597   int i;
598   int final = 0; /* did we see the ending boundary? */
599
600   if (!boundary)
601   {
602     mutt_error _("multipart message has no boundary parameter!");
603     return (NULL);
604   }
605
606   blen = mutt_strlen (boundary);
607   while (ftell (fp) < end_off && fgets (buffer, LONG_STRING, fp) != NULL)
608   {
609     len = mutt_strlen (buffer);
610
611     crlf =  (len > 1 && buffer[len - 2] == '\r') ? 1 : 0;
612
613     if (buffer[0] == '-' && buffer[1] == '-' &&
614         mutt_strncmp (buffer + 2, boundary, blen) == 0)
615     {
616       if (last)
617       {
618         last->length = ftell (fp) - last->offset - len - 1 - crlf;
619         if (last->parts && last->parts->length == 0)
620           last->parts->length = ftell (fp) - last->parts->offset - len - 1 - crlf;
621         /* if the body is empty, we can end up with a -1 length */
622         if (last->length < 0)
623           last->length = 0;
624       }
625
626       /* Remove any trailing whitespace, up to the length of the boundary */
627       for (i = len - 1; ISSPACE (buffer[i]) && i >= blen + 2; i--)
628         buffer[i] = 0;
629
630       /* Check for the end boundary */
631       if (mutt_strcmp (buffer + blen + 2, "--") == 0)
632       {
633         final = 1;
634         break; /* done parsing */
635       }
636       else if (buffer[2 + blen] == 0)
637       {
638         new = mutt_read_mime_header (fp, digest);
639
640 #ifdef SUN_ATTACHMENT
641         if (mutt_get_parameter ("content-lines", new->parameter)) {
642           for (lines = atoi(mutt_get_parameter ("content-lines", new->parameter));
643                lines; lines-- )
644              if (ftell (fp) >= end_off || fgets (buffer, LONG_STRING, fp) == NULL)
645                break;
646         }
647 #endif
648         
649         /*
650          * Consistency checking - catch
651          * bad attachment end boundaries
652          */
653         
654         if(new->offset > end_off)
655         {
656           mutt_free_body(&new);
657           break;
658         }
659         if (head)
660         {
661           last->next = new;
662           last = new;
663         }
664         else
665           last = head = new;
666       }
667     }
668   }
669
670   /* in case of missing end boundary, set the length to something reasonable */
671   if (last && last->length == 0 && !final)
672     last->length = end_off - last->offset;
673
674   /* parse recursive MIME parts */
675   for(last = head; last; last = last->next)
676     mutt_parse_part(fp, last);
677   
678   return (head);
679 }
680
681 static const char *uncomment_timezone (char *buf, size_t buflen, const char *tz)
682 {
683   char *p;
684   size_t len;
685
686   if (*tz != '(')
687     return tz; /* no need to do anything */
688   tz++;
689   SKIPWS (tz);
690   if ((p = strpbrk (tz, " )")) == NULL)
691     return tz;
692   len = p - tz;
693   if (len > buflen - 1)
694     len = buflen - 1;
695   memcpy (buf, tz, len);
696   buf[len] = 0;
697   return buf;
698 }
699
700 static struct tz_t
701 {
702   char tzname[5];
703   unsigned char zhours;
704   unsigned char zminutes;
705   unsigned char zoccident; /* west of UTC? */
706 }
707 TimeZones[] =
708 {
709   { "aat",   1,  0, 1 }, /* Atlantic Africa Time */
710   { "adt",   4,  0, 0 }, /* Arabia DST */
711   { "ast",   3,  0, 0 }, /* Arabia */
712 /*{ "ast",   4,  0, 1 },*/ /* Atlantic */
713   { "bst",   1,  0, 0 }, /* British DST */
714   { "cat",   1,  0, 0 }, /* Central Africa */
715   { "cdt",   5,  0, 1 },
716   { "cest",  2,  0, 0 }, /* Central Europe DST */
717   { "cet",   1,  0, 0 }, /* Central Europe */
718   { "cst",   6,  0, 1 },
719 /*{ "cst",   8,  0, 0 },*/ /* China */
720 /*{ "cst",   9, 30, 0 },*/ /* Australian Central Standard Time */
721   { "eat",   3,  0, 0 }, /* East Africa */
722   { "edt",   4,  0, 1 },
723   { "eest",  3,  0, 0 }, /* Eastern Europe DST */
724   { "eet",   2,  0, 0 }, /* Eastern Europe */
725   { "egst",  0,  0, 0 }, /* Eastern Greenland DST */
726   { "egt",   1,  0, 1 }, /* Eastern Greenland */
727   { "est",   5,  0, 1 },
728   { "gmt",   0,  0, 0 },
729   { "gst",   4,  0, 0 }, /* Presian Gulf */
730   { "hkt",   8,  0, 0 }, /* Hong Kong */
731   { "ict",   7,  0, 0 }, /* Indochina */
732   { "idt",   3,  0, 0 }, /* Israel DST */
733   { "ist",   2,  0, 0 }, /* Israel */
734 /*{ "ist",   5, 30, 0 },*/ /* India */
735   { "jst",   9,  0, 0 }, /* Japan */
736   { "kst",   9,  0, 0 }, /* Korea */
737   { "mdt",   6,  0, 1 },
738   { "met",   1,  0, 0 }, /* this is now officially CET */
739   { "msd",   4,  0, 0 }, /* Moscow DST */
740   { "msk",   3,  0, 0 }, /* Moscow */
741   { "mst",   7,  0, 1 },
742   { "nzdt", 13,  0, 0 }, /* New Zealand DST */
743   { "nzst", 12,  0, 0 }, /* New Zealand */
744   { "pdt",   7,  0, 1 },
745   { "pst",   8,  0, 1 },
746   { "sat",   2,  0, 0 }, /* South Africa */
747   { "smt",   4,  0, 0 }, /* Seychelles */
748   { "sst",  11,  0, 1 }, /* Samoa */
749 /*{ "sst",   8,  0, 0 },*/ /* Singapore */
750   { "utc",   0,  0, 0 },
751   { "wat",   0,  0, 0 }, /* West Africa */
752   { "west",  1,  0, 0 }, /* Western Europe DST */
753   { "wet",   0,  0, 0 }, /* Western Europe */
754   { "wgst",  2,  0, 1 }, /* Western Greenland DST */
755   { "wgt",   3,  0, 1 }, /* Western Greenland */
756   { "wst",   8,  0, 0 }, /* Western Australia */
757 };
758
759 /* parses a date string in RFC822 format:
760  *
761  * Date: [ weekday , ] day-of-month month year hour:minute:second timezone
762  *
763  * This routine assumes that `h' has been initialized to 0.  the `timezone'
764  * field is optional, defaulting to +0000 if missing.
765  */
766 time_t mutt_parse_date (const char *s, HEADER *h)
767 {
768   int count = 0;
769   char *t;
770   int hour, min, sec;
771   struct tm tm;
772   int i;
773   int tz_offset = 0;
774   int zhours = 0;
775   int zminutes = 0;
776   int zoccident = 0;
777   const char *ptz;
778   char tzstr[SHORT_STRING];
779   char scratch[SHORT_STRING];
780
781   /* Don't modify our argument. Fixed-size buffer is ok here since
782    * the date format imposes a natural limit. 
783    */
784
785   strfcpy (scratch, s, sizeof (scratch));
786   
787   /* kill the day of the week, if it exists. */
788   if ((t = strchr (scratch, ',')))
789     t++;
790   else
791     t = scratch;
792   SKIPWS (t);
793
794   memset (&tm, 0, sizeof (tm));
795
796   while ((t = strtok (t, " \t")) != NULL)
797   {
798     switch (count)
799     {
800       case 0: /* day of the month */
801         if (!isdigit ((unsigned char) *t))
802           return (-1);
803         tm.tm_mday = atoi (t);
804         if (tm.tm_mday > 31)
805           return (-1);
806         break;
807
808       case 1: /* month of the year */
809         if ((i = mutt_check_month (t)) < 0)
810           return (-1);
811         tm.tm_mon = i;
812         break;
813
814       case 2: /* year */
815         tm.tm_year = atoi (t);
816         if (tm.tm_year < 50)
817           tm.tm_year += 100;
818         else if (tm.tm_year >= 1900)
819           tm.tm_year -= 1900;
820         break;
821
822       case 3: /* time of day */
823         if (sscanf (t, "%d:%d:%d", &hour, &min, &sec) == 3)
824           ;
825         else if (sscanf (t, "%d:%d", &hour, &min) == 2)
826           sec = 0;
827         else
828         {
829           dprint(1, (debugfile, "parse_date: could not process time format: %s\n", t));
830           return(-1);
831         }
832         tm.tm_hour = hour;
833         tm.tm_min = min;
834         tm.tm_sec = sec;
835         break;
836
837       case 4: /* timezone */
838         /* sometimes we see things like (MST) or (-0700) so attempt to
839          * compensate by uncommenting the string if non-RFC822 compliant
840          */
841         ptz = uncomment_timezone (tzstr, sizeof (tzstr), t);
842
843         if (*ptz == '+' || *ptz == '-')
844         {
845           if (ptz[1] && ptz[2] && ptz[3] && ptz[4]
846               && isdigit ((unsigned char) ptz[1]) && isdigit ((unsigned char) ptz[2])
847               && isdigit ((unsigned char) ptz[3]) && isdigit ((unsigned char) ptz[4]))
848           {
849             zhours = (ptz[1] - '0') * 10 + (ptz[2] - '0');
850             zminutes = (ptz[3] - '0') * 10 + (ptz[4] - '0');
851
852             if (ptz[0] == '-')
853               zoccident = 1;
854           }
855         }
856         else
857         {
858           struct tz_t *tz;
859
860           tz = bsearch (ptz, TimeZones, sizeof TimeZones/sizeof (struct tz_t),
861                         sizeof (struct tz_t),
862                         (int (*)(const void *, const void *)) ascii_strcasecmp
863                         /* This is safe to do: A pointer to a struct equals
864                          * a pointer to its first element*/);
865
866           if (tz)
867           {
868             zhours = tz->zhours;
869             zminutes = tz->zminutes;
870             zoccident = tz->zoccident;
871           }
872
873           /* ad hoc support for the European MET (now officially CET) TZ */
874           if (ascii_strcasecmp (t, "MET") == 0)
875           {
876             if ((t = strtok (NULL, " \t")) != NULL)
877             {
878               if (!ascii_strcasecmp (t, "DST"))
879                 zhours++;
880             }
881           }
882         }
883         tz_offset = zhours * 3600 + zminutes * 60;
884         if (!zoccident)
885           tz_offset = -tz_offset;
886         break;
887     }
888     count++;
889     t = 0;
890   }
891
892   if (count < 4) /* don't check for missing timezone */
893   {
894     dprint(1,(debugfile, "parse_date(): error parsing date format, using received time\n"));
895     return (-1);
896   }
897
898   if (h)
899   {
900     h->zhours = zhours;
901     h->zminutes = zminutes;
902     h->zoccident = zoccident;
903   }
904
905   return (mutt_mktime (&tm, 0) + tz_offset);
906 }
907
908 /* extract the first substring that looks like a message-id */
909 static char *extract_message_id (const char *s)
910 {
911   const char *p;
912   char *r;
913   size_t l;
914
915   if ((s = strchr (s, '<')) == NULL || (p = strchr (s, '>')) == NULL)
916     return (NULL);
917   l = (size_t)(p - s) + 1;
918   r = safe_malloc (l + 1);
919   memcpy (r, s, l);
920   r[l] = 0;
921   return (r);
922 }
923
924 void mutt_parse_mime_message (CONTEXT *ctx, HEADER *cur)
925 {
926   MESSAGE *msg;
927
928   if (cur->content->type != TYPEMESSAGE && cur->content->type != TYPEMULTIPART)
929     return; /* nothing to do */
930
931   if (cur->content->parts)
932     return; /* The message was parsed earlier. */
933
934   if ((msg = mx_open_message (ctx, cur->msgno)))
935   {
936     mutt_parse_part (msg->fp, cur->content);
937
938     if (WithCrypto)
939       cur->security = crypt_query (cur->content);
940
941     mx_close_message (&msg);
942   }
943 }
944
945 int mutt_parse_rfc822_line (ENVELOPE *e, HEADER *hdr, char *line, char *p, short user_hdrs, short weed,
946                             short do_2047, LIST **lastp)
947 {
948   int matched = 0;
949   LIST *last = NULL;
950   
951   if (lastp)
952     last = *lastp;
953   
954   switch (ascii_tolower (line[0]))
955   {
956     case 'a':
957     if (ascii_strcasecmp (line+1, "pparently-to") == 0)
958     {
959       e->to = rfc822_parse_adrlist (e->to, p);
960       matched = 1;
961     }
962     else if (ascii_strcasecmp (line+1, "pparently-from") == 0)
963     {
964       e->from = rfc822_parse_adrlist (e->from, p);
965       matched = 1;
966     }
967     break;
968     
969     case 'b':
970     if (ascii_strcasecmp (line+1, "cc") == 0)
971     {
972       e->bcc = rfc822_parse_adrlist (e->bcc, p);
973       matched = 1;
974     }
975     break;
976     
977     case 'c':
978     if (ascii_strcasecmp (line+1, "c") == 0)
979     {
980       e->cc = rfc822_parse_adrlist (e->cc, p);
981       matched = 1;
982     }
983     else if (ascii_strncasecmp (line + 1, "ontent-", 7) == 0)
984     {
985       if (ascii_strcasecmp (line+8, "type") == 0)
986       {
987         if (hdr)
988           mutt_parse_content_type (p, hdr->content);
989         matched = 1;
990       }
991       else if (ascii_strcasecmp (line+8, "transfer-encoding") == 0)
992       {
993         if (hdr)
994           hdr->content->encoding = mutt_check_encoding (p);
995         matched = 1;
996       }
997       else if (ascii_strcasecmp (line+8, "length") == 0)
998       {
999         if (hdr)
1000         {
1001           if ((hdr->content->length = atoi (p)) < 0)
1002             hdr->content->length = -1;
1003         }
1004         matched = 1;
1005       }
1006       else if (ascii_strcasecmp (line+8, "description") == 0)
1007       {
1008         if (hdr)
1009         {
1010           mutt_str_replace (&hdr->content->description, p);
1011           rfc2047_decode (&hdr->content->description);
1012         }
1013         matched = 1;
1014       }
1015       else if (ascii_strcasecmp (line+8, "disposition") == 0)
1016       {
1017         if (hdr)
1018           parse_content_disposition (p, hdr->content);
1019         matched = 1;
1020       }
1021     }
1022     break;
1023     
1024     case 'd':
1025     if (!ascii_strcasecmp ("ate", line + 1))
1026     {
1027       mutt_str_replace (&e->date, p);
1028       if (hdr)
1029         hdr->date_sent = mutt_parse_date (p, hdr);
1030       matched = 1;
1031     }
1032     break;
1033     
1034     case 'e':
1035     if (!ascii_strcasecmp ("xpires", line + 1) &&
1036         hdr && mutt_parse_date (p, NULL) < time (NULL))
1037       hdr->expired = 1;
1038     break;
1039     
1040     case 'f':
1041     if (!ascii_strcasecmp ("rom", line + 1))
1042     {
1043       e->from = rfc822_parse_adrlist (e->from, p);
1044       matched = 1;
1045     }
1046 #ifdef USE_NNTP
1047     else if (!mutt_strcasecmp (line+1, "ollowup-to"))
1048     {
1049       if (!e->followup_to)
1050       {
1051         mutt_remove_trailing_ws (p);
1052         e->followup_to = safe_strdup (mutt_skip_whitespace (p));
1053       }
1054       matched = 1;
1055     }
1056 #endif
1057     break;
1058     
1059     case 'i':
1060     if (!ascii_strcasecmp (line+1, "n-reply-to"))
1061     {
1062       mutt_free_list (&e->in_reply_to);
1063       e->in_reply_to = mutt_parse_references (p, 1);
1064       matched = 1;
1065     }
1066     break;
1067     
1068     case 'l':
1069     if (!ascii_strcasecmp (line + 1, "ines"))
1070     {
1071       if (hdr)
1072       {
1073         hdr->lines = atoi (p);
1074
1075         /* 
1076          * HACK - mutt has, for a very short time, produced negative
1077          * Lines header values.  Ignore them. 
1078          */
1079         if (hdr->lines < 0)
1080           hdr->lines = 0;
1081       }
1082
1083       matched = 1;
1084     }
1085     else if (!ascii_strcasecmp (line + 1, "ist-Post"))
1086     {
1087       /* RFC 2369.  FIXME: We should ignore whitespace, but don't. */
1088       if (strncmp (p, "NO", 2))
1089       {
1090         char *beg, *end;
1091         for (beg = strchr (p, '<'); beg; beg = strchr (end, ','))
1092         {
1093           ++beg;
1094           if (!(end = strchr (beg, '>')))
1095             break;
1096           
1097           /* Take the first mailto URL */
1098           if (url_check_scheme (beg) == U_MAILTO)
1099           {
1100             FREE (&e->list_post);
1101             e->list_post = mutt_substrdup (beg, end);
1102             break;
1103           }
1104         }
1105       }
1106       matched = 1;
1107     }
1108     break;
1109     
1110     case 'm':
1111     if (!ascii_strcasecmp (line + 1, "ime-version"))
1112     {
1113       if (hdr)
1114         hdr->mime = 1;
1115       matched = 1;
1116     }
1117     else if (!ascii_strcasecmp (line + 1, "essage-id"))
1118     {
1119       /* We add a new "Message-Id:" when building a message */
1120       FREE (&e->message_id);
1121       e->message_id = extract_message_id (p);
1122       matched = 1;
1123     }
1124     else if (!ascii_strncasecmp (line + 1, "ail-", 4))
1125     {
1126       if (!ascii_strcasecmp (line + 5, "reply-to"))
1127       {
1128         /* override the Reply-To: field */
1129         rfc822_free_address (&e->reply_to);
1130         e->reply_to = rfc822_parse_adrlist (e->reply_to, p);
1131         matched = 1;
1132       }
1133       else if (!ascii_strcasecmp (line + 5, "followup-to"))
1134       {
1135         e->mail_followup_to = rfc822_parse_adrlist (e->mail_followup_to, p);
1136         matched = 1;
1137       }
1138     }
1139     break;
1140     
1141 #ifdef USE_NNTP
1142     case 'n':
1143     if (!mutt_strcasecmp (line + 1, "ewsgroups"))
1144     {
1145       FREE (&e->newsgroups);
1146       mutt_remove_trailing_ws (p);
1147       e->newsgroups = safe_strdup (mutt_skip_whitespace (p));
1148       matched = 1;
1149     }
1150     break;
1151 #endif
1152
1153     case 'o':
1154     /* field `Organization:' saves only for pager! */
1155     if (!mutt_strcasecmp (line + 1, "rganization"))
1156     {
1157       if (!e->organization && mutt_strcasecmp (p, "unknown"))
1158         e->organization = safe_strdup (p);
1159     }
1160     break;
1161
1162     case 'r':
1163     if (!ascii_strcasecmp (line + 1, "eferences"))
1164     {
1165       mutt_free_list (&e->references);
1166       e->references = mutt_parse_references (p, 0);
1167       matched = 1;
1168     }
1169     else if (!ascii_strcasecmp (line + 1, "eply-to"))
1170     {
1171       e->reply_to = rfc822_parse_adrlist (e->reply_to, p);
1172       matched = 1;
1173     }
1174     else if (!ascii_strcasecmp (line + 1, "eturn-path"))
1175     {
1176       e->return_path = rfc822_parse_adrlist (e->return_path, p);
1177       matched = 1;
1178     }
1179     else if (!ascii_strcasecmp (line + 1, "eceived"))
1180     {
1181       if (hdr && !hdr->received)
1182       {
1183         char *d = strchr (p, ';');
1184         
1185         if (d)
1186           hdr->received = mutt_parse_date (d + 1, NULL);
1187       }
1188     }
1189     break;
1190     
1191     case 's':
1192     if (!ascii_strcasecmp (line + 1, "ubject"))
1193     {
1194       if (!e->subject)
1195         e->subject = safe_strdup (p);
1196       matched = 1;
1197     }
1198     else if (!ascii_strcasecmp (line + 1, "ender"))
1199     {
1200       e->sender = rfc822_parse_adrlist (e->sender, p);
1201       matched = 1;
1202     }
1203     else if (!ascii_strcasecmp (line + 1, "tatus"))
1204     {
1205       if (hdr)
1206       {
1207         while (*p)
1208         {
1209           switch(*p)
1210           {
1211             case 'r':
1212             hdr->replied = 1;
1213             break;
1214             case 'O':
1215               hdr->old = 1;
1216             break;
1217             case 'R':
1218             hdr->read = 1;
1219             break;
1220           }
1221           p++;
1222         }
1223       }
1224       matched = 1;
1225     }
1226     else if ((!ascii_strcasecmp ("upersedes", line + 1) ||
1227               !ascii_strcasecmp ("upercedes", line + 1)) && hdr)
1228       e->supersedes = safe_strdup (p);
1229     break;
1230     
1231     case 't':
1232     if (ascii_strcasecmp (line+1, "o") == 0)
1233     {
1234       e->to = rfc822_parse_adrlist (e->to, p);
1235       matched = 1;
1236     }
1237     break;
1238     
1239     case 'x':
1240     if (ascii_strcasecmp (line+1, "-status") == 0)
1241     {
1242       if (hdr)
1243       {
1244         while (*p)
1245         {
1246           switch (*p)
1247           {
1248             case 'A':
1249             hdr->replied = 1;
1250             break;
1251             case 'D':
1252             hdr->deleted = 1;
1253             break;
1254             case 'F':
1255             hdr->flagged = 1;
1256             break;
1257             default:
1258             break;
1259           }
1260           p++;
1261         }
1262       }
1263       matched = 1;
1264     }
1265     else if (ascii_strcasecmp (line+1, "-label") == 0)
1266     {
1267       e->x_label = safe_strdup(p);
1268       matched = 1;
1269     }
1270 #ifdef USE_NNTP
1271     else if (!mutt_strcasecmp (line + 1, "-comment-to"))
1272     {
1273       if (!e->x_comment_to)
1274         e->x_comment_to = safe_strdup (p);
1275       matched = 1;
1276     }
1277     else if (!mutt_strcasecmp (line + 1, "ref"))
1278     {
1279       if (!e->xref)
1280         e->xref = safe_strdup (p);
1281       matched = 1;
1282     }
1283 #endif
1284     
1285     default:
1286     break;
1287   }
1288   
1289   /* Keep track of the user-defined headers */
1290   if (!matched && user_hdrs)
1291   {
1292     /* restore the original line */
1293     line[strlen (line)] = ':';
1294     
1295     if (weed && option (OPTWEED) && mutt_matches_ignore (line, Ignore)
1296         && !mutt_matches_ignore (line, UnIgnore))
1297       goto done;
1298
1299     if (last)
1300     {
1301       last->next = mutt_new_list ();
1302       last = last->next;
1303     }
1304     else
1305       last = e->userhdrs = mutt_new_list ();
1306     last->data = safe_strdup (line);
1307     if (do_2047)
1308       rfc2047_decode (&last->data);
1309   }
1310
1311   done:
1312   
1313   *lastp = last;
1314   return matched;
1315 }
1316   
1317   
1318 /* mutt_read_rfc822_header() -- parses a RFC822 header
1319  *
1320  * Args:
1321  *
1322  * f            stream to read from
1323  *
1324  * hdr          header structure of current message (optional).
1325  * 
1326  * user_hdrs    If set, store user headers.  Used for recall-message and
1327  *              postpone modes.
1328  * 
1329  * weed         If this parameter is set and the user has activated the
1330  *              $weed option, honor the header weed list for user headers.
1331  *              Used for recall-message.
1332  * 
1333  * Returns:     newly allocated envelope structure.  You should free it by
1334  *              mutt_free_envelope() when envelope stay unneeded.
1335  */
1336 ENVELOPE *mutt_read_rfc822_header (FILE *f, HEADER *hdr, short user_hdrs,
1337                                    short weed)
1338 {
1339   ENVELOPE *e = mutt_new_envelope();
1340   LIST *last = NULL;
1341   char *line = safe_malloc (LONG_STRING);
1342   char *p;
1343   long loc;
1344   int matched;
1345   size_t linelen = LONG_STRING;
1346   char buf[LONG_STRING+1];
1347
1348   if (hdr)
1349   {
1350     if (hdr->content == NULL)
1351     {
1352       hdr->content = mutt_new_body ();
1353
1354       /* set the defaults from RFC1521 */
1355       hdr->content->type        = TYPETEXT;
1356       hdr->content->subtype     = safe_strdup ("plain");
1357       hdr->content->encoding    = ENC7BIT;
1358       hdr->content->length      = -1;
1359
1360       /* RFC 2183 says this is arbitrary */
1361       hdr->content->disposition = DISPINLINE;
1362     }
1363   }
1364
1365   while ((loc = ftell (f)),
1366           *(line = read_rfc822_line (f, line, &linelen)) != 0)
1367   {
1368     matched = 0;
1369
1370     if ((p = strpbrk (line, ": \t")) == NULL || *p != ':')
1371     {
1372       char return_path[LONG_STRING];
1373       time_t t;
1374
1375       /* some bogus MTAs will quote the original "From " line */
1376       if (mutt_strncmp (">From ", line, 6) == 0)
1377         continue; /* just ignore */
1378       else if (is_from (line, return_path, sizeof (return_path), &t))
1379       {
1380         /* MH somtimes has the From_ line in the middle of the header! */
1381         if (hdr && !hdr->received)
1382           hdr->received = t - mutt_local_tz (t);
1383         continue;
1384       }
1385
1386       fseek (f, loc, 0);
1387       break; /* end of header */
1388     }
1389
1390     *buf = '\0';
1391
1392     if (mutt_match_spam_list(line, SpamList, buf, sizeof(buf)))
1393     {
1394       if (!mutt_match_rx_list(line, NoSpamList))
1395       {
1396
1397         /* if spam tag already exists, figure out how to amend it */
1398         if (e->spam && *buf)
1399         {
1400           /* If SpamSep defined, append with separator */
1401           if (SpamSep)
1402           {
1403             mutt_buffer_addstr(e->spam, SpamSep);
1404             mutt_buffer_addstr(e->spam, buf);
1405           }
1406
1407           /* else overwrite */
1408           else
1409           {
1410             e->spam->dptr = e->spam->data;
1411             *e->spam->dptr = '\0';
1412             mutt_buffer_addstr(e->spam, buf);
1413           }
1414         }
1415
1416         /* spam tag is new, and match expr is non-empty; copy */
1417         else if (!e->spam && *buf)
1418         {
1419           e->spam = mutt_buffer_from(NULL, buf);
1420         }
1421
1422         /* match expr is empty; plug in null string if no existing tag */
1423         else if (!e->spam)
1424         {
1425           e->spam = mutt_buffer_from(NULL, "");
1426         }
1427
1428         if (e->spam && e->spam->data)
1429           dprint(5, (debugfile, "p822: spam = %s\n", e->spam->data));
1430       }
1431     }
1432
1433     *p = 0;
1434     p++;
1435     SKIPWS (p);
1436     if (!*p)
1437       continue; /* skip empty header fields */
1438
1439     matched = mutt_parse_rfc822_line (e, hdr, line, p, user_hdrs, weed, 1, &last);
1440     
1441   }
1442
1443   FREE (&line);
1444
1445   if (hdr)
1446   {
1447     hdr->content->hdr_offset = hdr->offset;
1448     hdr->content->offset = ftell (f);
1449
1450     /* do RFC2047 decoding */
1451     rfc2047_decode_adrlist (e->from);
1452     rfc2047_decode_adrlist (e->to);
1453     rfc2047_decode_adrlist (e->cc);
1454     rfc2047_decode_adrlist (e->reply_to);
1455     rfc2047_decode_adrlist (e->mail_followup_to);
1456     rfc2047_decode_adrlist (e->return_path);
1457     rfc2047_decode_adrlist (e->sender);
1458
1459     if (e->subject)
1460     {
1461       regmatch_t pmatch[1];
1462
1463       rfc2047_decode (&e->subject);
1464
1465       if (regexec (ReplyRegexp.rx, e->subject, 1, pmatch, 0) == 0)
1466         e->real_subj = e->subject + pmatch[0].rm_eo;
1467       else
1468         e->real_subj = e->subject;
1469     }
1470
1471     /* check for missing or invalid date */
1472     if (hdr->date_sent <= 0)
1473     {
1474       dprint(1,(debugfile,"read_rfc822_header(): no date found, using received time from msg separator\n"));
1475       hdr->date_sent = hdr->received;
1476     }
1477   }
1478
1479   return (e);
1480 }
1481
1482 ADDRESS *mutt_parse_adrlist (ADDRESS *p, const char *s)
1483 {
1484   const char *q;
1485
1486   /* check for a simple whitespace separated list of addresses */
1487   if ((q = strpbrk (s, "\"<>():;,\\")) == NULL)
1488   {
1489     char tmp[HUGE_STRING];
1490     char *r;
1491
1492     strfcpy (tmp, s, sizeof (tmp));
1493     r = tmp;
1494     while ((r = strtok (r, " \t")) != NULL)
1495     {
1496       p = rfc822_parse_adrlist (p, r);
1497       r = NULL;
1498     }
1499   }
1500   else
1501     p = rfc822_parse_adrlist (p, s);
1502   
1503   return p;
1504 }