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