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