+static char *
+charset_from_mime_type (const char *mime_type)
+{
+ const char *charset;
+ struct string s;
+ const char *p;
+
+ if (mime_type == NULL)
+ return NULL;
+
+ charset = c_strcasestr (mime_type, "charset=");
+ if (charset == NULL)
+ return NULL;
+
+ ds_init_empty (&s);
+ p = charset + 8;
+ if (*p == '"')
+ {
+ /* Parse a "quoted-string" as defined by RFC 822. */
+ for (p++; *p != '\0' && *p != '"'; p++)
+ {
+ if (*p != '\\')
+ ds_put_byte (&s, *p);
+ else if (*++p != '\0')
+ ds_put_byte (&s, *p);
+ }
+ }
+ else
+ {
+ /* Parse a "token" as defined by RFC 2045. */
+ while (*p > 32 && *p < 127 && strchr ("()<>@,;:\\\"/[]?=", *p) == NULL)
+ ds_put_byte (&s, *p++);
+ }
+ if (!ds_is_empty (&s))
+ return ds_steal_cstr (&s);
+
+ ds_destroy (&s);
+ return NULL;
+}
+