always build imap as well.
[apps/madmutt.git] / parse.c
diff --git a/parse.c b/parse.c
index e074911..cd78866 100644 (file)
--- a/parse.c
+++ b/parse.c
 # include "config.h"
 #endif
 
+#include <lib-lib/mem.h>
+#include <lib-lib/str.h>
+#include <lib-lib/ascii.h>
+#include <lib-lib/macros.h>
+#include <lib-lib/buffer.h>
+
+#include <lib-mime/mime.h>
+
 #include "mutt.h"
+#include "enter.h"
+#include "recvattach.h"
 #include "mx.h"
-#include "mime.h"
-#include "rfc2047.h"
-#include "rfc2231.h"
 #include "mutt_crypt.h"
 #include "url.h"
 
-#include "lib/mem.h"
-#include "lib/intl.h"
-#include "lib/str.h"
 #include "lib/rx.h"
+#include "lib/debug.h"
 
 #include <string.h>
 #include <ctype.h>
  * lines.  ``line'' must point to a dynamically allocated string; it is
  * increased if more space is required to fit the whole line.
  */
-static char *read_rfc822_line (FILE * f, char *line, size_t * linelen)
+char *mutt_read_rfc822_line (FILE * f, char *line, size_t * linelen)
 {
   char *buf = line;
   char ch;
   size_t offset = 0;
 
-  FOREVER {
+  for (;;) {
     if (fgets (buf, *linelen - offset, f) == NULL ||    /* end of file or */
         (ISSPACE (*line) && !offset)) { /* end of headers */
       *line = 0;
       return (line);
     }
 
-    buf += safe_strlen (buf) - 1;
+    buf += m_strlen(buf) - 1;
     if (*buf == '\n') {
       /* we did get a full line. remove trailing space */
       while (ISSPACE (*buf))
@@ -71,7 +76,7 @@ static char *read_rfc822_line (FILE * f, char *line, size_t * linelen)
     if (*linelen < offset + STRING) {
       /* grow the buffer */
       *linelen += STRING;
-      safe_realloc (&line, *linelen);
+      p_realloc(&line, *linelen);
       buf = line + offset;
     }
   }
@@ -95,19 +100,19 @@ LIST *mutt_parse_references (char *s, int in_reply_to)
     new = NULL;
 
     if (*s == '<') {
-      n = safe_strlen (s);
+      n = m_strlen(s);
       if (s[n - 1] != '>') {
         o = s;
         s = NULL;
         continue;
       }
 
-      new = safe_strdup (s);
+      new = m_strdup(s);
     }
     else if (o) {
-      m = safe_strlen (s);
+      m = m_strlen(s);
       if (s[m - 1] == '>') {
-        new = safe_malloc (sizeof (char) * (n + m + 1));
+        new = p_new(char, n + m + 1);
         strcpy (new, o);        /* __STRCPY_CHECKED__ */
         strcpy (new + n, s);    /* __STRCPY_CHECKED__ */
       }
@@ -121,9 +126,9 @@ LIST *mutt_parse_references (char *s, int in_reply_to)
        */
       if (!(at = strchr (new, '@')) || strchr (at + 1, '@')
           || (in_reply_to && at - new <= 8))
-        FREE (&new);
+        p_delete(&new);
       else {
-        t = (LIST *) safe_malloc (sizeof (LIST));
+        t = p_new(LIST, 1);
         t->data = new;
         t->next = lst;
         lst = t;
@@ -150,13 +155,8 @@ int mutt_check_encoding (const char *c)
     return (ENCQUOTEDPRINTABLE);
   else if (ascii_strncasecmp ("base64", c, sizeof ("base64") - 1) == 0)
     return (ENCBASE64);
-  else if (ascii_strncasecmp ("x-uuencode", c, sizeof ("x-uuencode") - 1) ==
-           0)
-    return (ENCUUENCODED);
-#ifdef SUN_ATTACHMENT
-  else if (ascii_strncasecmp ("uuencode", c, sizeof ("uuencode") - 1) == 0)
+  else if (ascii_strncasecmp ("x-uuencode", c, sizeof ("x-uuencode") - 1) == 0)
     return (ENCUUENCODED);
-#endif
   else
     return (ENCOTHER);
 }
@@ -168,12 +168,11 @@ static PARAMETER *parse_parameters (const char *s)
   const char *p;
   size_t i;
 
-  dprint (2, (debugfile, "parse_parameters: `%s'\n", s));
+  debug_print (2, ("`%s'\n", s));
 
   while (*s) {
     if ((p = strpbrk (s, "=;")) == NULL) {
-      dprint (1,
-              (debugfile, "parse_parameters: malformed parameter: %s\n", s));
+      debug_print (1, ("malformed parameter: %s\n", s));
       goto bail;
     }
 
@@ -183,16 +182,13 @@ static PARAMETER *parse_parameters (const char *s)
 
       new = mutt_new_parameter ();
 
-      new->attribute = safe_malloc (i + 1);
-      memcpy (new->attribute, s, i);
-      new->attribute[i] = 0;
+      new->attribute = p_dupstr(s, i);
 
       /* remove whitespace from the end of the attribute name */
       while (ISSPACE (new->attribute[--i]))
         new->attribute[i] = 0;
 
-      s = p + 1;                /* skip over the = */
-      SKIPWS (s);
+      s = vskipspaces(p + 1);     /* skip over the = */
 
       if (*s == '"') {
         int state_ascii = 1;
@@ -231,10 +227,9 @@ static PARAMETER *parse_parameters (const char *s)
         buffer[i] = 0;
       }
 
-      new->value = safe_strdup (buffer);
+      new->value = m_strdup(buffer);
 
-      dprint (2, (debugfile, "parse_parameter: `%s' = `%s'\n",
-                  new->attribute ? new->attribute : "",
+      debug_print (2, ("`%s' = `%s'\n", new->attribute ? new->attribute : "",
                   new->value ? new->value : ""));
 
       /* Add this parameter to the list */
@@ -246,9 +241,7 @@ static PARAMETER *parse_parameters (const char *s)
         head = cur = new;
     }
     else {
-      dprint (1,
-              (debugfile, "parse_parameters(): parameter with no value: %s\n",
-               s));
+      debug_print (1, ("parameter with no value: %s\n", s));
       s = p;
     }
 
@@ -257,10 +250,8 @@ static PARAMETER *parse_parameters (const char *s)
       break;                    /* no more parameters */
 
     do {
-      s++;
-
       /* Move past any leading whitespace */
-      SKIPWS (s);
+      s = vskipspaces(s + 1);
     }
     while (*s == ';');          /* skip empty parameters */
   }
@@ -277,10 +268,6 @@ int mutt_check_mime_type (const char *s)
     return TYPETEXT;
   else if (ascii_strcasecmp ("multipart", s) == 0)
     return TYPEMULTIPART;
-#ifdef SUN_ATTACHMENT
-  else if (ascii_strcasecmp ("x-sun-attachment", s) == 0)
-    return TYPEMULTIPART;
-#endif
   else if (ascii_strcasecmp ("application", s) == 0)
     return TYPEAPPLICATION;
   else if (ascii_strcasecmp ("message", s) == 0)
@@ -293,6 +280,10 @@ int mutt_check_mime_type (const char *s)
     return TYPEVIDEO;
   else if (ascii_strcasecmp ("model", s) == 0)
     return TYPEMODEL;
+  else if (ascii_strcasecmp ("*", s) == 0)
+    return TYPEANY;
+  else if (ascii_strcasecmp (".*", s) == 0)
+    return TYPEANY;
   else
     return TYPEOTHER;
 }
@@ -302,7 +293,7 @@ void mutt_parse_content_type (char *s, BODY * ct)
   char *pc;
   char *subtype;
 
-  FREE (&ct->subtype);
+  p_delete(&ct->subtype);
   mutt_free_parameter (&ct->parameter);
 
   /* First extract any existing parameters */
@@ -317,14 +308,7 @@ void mutt_parse_content_type (char *s, BODY * ct)
      * let that take precedence, and don't set it here */
     if ((pc = mutt_get_parameter ("name", ct->parameter)) != 0
         && !ct->filename)
-      ct->filename = safe_strdup (pc);
-
-#ifdef SUN_ATTACHMENT
-    /* this is deep and utter perversion */
-    if ((pc = mutt_get_parameter ("conversions", ct->parameter)) != 0)
-      ct->encoding = mutt_check_encoding (pc);
-#endif
-
+      ct->filename = m_strdup(pc);
   }
 
   /* Now get the subtype */
@@ -332,19 +316,14 @@ void mutt_parse_content_type (char *s, BODY * ct)
     *subtype++ = '\0';
     for (pc = subtype; *pc && !ISSPACE (*pc) && *pc != ';'; pc++);
     *pc = '\0';
-    ct->subtype = safe_strdup (subtype);
+    ct->subtype = m_strdup(subtype);
   }
 
   /* Finally, get the major type */
   ct->type = mutt_check_mime_type (s);
 
-#ifdef SUN_ATTACHMENT
-  if (ascii_strcasecmp ("x-sun-attachment", s) == 0)
-    ct->subtype = safe_strdup ("x-sun-attachment");
-#endif
-
   if (ct->type == TYPEOTHER) {
-    ct->xtype = safe_strdup (s);
+    ct->xtype = m_strdup(s);
   }
 
   if (ct->subtype == NULL) {
@@ -352,20 +331,20 @@ void mutt_parse_content_type (char *s, BODY * ct)
      * field, so we can attempt to convert the type to BODY here.
      */
     if (ct->type == TYPETEXT)
-      ct->subtype = safe_strdup ("plain");
+      ct->subtype = m_strdup("plain");
     else if (ct->type == TYPEAUDIO)
-      ct->subtype = safe_strdup ("basic");
+      ct->subtype = m_strdup("basic");
     else if (ct->type == TYPEMESSAGE)
-      ct->subtype = safe_strdup ("rfc822");
+      ct->subtype = m_strdup("rfc822");
     else if (ct->type == TYPEOTHER) {
       char buffer[SHORT_STRING];
 
       ct->type = TYPEAPPLICATION;
       snprintf (buffer, sizeof (buffer), "x-%s", s);
-      ct->subtype = safe_strdup (buffer);
+      ct->subtype = m_strdup(buffer);
     }
     else
-      ct->subtype = safe_strdup ("x-unknown");
+      ct->subtype = m_strdup("x-unknown");
   }
 
   /* Default character set for text types. */
@@ -392,14 +371,12 @@ static void parse_content_disposition (char *s, BODY * ct)
 
   /* Check to see if a default filename was given */
   if ((s = strchr (s, ';')) != NULL) {
-    s++;
-    SKIPWS (s);
-    if ((s =
-         mutt_get_parameter ("filename",
-                             (parms = parse_parameters (s)))) != 0)
-      str_replace (&ct->filename, s);
+    s = vskipspaces(s + 1);
+    if ((s = mutt_get_parameter("filename",
+                                (parms = parse_parameters (s)))) != 0)
+      m_strreplace(&ct->filename, s);
     if ((s = mutt_get_parameter ("name", parms)) != 0)
-      ct->form_name = safe_strdup (s);
+      ct->form_name = m_strdup(s);
     mutt_free_parameter (&parms);
   }
 }
@@ -415,32 +392,27 @@ BODY *mutt_read_mime_header (FILE * fp, int digest)
 {
   BODY *p = mutt_new_body ();
   char *c;
-  char *line = safe_malloc (LONG_STRING);
+  char *line = p_new(char, LONG_STRING);
   size_t linelen = LONG_STRING;
 
-  p->hdr_offset = ftell (fp);
+  p->hdr_offset = ftello (fp);
 
   p->encoding = ENC7BIT;        /* default from RFC1521 */
   p->type = digest ? TYPEMESSAGE : TYPETEXT;
   p->disposition = DISPINLINE;
 
-  while (*(line = read_rfc822_line (fp, line, &linelen)) != 0) {
+  while (*(line = mutt_read_rfc822_line (fp, line, &linelen)) != 0) {
     /* Find the value of the current header */
     if ((c = strchr (line, ':'))) {
-      *c = 0;
-      c++;
-      SKIPWS (c);
+      *c++ = 0;
+      c = vskipspaces(c);
       if (!*c) {
-        dprint (1,
-                (debugfile,
-                 "mutt_read_mime_header(): skipping empty header field: %s\n",
-                 line));
+        debug_print (1, ("skipping empty header field: %s\n", line));
         continue;
       }
     }
     else {
-      dprint (1,
-              (debugfile, "read_mime_header: bogus MIME header: %s\n", line));
+      debug_print (1, ("bogus MIME header: %s\n", line));
       break;
     }
 
@@ -452,32 +424,18 @@ BODY *mutt_read_mime_header (FILE * fp, int digest)
       else if (!ascii_strcasecmp ("disposition", line + 8))
         parse_content_disposition (c, p);
       else if (!ascii_strcasecmp ("description", line + 8)) {
-        str_replace (&p->description, c);
+        m_strreplace(&p->description, c);
         rfc2047_decode (&p->description);
       }
     }
-#ifdef SUN_ATTACHMENT
-    else if (!ascii_strncasecmp ("x-sun-", line, 6)) {
-      if (!ascii_strcasecmp ("data-type", line + 6))
-        mutt_parse_content_type (c, p);
-      else if (!ascii_strcasecmp ("encoding-info", line + 6))
-        p->encoding = mutt_check_encoding (c);
-      else if (!ascii_strcasecmp ("content-lines", line + 6))
-        mutt_set_parameter ("content-lines", c, &(p->parameter));
-      else if (!ascii_strcasecmp ("data-description", line + 6)) {
-        str_replace (&p->description, c);
-        rfc2047_decode (&p->description);
-      }
-    }
-#endif
   }
-  p->offset = ftell (fp);       /* Mark the start of the real data */
+  p->offset = ftello (fp);       /* Mark the start of the real data */
   if (p->type == TYPETEXT && !p->subtype)
-    p->subtype = safe_strdup ("plain");
+    p->subtype = m_strdup("plain");
   else if (p->type == TYPEMESSAGE && !p->subtype)
-    p->subtype = safe_strdup ("rfc822");
+    p->subtype = m_strdup("rfc822");
 
-  FREE (&line);
+  p_delete(&line);
 
   return (p);
 }
@@ -488,14 +446,8 @@ void mutt_parse_part (FILE * fp, BODY * b)
 
   switch (b->type) {
   case TYPEMULTIPART:
-#ifdef SUN_ATTACHMENT
-    if (!ascii_strcasecmp (b->subtype, "x-sun-attachment"))
-      bound = "--------";
-    else
-#endif
-      bound = mutt_get_parameter ("boundary", b->parameter);
-
-    fseek (fp, b->offset, SEEK_SET);
+    bound = mutt_get_parameter ("boundary", b->parameter);
+    fseeko (fp, b->offset, SEEK_SET);
     b->parts = mutt_parse_multipart (fp, bound,
                                      b->offset + b->length,
                                      ascii_strcasecmp ("digest",
@@ -504,7 +456,7 @@ void mutt_parse_part (FILE * fp, BODY * b)
 
   case TYPEMESSAGE:
     if (b->subtype) {
-      fseek (fp, b->offset, SEEK_SET);
+      fseeko (fp, b->offset, SEEK_SET);
       if (mutt_is_message_type (b->type, b->subtype))
         b->parts = mutt_parse_messageRFC822 (fp, b);
       else if (ascii_strcasecmp (b->subtype, "external-body") == 0)
@@ -521,7 +473,7 @@ void mutt_parse_part (FILE * fp, BODY * b)
   /* try to recover from parsing error */
   if (!b->parts) {
     b->type = TYPETEXT;
-    str_replace (&b->subtype, "plain");
+    m_strreplace(&b->subtype, "plain");
   }
 }
 
@@ -541,7 +493,7 @@ BODY *mutt_parse_messageRFC822 (FILE * fp, BODY * parent)
   BODY *msg;
 
   parent->hdr = mutt_new_header ();
-  parent->hdr->offset = ftell (fp);
+  parent->hdr->offset = ftello (fp);
   parent->hdr->env = mutt_read_rfc822_header (fp, parent->hdr, 0, 0);
   msg = parent->hdr->content;
 
@@ -571,12 +523,9 @@ BODY *mutt_parse_messageRFC822 (FILE * fp, BODY * parent)
  *     digest          1 if reading a multipart/digest, 0 otherwise
  */
 
-BODY *mutt_parse_multipart (FILE * fp, const char *boundary, long end_off,
+BODY *mutt_parse_multipart (FILE * fp, const char *boundary, off_t end_off,
                             int digest)
 {
-#ifdef SUN_ATTACHMENT
-  int lines;
-#endif
   int blen, len, crlf = 0;
   char buffer[LONG_STRING];
   BODY *head = 0, *last = 0, *new = 0;
@@ -589,19 +538,19 @@ BODY *mutt_parse_multipart (FILE * fp, const char *boundary, long end_off,
     return (NULL);
   }
 
-  blen = safe_strlen (boundary);
-  while (ftell (fp) < end_off && fgets (buffer, LONG_STRING, fp) != NULL) {
-    len = safe_strlen (buffer);
+  blen = m_strlen(boundary);
+  while (ftello (fp) < end_off && fgets (buffer, LONG_STRING, fp) != NULL) {
+    len = m_strlen(buffer);
 
     crlf = (len > 1 && buffer[len - 2] == '\r') ? 1 : 0;
 
     if (buffer[0] == '-' && buffer[1] == '-' &&
-        safe_strncmp (buffer + 2, boundary, blen) == 0) {
+        m_strncmp(buffer + 2, boundary, blen) == 0) {
       if (last) {
-        last->length = ftell (fp) - last->offset - len - 1 - crlf;
+        last->length = ftello (fp) - last->offset - len - 1 - crlf;
         if (last->parts && last->parts->length == 0)
           last->parts->length =
-            ftell (fp) - last->parts->offset - len - 1 - crlf;
+            ftello (fp) - last->parts->offset - len - 1 - crlf;
         /* if the body is empty, we can end up with a -1 length */
         if (last->length < 0)
           last->length = 0;
@@ -612,24 +561,13 @@ BODY *mutt_parse_multipart (FILE * fp, const char *boundary, long end_off,
         buffer[i] = 0;
 
       /* Check for the end boundary */
-      if (safe_strcmp (buffer + blen + 2, "--") == 0) {
+      if (m_strcmp(buffer + blen + 2, "--") == 0) {
         final = 1;
         break;                  /* done parsing */
       }
       else if (buffer[2 + blen] == 0) {
         new = mutt_read_mime_header (fp, digest);
 
-#ifdef SUN_ATTACHMENT
-        if (mutt_get_parameter ("content-lines", new->parameter)) {
-          for (lines =
-               atoi (mutt_get_parameter ("content-lines", new->parameter));
-               lines; lines--)
-            if (ftell (fp) >= end_off
-                || fgets (buffer, LONG_STRING, fp) == NULL)
-              break;
-        }
-#endif
-
         /*
          * Consistency checking - catch
          * bad attachment end boundaries
@@ -668,8 +606,7 @@ static const char *uncomment_timezone (char *buf, size_t buflen,
 
   if (*tz != '(')
     return tz;                  /* no need to do anything */
-  tz++;
-  SKIPWS (tz);
+  tz = vskipspaces(tz + 1);
   if ((p = strpbrk (tz, " )")) == NULL)
     return tz;
   len = p - tz;
@@ -793,19 +730,19 @@ time_t mutt_parse_date (const char *s, HEADER * h)
   char scratch[SHORT_STRING];
 
   /* Don't modify our argument. Fixed-size buffer is ok here since
-   * the date format imposes a natural limit. 
+   * the date format imposes a natural limit.
    */
 
-  strfcpy (scratch, s, sizeof (scratch));
+  m_strcpy(scratch, sizeof(scratch), s);
 
   /* kill the day of the week, if it exists. */
   if ((t = strchr (scratch, ',')))
     t++;
   else
     t = scratch;
-  SKIPWS (t);
+  t = vskipspaces(t);
 
-  memset (&tm, 0, sizeof (tm));
+  p_clear(&tm, 1);
 
   while ((t = strtok (t, " \t")) != NULL) {
     switch (count) {
@@ -836,9 +773,7 @@ time_t mutt_parse_date (const char *s, HEADER * h)
       else if (sscanf (t, "%d:%d", &hour, &min) == 2)
         sec = 0;
       else {
-        dprint (1,
-                (debugfile, "parse_date: could not process time format: %s\n",
-                 t));
+        debug_print (1, ("could not process time format: %s\n", t));
         return (-1);
       }
       tm.tm_hour = hour;
@@ -898,9 +833,7 @@ time_t mutt_parse_date (const char *s, HEADER * h)
   }
 
   if (count < 4) {              /* don't check for missing timezone */
-    dprint (1,
-            (debugfile,
-             "parse_date(): error parsing date format, using received time\n"));
+    debug_print (1, ("error parsing date format, using received time\n"));
     return (-1);
   }
 
@@ -914,40 +847,37 @@ time_t mutt_parse_date (const char *s, HEADER * h)
 }
 
 /* extract the first substring that looks like a message-id */
-static char *extract_message_id (const char *s)
+static char *extract_message_id(const char *s)
 {
-  const char *p;
-  char *r;
-  size_t l;
+    const char *p;
 
-  if ((s = strchr (s, '<')) == NULL || (p = strchr (s, '>')) == NULL)
-    return (NULL);
-  l = (size_t) (p - s) + 1;
-  r = safe_malloc (l + 1);
-  memcpy (r, s, l);
-  r[l] = 0;
-  return (r);
+    if ((s = strchr(s, '<')) == NULL || (p = strchr(s, '>')) == NULL)
+        return NULL;
+    return p_dupstr(s, (p - s) + 1);
 }
 
 void mutt_parse_mime_message (CONTEXT * ctx, HEADER * cur)
 {
   MESSAGE *msg;
+  int flags = 0;
 
-  if (cur->content->type != TYPEMESSAGE
-      && cur->content->type != TYPEMULTIPART)
-    return;                     /* nothing to do */
+  do {
+    if (cur->content->type != TYPEMESSAGE
+        && cur->content->type != TYPEMULTIPART)
+      break;                     /* nothing to do */
 
-  if (cur->content->parts)
-    return;                     /* The message was parsed earlier. */
+    if (cur->content->parts)
+      break;                     /* The message was parsed earlier. */
 
-  if ((msg = mx_open_message (ctx, cur->msgno))) {
-    mutt_parse_part (msg->fp, cur->content);
+    if ((msg = mx_open_message (ctx, cur->msgno))) {
+      mutt_parse_part (msg->fp, cur->content);
 
-    if (WithCrypto)
       cur->security = crypt_query (cur->content);
 
-    mx_close_message (&msg);
-  }
+      mx_close_message (&msg);
+    }
+  } while (0);
+  mutt_count_body_parts (cur, flags | M_PARTS_RECOUNT);
 }
 
 int mutt_parse_rfc822_line (ENVELOPE * e, HEADER * hdr, char *line, char *p,
@@ -1004,7 +934,7 @@ int mutt_parse_rfc822_line (ENVELOPE * e, HEADER * hdr, char *line, char *p,
       }
       else if (ascii_strcasecmp (line + 8, "description") == 0) {
         if (hdr) {
-          str_replace (&hdr->content->description, p);
+          m_strreplace(&hdr->content->description, p);
           rfc2047_decode (&hdr->content->description);
         }
         matched = 1;
@@ -1019,7 +949,7 @@ int mutt_parse_rfc822_line (ENVELOPE * e, HEADER * hdr, char *line, char *p,
 
   case 'd':
     if (!ascii_strcasecmp ("ate", line + 1)) {
-      str_replace (&e->date, p);
+      m_strreplace(&e->date, p);
       if (hdr)
         hdr->date_sent = mutt_parse_date (p, hdr);
       matched = 1;
@@ -1040,16 +970,16 @@ int mutt_parse_rfc822_line (ENVELOPE * e, HEADER * hdr, char *line, char *p,
        * and mark mail/(esp.) news article as your own. aaargh! this
        * bothered me for _years_ */
       if (!e->from) {
-        e->from = rfc822_new_address ();
-        e->from->personal = safe_strdup (line + 6);
+        e->from = address_new ();
+        e->from->personal = m_strdup(p);
       }
       matched = 1;
     }
 #ifdef USE_NNTP
-    else if (!safe_strcasecmp (line + 1, "ollowup-to")) {
+    else if (!m_strcasecmp(line + 1, "ollowup-to")) {
       if (!e->followup_to) {
-        mutt_remove_trailing_ws (p);
-        e->followup_to = safe_strdup (mutt_skip_whitespace (p));
+        m_strrtrim(p);
+        e->followup_to = m_strdup(skipspaces(p));
       }
       matched = 1;
     }
@@ -1069,9 +999,9 @@ int mutt_parse_rfc822_line (ENVELOPE * e, HEADER * hdr, char *line, char *p,
       if (hdr) {
         hdr->lines = atoi (p);
 
-        /* 
+        /*
          * HACK - mutt has, for a very short time, produced negative
-         * Lines header values.  Ignore them. 
+         * Lines header values.  Ignore them.
          */
         if (hdr->lines < 0)
           hdr->lines = 0;
@@ -1091,8 +1021,8 @@ int mutt_parse_rfc822_line (ENVELOPE * e, HEADER * hdr, char *line, char *p,
 
           /* Take the first mailto URL */
           if (url_check_scheme (beg) == U_MAILTO) {
-            FREE (&e->list_post);
-            e->list_post = str_substrdup (beg, end);
+            p_delete(&e->list_post);
+            e->list_post = p_dupstr(beg, end - beg);
             break;
           }
         }
@@ -1108,15 +1038,15 @@ int mutt_parse_rfc822_line (ENVELOPE * e, HEADER * hdr, char *line, char *p,
       matched = 1;
     }
     else if (!ascii_strcasecmp (line + 1, "essage-id")) {
-      /* We add a new "Message-Id:" when building a message */
-      FREE (&e->message_id);
+      /* We add a new "Message-ID:" when building a message */
+      p_delete(&e->message_id);
       e->message_id = extract_message_id (p);
       matched = 1;
     }
     else if (!ascii_strncasecmp (line + 1, "ail-", 4)) {
       if (!ascii_strcasecmp (line + 5, "reply-to")) {
         /* override the Reply-To: field */
-        rfc822_free_address (&e->reply_to);
+        address_delete (&e->reply_to);
         e->reply_to = rfc822_parse_adrlist (e->reply_to, p);
         matched = 1;
       }
@@ -1129,10 +1059,10 @@ int mutt_parse_rfc822_line (ENVELOPE * e, HEADER * hdr, char *line, char *p,
 
 #ifdef USE_NNTP
   case 'n':
-    if (!safe_strcasecmp (line + 1, "ewsgroups")) {
-      FREE (&e->newsgroups);
-      mutt_remove_trailing_ws (p);
-      e->newsgroups = safe_strdup (mutt_skip_whitespace (p));
+    if (!m_strcasecmp(line + 1, "ewsgroups")) {
+      p_delete(&e->newsgroups);
+      m_strrtrim(p);
+      e->newsgroups = m_strdup(skipspaces(p));
       matched = 1;
     }
     break;
@@ -1140,9 +1070,9 @@ int mutt_parse_rfc822_line (ENVELOPE * e, HEADER * hdr, char *line, char *p,
 
   case 'o':
     /* field `Organization:' saves only for pager! */
-    if (!safe_strcasecmp (line + 1, "rganization")) {
-      if (!e->organization && safe_strcasecmp (p, "unknown"))
-        e->organization = safe_strdup (p);
+    if (!m_strcasecmp(line + 1, "rganization")) {
+      if (!e->organization && m_strcasecmp(p, "unknown"))
+        e->organization = m_strdup(p);
     }
     break;
 
@@ -1173,7 +1103,7 @@ int mutt_parse_rfc822_line (ENVELOPE * e, HEADER * hdr, char *line, char *p,
   case 's':
     if (!ascii_strcasecmp (line + 1, "ubject")) {
       if (!e->subject)
-        e->subject = safe_strdup (p);
+        e->subject = m_strdup(p);
       matched = 1;
     }
     else if (!ascii_strcasecmp (line + 1, "ender")) {
@@ -1201,7 +1131,7 @@ int mutt_parse_rfc822_line (ENVELOPE * e, HEADER * hdr, char *line, char *p,
     }
     else if ((!ascii_strcasecmp ("upersedes", line + 1) ||
               !ascii_strcasecmp ("upercedes", line + 1)) && hdr)
-      e->supersedes = safe_strdup (p);
+      e->supersedes = m_strdup(p);
     break;
 
   case 't':
@@ -1234,18 +1164,18 @@ int mutt_parse_rfc822_line (ENVELOPE * e, HEADER * hdr, char *line, char *p,
       matched = 1;
     }
     else if (ascii_strcasecmp (line + 1, "-label") == 0) {
-      e->x_label = safe_strdup (p);
+      e->x_label = m_strdup(p);
       matched = 1;
     }
 #ifdef USE_NNTP
-    else if (!safe_strcasecmp (line + 1, "-comment-to")) {
+    else if (!m_strcasecmp(line + 1, "-comment-to")) {
       if (!e->x_comment_to)
-        e->x_comment_to = safe_strdup (p);
+        e->x_comment_to = m_strdup(p);
       matched = 1;
     }
-    else if (!safe_strcasecmp (line + 1, "ref")) {
+    else if (!m_strcasecmp(line + 1, "ref")) {
       if (!e->xref)
-        e->xref = safe_strdup (p);
+        e->xref = m_strdup(p);
       matched = 1;
     }
 #endif
@@ -1257,7 +1187,7 @@ int mutt_parse_rfc822_line (ENVELOPE * e, HEADER * hdr, char *line, char *p,
   /* Keep track of the user-defined headers */
   if (!matched && user_hdrs) {
     /* restore the original line */
-    line[safe_strlen (line)] = ':';
+    line[m_strlen(line)] = ':';
 
     if (weed && option (OPTWEED) && mutt_matches_ignore (line, Ignore)
         && !mutt_matches_ignore (line, UnIgnore))
@@ -1269,7 +1199,7 @@ int mutt_parse_rfc822_line (ENVELOPE * e, HEADER * hdr, char *line, char *p,
     }
     else
       last = e->userhdrs = mutt_new_list ();
-    last->data = safe_strdup (line);
+    last->data = m_strdup(line);
     if (do_2047)
       rfc2047_decode (&last->data);
   }
@@ -1288,14 +1218,14 @@ done:
  * f           stream to read from
  *
  * hdr         header structure of current message (optional).
- * 
+ *
  * user_hdrs   If set, store user headers.  Used for recall-message and
  *             postpone modes.
- * 
+ *
  * weed                If this parameter is set and the user has activated the
  *             $weed option, honor the header weed list for user headers.
  *             Used for recall-message.
- * 
+ *
  * Returns:     newly allocated envelope structure.  You should free it by
  *              mutt_free_envelope() when envelope stay unneeded.
  */
@@ -1304,9 +1234,9 @@ ENVELOPE *mutt_read_rfc822_header (FILE * f, HEADER * hdr, short user_hdrs,
 {
   ENVELOPE *e = mutt_new_envelope ();
   LIST *last = NULL;
-  char *line = safe_malloc (LONG_STRING);
+  char *line = p_new(char, LONG_STRING);
   char *p;
-  long loc;
+  off_t loc;
   int matched;
   size_t linelen = LONG_STRING;
   char buf[LONG_STRING + 1];
@@ -1317,7 +1247,7 @@ ENVELOPE *mutt_read_rfc822_header (FILE * f, HEADER * hdr, short user_hdrs,
 
       /* set the defaults from RFC1521 */
       hdr->content->type = TYPETEXT;
-      hdr->content->subtype = safe_strdup ("plain");
+      hdr->content->subtype = m_strdup("plain");
       hdr->content->encoding = ENC7BIT;
       hdr->content->length = -1;
 
@@ -1326,8 +1256,8 @@ ENVELOPE *mutt_read_rfc822_header (FILE * f, HEADER * hdr, short user_hdrs,
     }
   }
 
-  while ((loc = ftell (f)),
-         *(line = read_rfc822_line (f, line, &linelen)) != 0) {
+  while ((loc = ftello (f)),
+         *(line = mutt_read_rfc822_line (f, line, &linelen)) != 0) {
     matched = 0;
 
     if ((p = strpbrk (line, ": \t")) == NULL || *p != ':') {
@@ -1335,7 +1265,7 @@ ENVELOPE *mutt_read_rfc822_header (FILE * f, HEADER * hdr, short user_hdrs,
       time_t t;
 
       /* some bogus MTAs will quote the original "From " line */
-      if (safe_strncmp (">From ", line, 6) == 0)
+      if (m_strncmp(">From ", line, 6) == 0)
         continue;               /* just ignore */
       else if (is_from (line, return_path, sizeof (return_path), &t)) {
         /* MH somtimes has the From_ line in the middle of the header! */
@@ -1344,7 +1274,7 @@ ENVELOPE *mutt_read_rfc822_header (FILE * f, HEADER * hdr, short user_hdrs,
         continue;
       }
 
-      fseek (f, loc, 0);
+      fseeko (f, loc, 0);
       break;                    /* end of header */
     }
 
@@ -1380,13 +1310,12 @@ ENVELOPE *mutt_read_rfc822_header (FILE * f, HEADER * hdr, short user_hdrs,
         }
 
         if (e->spam && e->spam->data)
-          dprint (5, (debugfile, "p822: spam = %s\n", e->spam->data));
+          debug_print (5, ("spam = %s\n", e->spam->data));
       }
     }
 
-    *p = 0;
-    p++;
-    SKIPWS (p);
+    *p++ = 0;
+    p = vskipspaces(p);
     if (!*p)
       continue;                 /* skip empty header fields */
 
@@ -1395,38 +1324,16 @@ ENVELOPE *mutt_read_rfc822_header (FILE * f, HEADER * hdr, short user_hdrs,
 
   }
 
-  FREE (&line);
+  p_delete(&line);
 
   if (hdr) {
     hdr->content->hdr_offset = hdr->offset;
-    hdr->content->offset = ftell (f);
-
-    /* do RFC2047 decoding */
-    rfc2047_decode_adrlist (e->from);
-    rfc2047_decode_adrlist (e->to);
-    rfc2047_decode_adrlist (e->cc);
-    rfc2047_decode_adrlist (e->bcc);
-    rfc2047_decode_adrlist (e->reply_to);
-    rfc2047_decode_adrlist (e->mail_followup_to);
-    rfc2047_decode_adrlist (e->return_path);
-    rfc2047_decode_adrlist (e->sender);
-
-    if (e->subject) {
-      regmatch_t pmatch[1];
-
-      rfc2047_decode (&e->subject);
-
-      if (regexec (ReplyRegexp.rx, e->subject, 1, pmatch, 0) == 0)
-        e->real_subj = e->subject + pmatch[0].rm_eo;
-      else
-        e->real_subj = e->subject;
-    }
-
+    hdr->content->offset = ftello (f);
+    rfc2047_decode_envelope(e);
     /* check for missing or invalid date */
     if (hdr->date_sent <= 0) {
-      dprint (1,
-              (debugfile,
-               "read_rfc822_header(): no date found, using received time from msg separator\n"));
+      debug_print (1, ("no date found, using received "
+                       "time from msg separator\n"));
       hdr->date_sent = hdr->received;
     }
   }
@@ -1434,7 +1341,7 @@ ENVELOPE *mutt_read_rfc822_header (FILE * f, HEADER * hdr, short user_hdrs,
   return (e);
 }
 
-ADDRESS *mutt_parse_adrlist (ADDRESS * p, const char *s)
+address_t *mutt_parse_adrlist (address_t * p, const char *s)
 {
   const char *q;
 
@@ -1443,7 +1350,7 @@ ADDRESS *mutt_parse_adrlist (ADDRESS * p, const char *s)
     char tmp[HUGE_STRING];
     char *r;
 
-    strfcpy (tmp, s, sizeof (tmp));
+    m_strcpy(tmp, sizeof(tmp), s);
     r = tmp;
     while ((r = strtok (r, " \t")) != NULL) {
       p = rfc822_parse_adrlist (p, r);
@@ -1455,3 +1362,133 @@ ADDRESS *mutt_parse_adrlist (ADDRESS * p, const char *s)
 
   return p;
 }
+
+
+/* Compares mime types to the ok and except lists */
+int count_body_parts_check(LIST **checklist, BODY *b, int dflt) {
+  LIST *type;
+  ATTACH_MATCH *a;
+
+  /* If list is null, use default behavior. */
+  if (! *checklist) {
+    /*return dflt;*/
+    return 0;
+  }
+
+  for (type = *checklist; type; type = type->next) {
+    a = (ATTACH_MATCH *)type->data;
+    debug_print(5, ("cbpc: %s %d/%s ?? %s/%s [%d]... ",
+               dflt ? "[OK] " : "[EXCL] ",
+               b->type, b->subtype, a->major, a->minor, a->major_int));
+    if ((a->major_int == TYPEANY || a->major_int == b->type) &&
+        !regexec(&a->minor_rx, b->subtype, 0, NULL, 0)) {
+      debug_print(5, ("yes\n"));
+      return 1;
+    } else {
+      debug_print(5, ("no\n"));
+    }
+  }
+  return 0;
+}
+
+#define AT_COUNT(why) { shallcount = 1; }
+#define AT_NOCOUNT(why) { shallcount = 0; }
+
+int count_body_parts (BODY *body, int flags) {
+  int count = 0;
+  int shallcount, shallrecurse;
+  BODY *bp;
+
+  if (body == NULL)
+    return 0;
+
+  for (bp = body; bp != NULL; bp = bp->next) {
+    /* Initial disposition is to count and not to recurse this part. */
+    AT_COUNT("default");
+    shallrecurse = 0;
+
+    debug_print(5, ("bp: desc=\"%s\"; fn=\"%s\", type=\"%d/%s\"\n",
+               bp->description ? bp->description : ("none"),
+               bp->filename ? bp->filename :
+               bp->d_filename ? bp->d_filename : "(none)",
+               bp->type, bp->subtype ? bp->subtype : "*"));
+
+    if (bp->type == TYPEMESSAGE) {
+      shallrecurse = 1;
+
+      /* If it's an external body pointer, don't recurse it. */
+      if (!ascii_strcasecmp (bp->subtype, "external-body"))
+        shallrecurse = 0;
+
+      /* Don't count containers if they're top-level. */
+      if (flags & M_PARTS_TOPLEVEL)
+        AT_NOCOUNT("top-level message/*");
+    } else if (bp->type == TYPEMULTIPART) {
+      /* Always recurse multiparts, except multipart/alternative. */
+      shallrecurse = 1;
+      if (!m_strcasecmp(bp->subtype, "alternative"))
+        shallrecurse = 0;
+
+      /* Don't count containers if they're top-level. */
+      if (flags & M_PARTS_TOPLEVEL)
+        AT_NOCOUNT("top-level multipart");
+    }
+
+    if (bp->disposition == DISPINLINE &&
+        bp->type != TYPEMULTIPART && bp->type != TYPEMESSAGE && bp == body)
+      AT_NOCOUNT("ignore fundamental inlines");
+
+    /* If this body isn't scheduled for enumeration already, don't bother
+     * profiling it further. */
+
+    if (shallcount) {
+      /* Turn off shallcount if message type is not in ok list,
+       * or if it is in except list. Check is done separately for
+       * inlines vs. attachments.
+       */
+
+      if (bp->disposition == DISPATTACH) {
+        if (!count_body_parts_check(&AttachAllow, bp, 1))
+          AT_NOCOUNT("attach not allowed");
+        if (count_body_parts_check(&AttachExclude, bp, 0))
+          AT_NOCOUNT("attach excluded");
+      } else {
+        if (!count_body_parts_check(&InlineAllow, bp, 1))
+          AT_NOCOUNT("inline not allowed");
+        if (count_body_parts_check(&InlineExclude, bp, 0))
+          AT_NOCOUNT("excluded");
+      }
+    }
+
+    if (shallcount)
+      count++;
+    bp->attach_qualifies = shallcount ? 1 : 0;
+
+    debug_print(5, ("cbp: %p shallcount = %d\n", bp, shallcount));
+
+    if (shallrecurse) {
+      debug_print(5, ("cbp: %p pre count = %d\n", bp, count));
+      bp->attach_count = count_body_parts(bp->parts, flags & ~M_PARTS_TOPLEVEL);
+      count += bp->attach_count;
+      debug_print(5, ("cbp: %p post count = %d\n", bp, count));
+    }
+  }
+
+  debug_print(5, ("bp: return %d\n", count < 0 ? 0 : count));
+  return count < 0 ? 0 : count;
+}
+
+int mutt_count_body_parts (HEADER *hdr, int flags) {
+  if (!option (OPTCOUNTATTACH))
+    return (0);
+  if (hdr->attach_valid && !(flags & M_PARTS_RECOUNT))
+    return hdr->attach_total;
+
+  if (AttachAllow || AttachExclude || InlineAllow || InlineExclude)
+    hdr->attach_total = count_body_parts(hdr->content, flags | M_PARTS_TOPLEVEL);
+  else
+    hdr->attach_total = 0;
+
+  hdr->attach_valid = 1;
+  return hdr->attach_total;
+}