2006-10-12 [colin] 2.5.5cvs4
[claws.git] / src / procmime.c
index b89338b28a16de29b73b3766cdf6d76600b35b46..4314ec79c4fef1f517837c43ab320c7a837441d4 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
- * Copyright (C) 1999-2004 Hiroyuki Yamamoto & The Sylpheed-Claws Team
+ * Copyright (C) 1999-2006 Hiroyuki Yamamoto & The Sylpheed-Claws Team
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
@@ -14,7 +14,7 @@
  *
  * You should have received a copy of the GNU General Public License
  * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  */
 
 #ifdef HAVE_CONFIG_H
 
 #include <stdio.h>
 #include <glib.h>
+#include <glib/gi18n.h>
 #include <stdio.h>
 #include <string.h>
-#include <locale.h>
+#if HAVE_LOCALE_H
+#  include <locale.h>
+#endif
 #include <ctype.h>
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <unistd.h>
 
-#include "intl.h"
 #include "procmime.h"
 #include "procheader.h"
 #include "base64.h"
@@ -45,8 +47,8 @@
 #include "codeconv.h"
 #include "utils.h"
 #include "prefs_common.h"
-
 #include "prefs_gtk.h"
+#include "alertpanel.h"
 
 static GHashTable *procmime_get_mime_type_table        (void);
 
@@ -55,12 +57,18 @@ MimeInfo *procmime_mimeinfo_new(void)
        MimeInfo *mimeinfo;
 
        mimeinfo = g_new0(MimeInfo, 1);
-       mimeinfo->type          = MIMETYPE_UNKNOWN;
-       mimeinfo->encoding_type = ENC_UNKNOWN;
-       mimeinfo->disposition   = DISPOSITIONTYPE_UNKNOWN;
+       mimeinfo->content        = MIMECONTENT_EMPTY;
+       mimeinfo->data.filename  = NULL;
 
-       mimeinfo->parameters = g_hash_table_new(g_str_hash, g_str_equal);
-       mimeinfo->node       = g_node_new(mimeinfo);
+       mimeinfo->type           = MIMETYPE_UNKNOWN;
+       mimeinfo->encoding_type  = ENC_UNKNOWN;
+       mimeinfo->typeparameters = g_hash_table_new(g_str_hash, g_str_equal);
+
+       mimeinfo->disposition    = DISPOSITIONTYPE_UNKNOWN;
+       mimeinfo->dispositionparameters 
+                                = g_hash_table_new(g_str_hash, g_str_equal);
+
+       mimeinfo->node           = g_node_new(mimeinfo);
        
        return mimeinfo;
 }
@@ -94,16 +102,31 @@ static gboolean free_func(GNode *node, gpointer data)
 {
        MimeInfo *mimeinfo = (MimeInfo *) node->data;
 
-       if (mimeinfo->tmpfile)
-               unlink(mimeinfo->filename);
-       g_free(mimeinfo->filename);
+       switch (mimeinfo->content) {
+       case MIMECONTENT_FILE:
+               if (mimeinfo->tmp)
+                       g_unlink(mimeinfo->data.filename);
+               g_free(mimeinfo->data.filename);
+               break;
+
+       case MIMECONTENT_MEM:
+               if (mimeinfo->tmp)
+                       g_free(mimeinfo->data.mem);
+       default:
+               break;
+       }
 
        g_free(mimeinfo->subtype);
        g_free(mimeinfo->description);
        g_free(mimeinfo->id);
+       g_free(mimeinfo->location);
 
-       g_hash_table_foreach_remove(mimeinfo->parameters, procmime_mimeinfo_parameters_destroy, NULL);
-       g_hash_table_destroy(mimeinfo->parameters);
+       g_hash_table_foreach_remove(mimeinfo->typeparameters,
+               procmime_mimeinfo_parameters_destroy, NULL);
+       g_hash_table_destroy(mimeinfo->typeparameters);
+       g_hash_table_foreach_remove(mimeinfo->dispositionparameters,
+               procmime_mimeinfo_parameters_destroy, NULL);
+       g_hash_table_destroy(mimeinfo->dispositionparameters);
 
        if (mimeinfo->privacy)
                privacy_free_privacydata(mimeinfo->privacy);
@@ -126,53 +149,6 @@ void procmime_mimeinfo_free_all(MimeInfo *mimeinfo)
        g_node_destroy(node);
 }
 
-#if 0 /* UNUSED */
-MimeInfo *procmime_mimeinfo_insert(MimeInfo *parent, MimeInfo *mimeinfo)
-{
-       MimeInfo *child = parent->children;
-
-       if (!child)
-               parent->children = mimeinfo;
-       else {
-               while (child->next != NULL)
-                       child = child->next;
-
-               child->next = mimeinfo;
-       }
-
-       mimeinfo->parent = parent;
-       mimeinfo->level = parent->level + 1;
-
-       return mimeinfo;
-}
-
-void procmime_mimeinfo_replace(MimeInfo *old, MimeInfo *new)
-{
-       MimeInfo *parent = old->parent;
-       MimeInfo *child;
-
-       g_return_if_fail(parent != NULL);
-       g_return_if_fail(new->next == NULL);
-
-       for (child = parent->children; child && child != old;
-            child = child->next)
-               ;
-       if (!child) {
-               g_warning("oops: parent can't find it's own child");
-               return;
-       }
-       procmime_mimeinfo_free_all(old);
-
-       if (child == parent->children) {
-               new->next = parent->children->next;
-               parent->children = new;
-       } else {
-               new->next = child->next;
-               child = new;
-       }
-}
-#endif
-
 MimeInfo *procmime_mimeinfo_parent(MimeInfo *mimeinfo)
 {
        g_return_val_if_fail(mimeinfo != NULL, NULL);
@@ -210,11 +186,16 @@ MimeInfo *procmime_scan_message(MsgInfo *msginfo)
        gchar *filename;
        MimeInfo *mimeinfo;
 
-       filename = procmsg_get_message_file(msginfo);
-       if (!filename)
+       filename = procmsg_get_message_file_path(msginfo);
+       if (!filename || !is_file_exist(filename)) {
+               g_free(filename);
+               filename = procmsg_get_message_file(msginfo);
+       }
+       if (!filename || !is_file_exist(filename)) 
                return NULL;
-       if (msginfo->folder->stype != F_QUEUE && 
-           msginfo->folder->stype != F_DRAFT)
+
+       if (!folder_has_parent_of_type(msginfo->folder, F_QUEUE) &&
+           !folder_has_parent_of_type(msginfo->folder, F_DRAFT))
                mimeinfo = procmime_scan_file(filename);
        else
                mimeinfo = procmime_scan_queue_file(filename);
@@ -234,10 +215,34 @@ enum
 
 const gchar *procmime_mimeinfo_get_parameter(MimeInfo *mimeinfo, const gchar *name)
 {
+       const gchar *value;
+
        g_return_val_if_fail(mimeinfo != NULL, NULL);
        g_return_val_if_fail(name != NULL, NULL);
+
+       value = g_hash_table_lookup(mimeinfo->dispositionparameters, name);
+       if (value == NULL)
+               value = g_hash_table_lookup(mimeinfo->typeparameters, name);
        
-       return g_hash_table_lookup(mimeinfo->parameters, name);
+       return value;
+}
+
+#define FLUSH_LASTLINE() {                                                     \
+       if (*lastline != '\0') {                                                \
+               gint llen = 0;                                                  \
+               strretchomp(lastline);                                          \
+               llen = strlen(lastline);                                        \
+               if (lastline[llen-1] == ' ' && strcmp(lastline,"-- ")) {        \
+                       /* this is flowed */                                    \
+                       if (delsp)                                              \
+                               lastline[llen-1] = '\0';                        \
+                       fputs(lastline, outfp);                                 \
+               } else {                                                        \
+                       fputs(lastline, outfp);                                 \
+                       fputs("\n", outfp);                                     \
+               }                                                               \
+       }                                                                       \
+       strcpy(lastline, buf);                                                  \
 }
 
 gboolean procmime_decode_content(MimeInfo *mimeinfo)
@@ -247,19 +252,38 @@ gboolean procmime_decode_content(MimeInfo *mimeinfo)
        gchar *tmpfilename;
        FILE *outfp, *infp;
        struct stat statbuf;
-
+       gboolean tmp_file = FALSE;
+       gboolean flowed = FALSE;
+       gboolean delsp = FALSE; 
        EncodingType encoding = forced_encoding 
                                ? forced_encoding
                                : mimeinfo->encoding_type;
+       gchar lastline[BUFFSIZE];
+       memset(lastline, 0, BUFFSIZE);
                   
        g_return_val_if_fail(mimeinfo != NULL, FALSE);
 
-       if (encoding == ENC_BINARY || 
-           encoding == ENC_7BIT ||
-           encoding == ENC_8BIT)
+       if (prefs_common.respect_flowed_format &&
+           mimeinfo->type == MIMETYPE_TEXT && 
+           !strcasecmp(mimeinfo->subtype, "plain")) {
+               if (procmime_mimeinfo_get_parameter(mimeinfo, "format") != NULL &&
+                   !strcasecmp(procmime_mimeinfo_get_parameter(mimeinfo, "format"),"flowed"))
+                       flowed = TRUE;
+               if (flowed &&
+                   procmime_mimeinfo_get_parameter(mimeinfo, "delsp") != NULL &&
+                   !strcasecmp(procmime_mimeinfo_get_parameter(mimeinfo, "delsp"),"yes"))
+                       delsp = TRUE;
+       }
+       
+       if (!flowed && (
+            encoding == ENC_UNKNOWN ||
+            encoding == ENC_BINARY ||
+            encoding == ENC_7BIT ||
+            encoding == ENC_8BIT
+           ))
                return TRUE;
 
-       infp = fopen(mimeinfo->filename, "rb");
+       infp = g_fopen(mimeinfo->data.filename, "rb");
        if (!infp) {
                perror("fopen");
                return FALSE;
@@ -269,32 +293,73 @@ gboolean procmime_decode_content(MimeInfo *mimeinfo)
        outfp = get_tmpfile_in_dir(get_mime_tmp_dir(), &tmpfilename);
        if (!outfp) {
                perror("tmpfile");
+               fclose(infp);
                return FALSE;
        }
-
+       tmp_file = TRUE;
        readend = mimeinfo->offset + mimeinfo->length;
 
        if (encoding == ENC_QUOTED_PRINTABLE) {
                while ((ftell(infp) < readend) && (fgets(buf, sizeof(buf), infp) != NULL)) {
                        gint len;
                        len = qp_decode_line(buf);
-                       fwrite(buf, len, 1, outfp);
+                       buf[len]='\0';
+                       if (!flowed) {
+                               fwrite(buf, 1, len, outfp);
+                       } else {
+                               FLUSH_LASTLINE();
+                       }
                }
+               if (flowed)
+                       FLUSH_LASTLINE();
        } else if (encoding == ENC_BASE64) {
                gchar outbuf[BUFFSIZE];
                gint len;
                Base64Decoder *decoder;
+               gboolean got_error = FALSE;
+               gboolean uncanonicalize = FALSE;
+               FILE *tmpfp = outfp;
+
+               if (mimeinfo->type == MIMETYPE_TEXT ||
+                   mimeinfo->type == MIMETYPE_MESSAGE) {
+                       uncanonicalize = TRUE;
+                       tmpfp = my_tmpfile();
+                       if (!tmpfp) {
+                               perror("tmpfile");
+                               if (tmp_file) fclose(outfp);
+                               fclose(infp);
+                               return FALSE;
+                       }
+               }
 
                decoder = base64_decoder_new();
                while ((ftell(infp) < readend) && (fgets(buf, sizeof(buf), infp) != NULL)) {
                        len = base64_decoder_decode(decoder, buf, outbuf);
-                       if (len < 0) {
-                               g_warning("Bad BASE64 content\n");
-                               break;
+                       if (len < 0 && !got_error) {
+                               g_warning("Bad BASE64 content.\n");
+                               fwrite(_("[Error decoding BASE64]\n"),
+                                       sizeof(gchar),
+                                       strlen(_("[Error decoding BASE64]\n")),
+                                       tmpfp);
+                               got_error = TRUE;
+                               continue;
+                       } else if (len >= 0) {
+                               /* print out the error message only once 
+                                * per block */
+                               fwrite(outbuf, sizeof(gchar), len, tmpfp);
+                               got_error = FALSE;
                        }
-                       fwrite(outbuf, sizeof(gchar), len, outfp);
                }
                base64_decoder_free(decoder);
+
+               if (uncanonicalize) {
+                       rewind(tmpfp);
+                       while (fgets(buf, sizeof(buf), tmpfp) != NULL) {
+                               strcrchomp(buf);
+                               fputs(buf, outfp);
+                       }
+                       fclose(tmpfp);
+               }
        } else if (encoding == ENC_X_UUENCODE) {
                gchar outbuf[BUFFSIZE];
                gint len;
@@ -316,19 +381,25 @@ gboolean procmime_decode_content(MimeInfo *mimeinfo)
                }
        } else {
                while ((ftell(infp) < readend) && (fgets(buf, sizeof(buf), infp) != NULL)) {
-                       fputs(buf, outfp);
+                       if (!flowed) {
+                               fputs(buf, outfp);
+                       } else {
+                               FLUSH_LASTLINE();
+                       }
                }
+               if (flowed)
+                       FLUSH_LASTLINE();
        }
 
        fclose(outfp);
        fclose(infp);
 
        stat(tmpfilename, &statbuf);
-       if (mimeinfo->tmpfile)
-               unlink(mimeinfo->filename);
-       g_free(mimeinfo->filename);
-       mimeinfo->filename = tmpfilename;
-       mimeinfo->tmpfile = TRUE;
+       if (mimeinfo->tmp && (mimeinfo->data.filename != NULL))
+               g_unlink(mimeinfo->data.filename);
+       g_free(mimeinfo->data.filename);
+       mimeinfo->data.filename = tmpfilename;
+       mimeinfo->tmp = TRUE;
        mimeinfo->offset = 0;
        mimeinfo->length = statbuf.st_size;
        mimeinfo->encoding_type = ENC_BINARY;
@@ -336,6 +407,141 @@ gboolean procmime_decode_content(MimeInfo *mimeinfo)
        return TRUE;
 }
 
+#define B64_LINE_SIZE          57
+#define B64_BUFFSIZE           77
+
+gboolean procmime_encode_content(MimeInfo *mimeinfo, EncodingType encoding)
+{
+       FILE *infp = NULL, *outfp;
+       gint len;
+       gchar *tmpfilename;
+       struct stat statbuf;
+
+       if (mimeinfo->content == MIMECONTENT_EMPTY)
+               return TRUE;
+
+       if (mimeinfo->encoding_type != ENC_UNKNOWN &&
+           mimeinfo->encoding_type != ENC_BINARY &&
+           mimeinfo->encoding_type != ENC_7BIT &&
+           mimeinfo->encoding_type != ENC_8BIT)
+               if(!procmime_decode_content(mimeinfo))
+                       return FALSE;
+
+       outfp = get_tmpfile_in_dir(get_mime_tmp_dir(), &tmpfilename);
+       if (!outfp) {
+               perror("tmpfile");
+               return FALSE;
+       }
+
+       if (mimeinfo->content == MIMECONTENT_FILE) {
+               if ((infp = g_fopen(mimeinfo->data.filename, "rb")) == NULL) {
+                       g_warning("Can't open file %s\n", mimeinfo->data.filename);
+                       return FALSE;
+               }
+       } else if (mimeinfo->content == MIMECONTENT_MEM) {
+               infp = str_open_as_stream(mimeinfo->data.mem);
+               if (infp == NULL)
+                       return FALSE;
+       }
+
+       if (encoding == ENC_BASE64) {
+               gchar inbuf[B64_LINE_SIZE], outbuf[B64_BUFFSIZE];
+               FILE *tmp_fp = infp;
+               gchar *tmp_file = NULL;
+
+               if (mimeinfo->type == MIMETYPE_TEXT ||
+                    mimeinfo->type == MIMETYPE_MESSAGE) {
+                       if (mimeinfo->content == MIMECONTENT_FILE) {
+                               tmp_file = get_tmp_file();
+                               if (canonicalize_file(mimeinfo->data.filename, tmp_file) < 0) {
+                                       g_free(tmp_file);
+                                       fclose(infp);
+                                       return FALSE;
+                               }
+                               if ((tmp_fp = g_fopen(tmp_file, "rb")) == NULL) {
+                                       FILE_OP_ERROR(tmp_file, "fopen");
+                                       g_unlink(tmp_file);
+                                       g_free(tmp_file);
+                                       fclose(infp);
+                                       return FALSE;
+                               }
+                       } else {
+                               gchar *out = canonicalize_str(mimeinfo->data.mem);
+                               fclose(infp);
+                               infp = str_open_as_stream(out);
+                               tmp_fp = infp;
+                               g_free(out);
+                               if (infp == NULL)
+                                       return FALSE;
+                       }
+               }
+
+               while ((len = fread(inbuf, sizeof(gchar),
+                                   B64_LINE_SIZE, tmp_fp))
+                      == B64_LINE_SIZE) {
+                       base64_encode(outbuf, inbuf, B64_LINE_SIZE);
+                       fputs(outbuf, outfp);
+                       fputc('\n', outfp);
+               }
+               if (len > 0 && feof(tmp_fp)) {
+                       base64_encode(outbuf, inbuf, len);
+                       fputs(outbuf, outfp);
+                       fputc('\n', outfp);
+               }
+
+               if (tmp_file) {
+                       fclose(tmp_fp);
+                       g_unlink(tmp_file);
+                       g_free(tmp_file);
+               }
+       } else if (encoding == ENC_QUOTED_PRINTABLE) {
+               gchar inbuf[BUFFSIZE], outbuf[BUFFSIZE * 4];
+
+               while (fgets(inbuf, sizeof(inbuf), infp) != NULL) {
+                       qp_encode_line(outbuf, inbuf);
+
+                       if (!strncmp("From ", outbuf, sizeof("From ")-1)) {
+                               gchar *tmpbuf = outbuf;
+                               
+                               tmpbuf += sizeof("From ")-1;
+                               
+                               fputs("=46rom ", outfp);
+                               fputs(tmpbuf, outfp);
+                       } else 
+                               fputs(outbuf, outfp);
+               }
+       } else {
+               gchar buf[BUFFSIZE];
+
+               while (fgets(buf, sizeof(buf), infp) != NULL) {
+                       strcrchomp(buf);
+                       fputs(buf, outfp);
+               }
+       }
+
+       fclose(outfp);
+       fclose(infp);
+
+       if (mimeinfo->content == MIMECONTENT_FILE) {
+               if (mimeinfo->tmp && (mimeinfo->data.filename != NULL))
+                       g_unlink(mimeinfo->data.filename);
+               g_free(mimeinfo->data.filename);
+       } else if (mimeinfo->content == MIMECONTENT_MEM) {
+               if (mimeinfo->tmp && (mimeinfo->data.mem != NULL))
+                       g_free(mimeinfo->data.mem);
+       }
+
+       stat(tmpfilename, &statbuf);
+       mimeinfo->content = MIMECONTENT_FILE;
+       mimeinfo->data.filename = tmpfilename;
+       mimeinfo->tmp = TRUE;
+       mimeinfo->offset = 0;
+       mimeinfo->length = statbuf.st_size;
+       mimeinfo->encoding_type = encoding;
+
+       return TRUE;
+}
+
 gint procmime_get_part(const gchar *outfile, MimeInfo *mimeinfo)
 {
        FILE *infp, *outfp;
@@ -348,16 +554,16 @@ gint procmime_get_part(const gchar *outfile, MimeInfo *mimeinfo)
        if (mimeinfo->encoding_type != ENC_BINARY && !procmime_decode_content(mimeinfo))
                return -1;
 
-       if ((infp = fopen(mimeinfo->filename, "rb")) == NULL) {
-               FILE_OP_ERROR(mimeinfo->filename, "fopen");
+       if ((infp = g_fopen(mimeinfo->data.filename, "rb")) == NULL) {
+               FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
                return -1;
        }
        if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
-               FILE_OP_ERROR(mimeinfo->filename, "fseek");
+               FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
                fclose(infp);
                return -1;
        }
-       if ((outfp = fopen(outfile, "wb")) == NULL) {
+       if ((outfp = g_fopen(outfile, "wb")) == NULL) {
                FILE_OP_ERROR(outfile, "fopen");
                fclose(infp);
                return -1;
@@ -373,7 +579,7 @@ gint procmime_get_part(const gchar *outfile, MimeInfo *mimeinfo)
        fclose(infp);
        if (fclose(outfp) == EOF) {
                FILE_OP_ERROR(outfile, "fclose");
-               unlink(outfile);
+               g_unlink(outfile);
                return -1;
        }
 
@@ -419,7 +625,7 @@ void renderer_read_config(void)
        renderer_list = NULL;
 
        rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, RENDERER_RC, NULL);
-       f = fopen(rcpath, "rb");
+       f = g_fopen(rcpath, "rb");
        g_free(rcpath);
        
        if (f == NULL)
@@ -499,7 +705,7 @@ FILE *procmime_get_text_content(MimeInfo *mimeinfo)
                return NULL;
        }
 
-       tmpfp = fopen(tmpfile, "rb");
+       tmpfp = g_fopen(tmpfile, "rb");
        if (tmpfp == NULL) {
                g_free(tmpfile);
                return NULL;
@@ -524,7 +730,7 @@ FILE *procmime_get_text_content(MimeInfo *mimeinfo)
                struct ContentRenderer * cr;
 
                cr = cur->data;
-               if (g_strcasecmp(cr->content_type, content_type) == 0) {
+               if (g_ascii_strcasecmp(cr->content_type, content_type) == 0) {
                        renderer = cr;
                        break;
                }
@@ -538,7 +744,7 @@ FILE *procmime_get_text_content(MimeInfo *mimeinfo)
                oldout = dup(1);
                
                dup2(fileno(outfp), 1);
-               
+
                p = popen(renderer->renderer, "w");
                if (p != NULL) {
                        size_t count;
@@ -551,20 +757,19 @@ FILE *procmime_get_text_content(MimeInfo *mimeinfo)
                }
                
                dup2(oldout, 1);
-#warning FIXME_GTK2 HTML/RTF not yet utf8
 /* CodeConverter seems to have no effect here */
-       } else if (mimeinfo->type == MIMETYPE_TEXT && !g_strcasecmp(mimeinfo->subtype, "html")) {
-               HTMLParser *parser;
+       } else if (mimeinfo->type == MIMETYPE_TEXT && !g_ascii_strcasecmp(mimeinfo->subtype, "html")) {
+               SC_HTMLParser *parser;
                CodeConverter *conv;
 
                conv = conv_code_converter_new(src_codeset);
-               parser = html_parser_new(tmpfp, conv);
-               while ((str = html_parse(parser)) != NULL) {
+               parser = sc_html_parser_new(tmpfp, conv);
+               while ((str = sc_html_parse(parser)) != NULL) {
                        fputs(str, outfp);
                }
-               html_parser_destroy(parser);
+               sc_html_parser_destroy(parser);
                conv_code_converter_destroy(conv);
-       } else if (mimeinfo->type == MIMETYPE_TEXT && !g_strcasecmp(mimeinfo->subtype, "enriched")) {
+       } else if (mimeinfo->type == MIMETYPE_TEXT && !g_ascii_strcasecmp(mimeinfo->subtype, "enriched")) {
                ERTFParser *parser;
                CodeConverter *conv;
 
@@ -593,7 +798,7 @@ FILE *procmime_get_text_content(MimeInfo *mimeinfo)
 
        fclose(tmpfp);
        rewind(outfp);
-       unlink(tmpfile);
+       g_unlink(tmpfile);
        g_free(tmpfile);
 
        return outfp;
@@ -612,8 +817,68 @@ FILE *procmime_get_first_text_content(MsgInfo *msginfo)
        if (!mimeinfo) return NULL;
 
        partinfo = mimeinfo;
-       while (partinfo && partinfo->type != MIMETYPE_TEXT)
+       while (partinfo && partinfo->type != MIMETYPE_TEXT) {
+               partinfo = procmime_mimeinfo_next(partinfo);
+       }
+       if (partinfo)
+               outfp = procmime_get_text_content(partinfo);
+
+       procmime_mimeinfo_free_all(mimeinfo);
+
+       return outfp;
+}
+
+
+static gboolean find_encrypted_func(GNode *node, gpointer data)
+{
+       MimeInfo *mimeinfo = (MimeInfo *) node->data;
+       MimeInfo **encinfo = (MimeInfo **) data;
+       
+       if (privacy_mimeinfo_is_encrypted(mimeinfo)) {
+               *encinfo = mimeinfo;
+               return TRUE;
+       }
+       
+       return FALSE;
+}
+
+static MimeInfo *find_encrypted_part(MimeInfo *rootinfo)
+{
+       MimeInfo *encinfo = NULL;
+
+       g_node_traverse(rootinfo->node, G_IN_ORDER, G_TRAVERSE_ALL, -1,
+               find_encrypted_func, &encinfo);
+       
+       return encinfo;
+}
+
+/* search the first encrypted text part of (multipart) MIME message,
+   decode, convert it and output to outfp. */
+FILE *procmime_get_first_encrypted_text_content(MsgInfo *msginfo)
+{
+       FILE *outfp = NULL;
+       MimeInfo *mimeinfo, *partinfo, *encinfo;
+
+       g_return_val_if_fail(msginfo != NULL, NULL);
+
+       mimeinfo = procmime_scan_message(msginfo);
+       if (!mimeinfo) {
+               return NULL;
+       }
+
+       partinfo = mimeinfo;
+       if ((encinfo = find_encrypted_part(partinfo)) != NULL) {
+               debug_print("decrypting message part\n");
+               if (privacy_mimeinfo_decrypt(encinfo) < 0) {
+                       alertpanel_error(_("Couldn't decrypt: %s"),
+                               privacy_get_error());
+                       return NULL;
+               }
+       }
+       partinfo = mimeinfo;
+       while (partinfo && partinfo->type != MIMETYPE_TEXT) {
                partinfo = procmime_mimeinfo_next(partinfo);
+       }
 
        if (partinfo)
                outfp = procmime_get_text_content(partinfo);
@@ -623,29 +888,44 @@ FILE *procmime_get_first_text_content(MsgInfo *msginfo)
        return outfp;
 }
 
+gboolean procmime_msginfo_is_encrypted(MsgInfo *msginfo)
+{
+       MimeInfo *mimeinfo, *partinfo;
+       gboolean result = FALSE;
+
+       g_return_val_if_fail(msginfo != NULL, FALSE);
+
+       mimeinfo = procmime_scan_message(msginfo);
+       if (!mimeinfo) {
+               return FALSE;
+       }
+
+       partinfo = mimeinfo;
+       result = (find_encrypted_part(partinfo) != NULL);
+       procmime_mimeinfo_free_all(mimeinfo);
+
+       return result;
+}
+
 gboolean procmime_find_string_part(MimeInfo *mimeinfo, const gchar *filename,
-                                  const gchar *str, gboolean case_sens)
+                                  const gchar *str, StrFindFunc find_func)
 {
        FILE *outfp;
        gchar buf[BUFFSIZE];
-       gchar *(* StrFindFunc) (const gchar *haystack, const gchar *needle);
 
        g_return_val_if_fail(mimeinfo != NULL, FALSE);
        g_return_val_if_fail(mimeinfo->type == MIMETYPE_TEXT, FALSE);
        g_return_val_if_fail(str != NULL, FALSE);
+       g_return_val_if_fail(find_func != NULL, FALSE);
 
        outfp = procmime_get_text_content(mimeinfo);
 
        if (!outfp)
                return FALSE;
 
-       if (case_sens)
-               StrFindFunc = strstr;
-       else
-               StrFindFunc = strcasestr;
-
        while (fgets(buf, sizeof(buf), outfp) != NULL) {
-               if (StrFindFunc(buf, str) != NULL) {
+               strretchomp(buf);
+               if (find_func(buf, str)) {
                        fclose(outfp);
                        return TRUE;
                }
@@ -657,7 +937,7 @@ gboolean procmime_find_string_part(MimeInfo *mimeinfo, const gchar *filename,
 }
 
 gboolean procmime_find_string(MsgInfo *msginfo, const gchar *str,
-                             gboolean case_sens)
+                             StrFindFunc find_func)
 {
        MimeInfo *mimeinfo;
        MimeInfo *partinfo;
@@ -666,6 +946,7 @@ gboolean procmime_find_string(MsgInfo *msginfo, const gchar *str,
 
        g_return_val_if_fail(msginfo != NULL, FALSE);
        g_return_val_if_fail(str != NULL, FALSE);
+       g_return_val_if_fail(find_func != NULL, FALSE);
 
        filename = procmsg_get_message_file(msginfo);
        if (!filename) return FALSE;
@@ -675,7 +956,7 @@ gboolean procmime_find_string(MsgInfo *msginfo, const gchar *str,
             partinfo = procmime_mimeinfo_next(partinfo)) {
                if (partinfo->type == MIMETYPE_TEXT) {
                        if (procmime_find_string_part
-                               (partinfo, filename, str, case_sens) == TRUE) {
+                               (partinfo, filename, str, find_func) == TRUE) {
                                found = TRUE;
                                break;
                        }
@@ -691,7 +972,7 @@ gboolean procmime_find_string(MsgInfo *msginfo, const gchar *str,
 gchar *procmime_get_tmp_file_name(MimeInfo *mimeinfo)
 {
        static guint32 id = 0;
-       const gchar *base;
+       gchar *base;
        gchar *filename;
        gchar f_prefix[10];
 
@@ -699,8 +980,8 @@ gchar *procmime_get_tmp_file_name(MimeInfo *mimeinfo)
 
        g_snprintf(f_prefix, sizeof(f_prefix), "%08x.", id++);
 
-       if ((mimeinfo->type == MIMETYPE_TEXT) && !g_strcasecmp(mimeinfo->subtype, "html"))
-               base = "mimetmp.html";
+       if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
+               base = g_strdup("mimetmp.html");
        else {
                const gchar *basetmp;
 
@@ -709,15 +990,19 @@ gchar *procmime_get_tmp_file_name(MimeInfo *mimeinfo)
                        basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
                if (basetmp == NULL)
                        basetmp = "mimetmp";
-               base = g_basename(basetmp);
-               if (*base == '\0') base = "mimetmp";
-               Xstrdup_a(base, base, return NULL);
+               basetmp = g_path_get_basename(basetmp);
+               if (*basetmp == '\0') 
+                       basetmp = g_strdup("mimetmp");
+               base = conv_filename_from_utf8(basetmp);
+               g_free((gchar*)basetmp);
                subst_for_shellsafe_filename(base);
        }
 
        filename = g_strconcat(get_mime_tmp_dir(), G_DIR_SEPARATOR_S,
                               f_prefix, base, NULL);
 
+       g_free(base);
+       
        return filename;
 }
 
@@ -728,18 +1013,20 @@ gchar *procmime_get_mime_type(const gchar *filename)
        static GHashTable *mime_type_table = NULL;
        MimeType *mime_type;
        const gchar *p;
-       gchar *ext;
+       gchar *ext = NULL;
+       gchar *base;
 
        if (!mime_type_table) {
                mime_type_table = procmime_get_mime_type_table();
                if (!mime_type_table) return NULL;
        }
 
-       filename = g_basename(filename);
-       p = strrchr(filename, '.');
+       base = g_path_get_basename(filename);
+       if ((p = strrchr(base, '.')) != NULL)
+               Xstrdup_a(ext, p + 1, p = NULL );
+       g_free(base);
        if (!p) return NULL;
 
-       Xstrdup_a(ext, p + 1, return NULL);
        g_strdown(ext);
        mime_type = g_hash_table_lookup(mime_type_table, ext);
        if (mime_type) {
@@ -771,7 +1058,7 @@ static gint procmime_str_equal(gconstpointer gptr1, gconstpointer gptr2)
        const char *str1 = gptr1;
        const char *str2 = gptr2;
 
-       return !strcasecmp(str1, str2);
+       return !g_utf8_collate(str1, str2);
 }
 
 static GHashTable *procmime_get_mime_type_table(void)
@@ -818,17 +1105,23 @@ GList *procmime_get_mime_type_list(void)
        GList *list = NULL;
        FILE *fp;
        gchar buf[BUFFSIZE];
-       guchar *p;
+       gchar *p;
        gchar *delim;
        MimeType *mime_type;
+       gboolean fp_is_glob_file = TRUE;
 
        if (mime_type_list) 
                return mime_type_list;
-
-       if ((fp = fopen("/etc/mime.types", "rb")) == NULL) {
-               if ((fp = fopen(SYSCONFDIR "/mime.types", "rb")) == NULL) {
-                       FILE_OP_ERROR(SYSCONFDIR "/mime.types", "fopen");
-                       return NULL;
+       
+       if ((fp = g_fopen("/usr/share/mime/globs", "rb")) == NULL) {
+               fp_is_glob_file = FALSE;
+               if ((fp = g_fopen("/etc/mime.types", "rb")) == NULL) {
+                       if ((fp = g_fopen(SYSCONFDIR "/mime.types", "rb")) 
+                               == NULL) {
+                               FILE_OP_ERROR(SYSCONFDIR "/mime.types", 
+                                       "fopen");
+                               return NULL;
+                       }
                }
        }
 
@@ -838,7 +1131,13 @@ GList *procmime_get_mime_type_list(void)
                g_strstrip(buf);
 
                p = buf;
-               while (*p && !isspace(*p)) p++;
+               
+               if (fp_is_glob_file) {
+                       while (*p && !g_ascii_isspace(*p) && (*p!=':')) p++;
+               } else {
+                       while (*p && !g_ascii_isspace(*p)) p++;
+               }
+
                if (*p) {
                        *p = '\0';
                        p++;
@@ -851,7 +1150,12 @@ GList *procmime_get_mime_type_list(void)
                mime_type->type = g_strdup(buf);
                mime_type->sub_type = g_strdup(delim + 1);
 
-               while (*p && isspace(*p)) p++;
+               if (fp_is_glob_file) {
+                       while (*p && (g_ascii_isspace(*p)||(*p=='*')||(*p=='.'))) p++;
+               } else {
+                       while (*p && g_ascii_isspace(*p)) p++;
+               }
+
                if (*p)
                        mime_type->extension = g_strdup(p);
                else
@@ -872,44 +1176,72 @@ EncodingType procmime_get_encoding_for_charset(const gchar *charset)
 {
        if (!charset)
                return ENC_8BIT;
-       else if (!strncasecmp(charset, "ISO-2022-", 9) ||
-                !strcasecmp(charset, "US-ASCII"))
+       else if (!g_ascii_strncasecmp(charset, "ISO-2022-", 9) ||
+                !g_ascii_strcasecmp(charset, "US-ASCII"))
                return ENC_7BIT;
-       else if (!strcasecmp(charset, "ISO-8859-5") ||
-                !strncasecmp(charset, "KOI8-", 5) ||
-                !strcasecmp(charset, "Windows-1251"))
+       else if (!g_ascii_strcasecmp(charset, "ISO-8859-5") ||
+                !g_ascii_strncasecmp(charset, "KOI8-", 5) ||
+                !g_ascii_strcasecmp(charset, "Windows-1251"))
                return ENC_8BIT;
-       else if (!strncasecmp(charset, "ISO-8859-", 9))
+       else if (!g_ascii_strncasecmp(charset, "ISO-8859-", 9))
                return ENC_QUOTED_PRINTABLE;
-       else
+       else if (!g_ascii_strncasecmp(charset, "UTF-8", 5))
+               return ENC_QUOTED_PRINTABLE;
+       else 
                return ENC_8BIT;
 }
 
-EncodingType procmime_get_encoding_for_file(const gchar *file)
+EncodingType procmime_get_encoding_for_text_file(const gchar *file, gboolean *has_binary)
 {
        FILE *fp;
-       guchar buf[BUFSIZ];
+       guchar buf[BUFFSIZE];
        size_t len;
+       size_t octet_chars = 0;
+       size_t total_len = 0;
+       gfloat octet_percentage;
+       gboolean force_b64 = FALSE;
 
-       if ((fp = fopen(file, "rb")) == NULL) {
+       if ((fp = g_fopen(file, "rb")) == NULL) {
                FILE_OP_ERROR(file, "fopen");
                return ENC_UNKNOWN;
        }
 
-       while ((len = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
+       while ((len = fread(buf, sizeof(guchar), sizeof(buf), fp)) > 0) {
                guchar *p;
                gint i;
 
-               for (p = buf, i = 0; i < len; p++, i++) {
-                       if (*p & 0x80) {
-                               fclose(fp);
-                               return ENC_BASE64;
+               for (p = buf, i = 0; i < len; ++p, ++i) {
+                       if (*p & 0x80)
+                               ++octet_chars;
+                       if (*p == '\0') {
+                               force_b64 = TRUE;
+                               *has_binary = TRUE;
                        }
                }
+               total_len += len;
        }
 
        fclose(fp);
-       return ENC_7BIT;
+       
+       if (total_len > 0)
+               octet_percentage = (gfloat)octet_chars / (gfloat)total_len;
+       else
+               octet_percentage = 0.0;
+
+       debug_print("procmime_get_encoding_for_text_file(): "
+                   "8bit chars: %d / %d (%f%%)\n", octet_chars, total_len,
+                   100.0 * octet_percentage);
+
+       if (octet_percentage > 0.20 || force_b64) {
+               debug_print("using BASE64\n");
+               return ENC_BASE64;
+       } else if (octet_chars > 0) {
+               debug_print("using quoted-printable\n");
+               return ENC_QUOTED_PRINTABLE;
+       } else {
+               debug_print("using 7bit\n");
+               return ENC_7BIT;
+       }
 }
 
 struct EncodingTable 
@@ -957,7 +1289,7 @@ static struct TypeTable mime_type_table[] = {
        {NULL, 0},
 };
 
-const gchar *procmime_get_type_str(MimeMediaType type)
+const gchar *procmime_get_media_type_str(MimeMediaType type)
 {
        struct TypeTable *type_table;
        
@@ -968,6 +1300,17 @@ const gchar *procmime_get_type_str(MimeMediaType type)
        return NULL;
 }
 
+MimeMediaType procmime_get_media_type(const gchar *str)
+{
+       struct TypeTable *typetablearray;
+
+       for (typetablearray = mime_type_table; typetablearray->str != NULL; typetablearray++)
+               if (g_ascii_strncasecmp(str, typetablearray->str, strlen(typetablearray->str)) == 0)
+                       return typetablearray->type;
+
+       return MIMETYPE_UNKNOWN;
+}
+
 /*!
  *\brief       Safe wrapper for content type string.
  *
@@ -978,17 +1321,18 @@ gchar *procmime_get_content_type_str(MimeMediaType type,
 {
        const gchar *type_str = NULL;
 
-       if (subtype == NULL || !(type_str = procmime_get_type_str(type)))
+       if (subtype == NULL || !(type_str = procmime_get_media_type_str(type)))
                return g_strdup("unknown");
        return g_strdup_printf("%s/%s", type_str, subtype);
 }
 
-void procmime_parse_mimepart(MimeInfo *parent,
+static int procmime_parse_mimepart(MimeInfo *parent,
                             gchar *content_type,
                             gchar *content_encoding,
                             gchar *content_description,
                             gchar *content_id,
                             gchar *content_disposition,
+                            gchar *content_location,
                             const gchar *filename,
                             guint offset,
                             guint length);
@@ -1004,53 +1348,54 @@ void procmime_parse_message_rfc822(MimeInfo *mimeinfo)
                                                   NULL, TRUE},
                                {"Content-Disposition:",
                                                   NULL, TRUE},
+                               {"Content-Location:",
+                                                  NULL, TRUE},
                                {"MIME-Version:",
                                                   NULL, TRUE},
                                {NULL,             NULL, FALSE}};
        guint content_start, i;
        FILE *fp;
-       gint mime_major, mime_minor;
+        gchar *tmp;
 
        procmime_decode_content(mimeinfo);
 
-       fp = fopen(mimeinfo->filename, "rb");
+       fp = g_fopen(mimeinfo->data.filename, "rb");
        if (fp == NULL) {
-               FILE_OP_ERROR(mimeinfo->filename, "fopen");
+               FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
                return;
        }
        fseek(fp, mimeinfo->offset, SEEK_SET);
        procheader_get_header_fields(fp, hentry);
-       if (hentry[0].body != NULL)
-               conv_unmime_header_overwrite(hentry[0].body);
-       if (hentry[2].body != NULL)
-               conv_unmime_header_overwrite(hentry[2].body);
-       if (hentry[4].body != NULL)
-               conv_unmime_header_overwrite(hentry[4].body);
+       if (hentry[0].body != NULL) {
+                tmp = conv_unmime_header(hentry[0].body, NULL);
+                g_free(hentry[0].body);
+                hentry[0].body = tmp;
+        }                
+       if (hentry[2].body != NULL) {
+                tmp = conv_unmime_header(hentry[2].body, NULL);
+                g_free(hentry[2].body);
+                hentry[2].body = tmp;
+        }                
+       if (hentry[4].body != NULL) {
+                tmp = conv_unmime_header(hentry[4].body, NULL);
+                g_free(hentry[4].body);
+                hentry[4].body = tmp;
+        }                
+       if (hentry[5].body != NULL) {
+                tmp = conv_unmime_header(hentry[5].body, NULL);
+                g_free(hentry[5].body);
+                hentry[5].body = tmp;
+        }                
        content_start = ftell(fp);
        fclose(fp);
-
-       if ((hentry[5].body != NULL) &&
-           (sscanf(hentry[5].body, "%d.%d", &mime_major, &mime_minor) == 2) &&
-           (mime_major == 1) && (mime_minor == 0)) {
-               procmime_parse_mimepart(mimeinfo,
-                                       hentry[0].body, hentry[1].body,
-                                       hentry[2].body, hentry[3].body, 
-                                       hentry[4].body, 
-                                       mimeinfo->filename, content_start,
-                                       mimeinfo->length - (content_start - mimeinfo->offset));
-       } else {
-               MimeInfo *subinfo;
-
-               subinfo = procmime_mimeinfo_new();
-               subinfo->encoding_type = ENC_BINARY;
-               subinfo->type = MIMETYPE_TEXT;
-               subinfo->subtype = g_strdup("plain");
-               subinfo->filename = g_strdup(mimeinfo->filename);
-               subinfo->offset = content_start;
-               subinfo->length = mimeinfo->length - (content_start - mimeinfo->offset);
-
-               g_node_append(mimeinfo->node, subinfo->node);
-       }
+       
+       procmime_parse_mimepart(mimeinfo,
+                               hentry[0].body, hentry[1].body,
+                               hentry[2].body, hentry[3].body,
+                               hentry[4].body, hentry[5].body,
+                               mimeinfo->data.filename, content_start,
+                               mimeinfo->length - (content_start - mimeinfo->offset));
+       
        for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
                g_free(hentry[i].body);
                hentry[i].body = NULL;
@@ -1068,38 +1413,41 @@ void procmime_parse_multipart(MimeInfo *mimeinfo)
                                                   NULL, TRUE},
                                {"Content-Disposition:",
                                                   NULL, TRUE},
+                               {"Content-Location:",
+                                                  NULL, TRUE},
                                {NULL,             NULL, FALSE}};
-       gchar *p;
+       gchar *p, *tmp;
        gchar *boundary;
        gint boundary_len = 0, lastoffset = -1, i;
        gchar buf[BUFFSIZE];
        FILE *fp;
+       int result = 0;
 
-       boundary = g_hash_table_lookup(mimeinfo->parameters, "boundary");
+       boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
        if (!boundary)
                return;
        boundary_len = strlen(boundary);
 
        procmime_decode_content(mimeinfo);
 
-       fp = fopen(mimeinfo->filename, "rb");
+       fp = g_fopen(mimeinfo->data.filename, "rb");
        if (fp == NULL) {
-               FILE_OP_ERROR(mimeinfo->filename, "fopen");
+               FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
                return;
        }
        fseek(fp, mimeinfo->offset, SEEK_SET);
-       while ((p = fgets(buf, sizeof(buf), fp)) != NULL) {
-               if (ftell(fp) > (mimeinfo->offset + mimeinfo->length))
+       while ((p = fgets(buf, sizeof(buf), fp)) != NULL && result == 0) {
+               if (ftell(fp) - 1 > (mimeinfo->offset + mimeinfo->length))
                        break;
 
                if (IS_BOUNDARY(buf, boundary, boundary_len)) {
                        if (lastoffset != -1) {
-                               procmime_parse_mimepart(mimeinfo,
+                               result = procmime_parse_mimepart(mimeinfo,
                                                        hentry[0].body, hentry[1].body,
                                                        hentry[2].body, hentry[3].body, 
-                                                       hentry[4].body, 
-                                                       mimeinfo->filename, lastoffset,
-                                                       (ftell(fp) - strlen(buf)) - lastoffset);
+                                                       hentry[4].body, hentry[5].body,
+                                                       mimeinfo->data.filename, lastoffset,
+                                                       (ftell(fp) - strlen(buf)) - lastoffset - 1);
                        }
                        
                        if (buf[2 + boundary_len]     == '-' &&
@@ -1111,12 +1459,26 @@ void procmime_parse_multipart(MimeInfo *mimeinfo)
                                hentry[i].body = NULL;
                        }
                        procheader_get_header_fields(fp, hentry);
-                       if (hentry[0].body != NULL)
-                               conv_unmime_header_overwrite(hentry[0].body);
-                       if (hentry[2].body != NULL)
-                               conv_unmime_header_overwrite(hentry[2].body);
-                       if (hentry[4].body != NULL)
-                               conv_unmime_header_overwrite(hentry[4].body);
+                        if (hentry[0].body != NULL) {
+                                tmp = conv_unmime_header(hentry[0].body, NULL);
+                                g_free(hentry[0].body);
+                                hentry[0].body = tmp;
+                        }                
+                        if (hentry[2].body != NULL) {
+                                tmp = conv_unmime_header(hentry[2].body, NULL);
+                                g_free(hentry[2].body);
+                                hentry[2].body = tmp;
+                        }                
+                        if (hentry[4].body != NULL) {
+                                tmp = conv_unmime_header(hentry[4].body, NULL);
+                                g_free(hentry[4].body);
+                                hentry[4].body = tmp;
+                        }                
+                        if (hentry[5].body != NULL) {
+                                tmp = conv_unmime_header(hentry[5].body, NULL);
+                                g_free(hentry[5].body);
+                                hentry[5].body = tmp;
+                        }                
                        lastoffset = ftell(fp);
                }
        }
@@ -1127,111 +1489,231 @@ void procmime_parse_multipart(MimeInfo *mimeinfo)
        fclose(fp);
 }
 
-static void add_to_mimeinfo_parameters(gchar **parts, MimeInfo *mimeinfo)
+static void parse_parameters(const gchar *parameters, GHashTable *table)
 {
-       gchar **strarray;
-
-       for (strarray = parts; *strarray != NULL; strarray++) {
-               gchar **parameters_parts;
-
-               parameters_parts = g_strsplit(*strarray, "=", 2);
-               if ((parameters_parts[0] != NULL) && (parameters_parts[1] != NULL)) {
-                       gchar *firstspace;
-
-                       g_strstrip(parameters_parts[0]);
-                       g_strstrip(parameters_parts[1]);
-                       g_strdown(parameters_parts[0]);
-                       if (parameters_parts[1][0] == '"')
-                               extract_quote(parameters_parts[1], '"');
-                       else if ((firstspace = strchr(parameters_parts[1], ' ')) != NULL)
-                               *firstspace = '\0';
-                       if (g_hash_table_lookup(mimeinfo->parameters,
-                                              parameters_parts[0]) == NULL)
-                               g_hash_table_insert(mimeinfo->parameters,
-                                                   g_strdup(parameters_parts[0]),
-                                                   g_strdup(parameters_parts[1]));
+       gchar *params, *param, *next;
+       GSList *convlist = NULL, *concatlist = NULL, *cur;
+
+       params = g_strdup(parameters);
+       param = params;
+       next = params;
+       for (; next != NULL; param = next) {
+               gchar *attribute, *value, *tmp;
+               gint len;
+               gboolean convert = FALSE;
+
+               next = strchr_with_skip_quote(param, '"', ';');
+               if (next != NULL) {
+                       next[0] = '\0';
+                       next++;
+               }
+
+               g_strstrip(param);
+
+               attribute = param;
+               value = strchr(attribute, '=');
+               if (value == NULL)
+                       continue;
+
+               value[0] = '\0';
+               value++;
+               while (value[0] == ' ')
+                       value++;
+
+               g_strdown(attribute);
+
+               len = strlen(attribute);
+               if (attribute[len - 1] == '*') {
+                       gchar *srcpos, *dstpos, *endpos;
+
+                       convert = TRUE;
+                       attribute[len - 1] = '\0';
+
+                       srcpos = value;
+                       dstpos = value;
+                       endpos = value + strlen(value);
+                       while (srcpos < endpos) {
+                               if (*srcpos != '%')
+                                       *dstpos = *srcpos;
+                               else {
+                                       guchar dstvalue;
+
+                                       if (!get_hex_value(&dstvalue, srcpos[1], srcpos[2]))
+                                               *dstpos = '?';
+                                       else
+                                               *dstpos = dstvalue;
+                                       srcpos += 2;
+                               }
+                               srcpos++;
+                               dstpos++;
+                       }
+                       *dstpos = '\0';
+               } else {
+                       if (value[0] == '"')
+                               extract_quote(value, '"');
+                       else if ((tmp = strchr(value, ' ')) != NULL)
+                               *tmp = '\0';
+               }
+
+               if (attribute) {
+                       while (attribute[0] == ' ')
+                               attribute++;
+                       while (attribute[strlen(attribute)-1] == ' ') 
+                               attribute[strlen(attribute)-1] = '\0';
+               } 
+               if (value) {
+                       while (value[0] == ' ')
+                               value++;
+                       while (value[strlen(value)-1] == ' ') 
+                               value[strlen(value)-1] = '\0';
+               }               
+               if (strrchr(attribute, '*') != NULL) {
+                       gchar *tmpattr;
+
+                       tmpattr = g_strdup(attribute);
+                       tmp = strrchr(tmpattr, '*');
+                       tmp[0] = '\0';
+
+                       if ((tmp[1] == '0') && (tmp[2] == '\0') && 
+                           (g_slist_find_custom(concatlist, attribute, g_str_equal) == NULL))
+                               concatlist = g_slist_prepend(concatlist, g_strdup(tmpattr));
+
+                       if (convert && (g_slist_find_custom(convlist, attribute, g_str_equal) == NULL))
+                               convlist = g_slist_prepend(convlist, g_strdup(tmpattr));
+
+                       g_free(tmpattr);
+               } else if (convert) {
+                       if (g_slist_find_custom(convlist, attribute, g_str_equal) == NULL)
+                               convlist = g_slist_prepend(convlist, g_strdup(attribute));
+               }
+
+               if (g_hash_table_lookup(table, attribute) == NULL)
+                       g_hash_table_insert(table, g_strdup(attribute), g_strdup(value));
+       }
+
+       for (cur = concatlist; cur != NULL; cur = g_slist_next(cur)) {
+               gchar *attribute, *attrwnum, *partvalue;
+               gint n = 0;
+               GString *value;
+
+               attribute = (gchar *) cur->data;
+               value = g_string_sized_new(64);
+
+               attrwnum = g_strdup_printf("%s*%d", attribute, n);
+               while ((partvalue = g_hash_table_lookup(table, attrwnum)) != NULL) {
+                       g_string_append(value, partvalue);
+
+                       g_free(attrwnum);
+                       n++;
+                       attrwnum = g_strdup_printf("%s*%d", attribute, n);
                }
-               g_strfreev(parameters_parts);
+               g_free(attrwnum);
+
+               g_hash_table_insert(table, g_strdup(attribute), g_strdup(value->str));
+               g_string_free(value, TRUE);
+       }
+       slist_free_strings(concatlist);
+       g_slist_free(concatlist);
+
+       for (cur = convlist; cur != NULL; cur = g_slist_next(cur)) {
+               gchar *attribute, *key, *value;
+               gchar *charset, *lang, *oldvalue, *newvalue;
+
+               attribute = (gchar *) cur->data;
+               if (!g_hash_table_lookup_extended(
+                       table, attribute, (gpointer *)(gchar *) &key, (gpointer *)(gchar *) &value))
+                       continue;
+
+               charset = value;
+               lang = strchr(charset, '\'');
+               if (lang == NULL)
+                       continue;
+               lang[0] = '\0';
+               lang++;
+               oldvalue = strchr(lang, '\'');
+               if (oldvalue == NULL)
+                       continue;
+               oldvalue[0] = '\0';
+               oldvalue++;
+
+               newvalue = conv_codeset_strdup(oldvalue, charset, CS_UTF_8);
+
+               g_hash_table_remove(table, attribute);
+               g_free(key);
+               g_free(value);
+
+               g_hash_table_insert(table, g_strdup(attribute), newvalue);
        }
+       slist_free_strings(convlist);
+       g_slist_free(convlist);
+
+       g_free(params);
 }      
 
 static void procmime_parse_content_type(const gchar *content_type, MimeInfo *mimeinfo)
 {
-       gchar **content_type_parts;
-       gchar **strarray;
-       gchar *str;
-       struct TypeTable *typetablearray;
-       
        g_return_if_fail(content_type != NULL);
        g_return_if_fail(mimeinfo != NULL);
 
-       /* Split content type into parts and remove trailing
-          and leading whitespaces from all strings */
-       content_type_parts = g_strsplit(content_type, ";", 0);
-       for (strarray = content_type_parts; *strarray != NULL; strarray++) {
-               g_strstrip(*strarray);
-       }
-
-       /* Get mimeinfo->type and mimeinfo->subtype */
-       str = content_type_parts[0];
        /* RFC 2045, page 13 says that the mime subtype is MANDATORY;
         * if it's not available we use the default Content-Type */
-       if ((str == NULL) || (str[0] == '\0') || (strchr(str, '/') == NULL)) {
+       if ((content_type[0] == '\0') || (strchr(content_type, '/') == NULL)) {
                mimeinfo->type = MIMETYPE_TEXT;
                mimeinfo->subtype = g_strdup("plain");
-               if (g_hash_table_lookup(mimeinfo->parameters,
-                                      "charset") == NULL)
-                       g_hash_table_insert(mimeinfo->parameters,
-                                           g_strdup("charset"),
-                                           g_strdup("us-ascii"));
+               if (g_hash_table_lookup(mimeinfo->typeparameters,
+                                      "charset") == NULL) {
+                       g_hash_table_insert(mimeinfo->typeparameters,
+                                   g_strdup("charset"),
+                                   g_strdup(
+                                       conv_get_locale_charset_str_no_utf8()));
+               }
        } else {
-               mimeinfo->type = MIMETYPE_UNKNOWN;
-               for (typetablearray = mime_type_table; typetablearray->str != NULL; typetablearray++) {
-                       if (g_strncasecmp(str, typetablearray->str, strlen(typetablearray->str)) == 0 &&
-                           str[strlen(typetablearray->str)] == '/') {
-                               mimeinfo->type = typetablearray->type;
-                               mimeinfo->subtype = g_strdup(str + strlen(typetablearray->str) + 1);
-                               break;
-                       }
+               gchar *type, *subtype, *params;
+
+               type = g_strdup(content_type);
+               subtype = strchr(type, '/') + 1;
+               *(subtype - 1) = '\0';
+               if ((params = strchr(subtype, ';')) != NULL) {
+                       params[0] = '\0';
+                       params++;
                }
 
-               /* Get mimeinfo->parmeters */
-               add_to_mimeinfo_parameters(&content_type_parts[1], mimeinfo);
-       }
+               mimeinfo->type = procmime_get_media_type(type);
+               mimeinfo->subtype = g_strdup(subtype);
 
-       g_strfreev(content_type_parts);
+               /* Get mimeinfo->typeparameters */
+               if (params != NULL)
+                       parse_parameters(params, mimeinfo->typeparameters);
+
+               g_free(type);
+       }
 }
 
 static void procmime_parse_content_disposition(const gchar *content_disposition, MimeInfo *mimeinfo)
 {
-       gchar **content_disp_parts;
-       gchar **strarray;
-       gchar *str;
+       gchar *tmp, *params;
 
        g_return_if_fail(content_disposition != NULL);
        g_return_if_fail(mimeinfo != NULL);
 
-       /* Split into parts and remove trailing
-          and leading whitespaces from all strings */
-       content_disp_parts = g_strsplit(content_disposition, ";", 0);
-       for (strarray = content_disp_parts; *strarray != NULL; strarray++) {
-               g_strstrip(*strarray);
-       }
-       /* Get mimeinfo->disposition */
-       str = content_disp_parts[0];
-       if (str == NULL) {
-               g_strfreev(content_disp_parts);
-               return;
-       }
-       if (!g_strcasecmp(str, "inline")) 
+       tmp = g_strdup(content_disposition);
+       if ((params = strchr(tmp, ';')) != NULL) {
+               params[0] = '\0';
+               params++;
+       }       
+       g_strstrip(tmp);
+
+       if (!g_ascii_strcasecmp(tmp, "inline")) 
                mimeinfo->disposition = DISPOSITIONTYPE_INLINE;
-       else if (!g_strcasecmp(str, "attachment"))
+       else if (!g_ascii_strcasecmp(tmp, "attachment"))
                mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
        else
                mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
        
-       add_to_mimeinfo_parameters(&content_disp_parts[1], mimeinfo);
-       g_strfreev(content_disp_parts);
+       if (params != NULL)
+               parse_parameters(params, mimeinfo->dispositionparameters);
+
+       g_free(tmp);
 }
 
 
@@ -1240,7 +1722,7 @@ static void procmime_parse_content_encoding(const gchar *content_encoding, MimeI
        struct EncodingTable *enc_table;
        
        for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
-               if (g_strcasecmp(enc_table->str, content_encoding) == 0) {
+               if (g_ascii_strcasecmp(enc_table->str, content_encoding) == 0) {
                        mimeinfo->encoding_type = enc_table->enc_type;
                        return;
                }
@@ -1249,12 +1731,13 @@ static void procmime_parse_content_encoding(const gchar *content_encoding, MimeI
        return;
 }
 
-void procmime_parse_mimepart(MimeInfo *parent,
+static int procmime_parse_mimepart(MimeInfo *parent,
                             gchar *content_type,
                             gchar *content_encoding,
                             gchar *content_description,
                             gchar *content_id,
                             gchar *content_disposition,
+                            gchar *content_location,
                             const gchar *filename,
                             guint offset,
                             guint length)
@@ -1263,9 +1746,19 @@ void procmime_parse_mimepart(MimeInfo *parent,
 
        /* Create MimeInfo */
        mimeinfo = procmime_mimeinfo_new();
-       if (parent != NULL)
+       mimeinfo->content = MIMECONTENT_FILE;
+       if (parent != NULL) {
+               if (g_node_depth(parent->node) > 32) {
+                       /* 32 is an arbitrary value
+                        * this avoids DOSsing ourselves 
+                        * with enormous messages
+                        */
+                       procmime_mimeinfo_free_all(mimeinfo);
+                       return -1;                      
+               }
                g_node_append(parent->node, mimeinfo->node);
-       mimeinfo->filename = g_strdup(filename);
+       }
+       mimeinfo->data.filename = g_strdup(filename);
        mimeinfo->offset = offset;
        mimeinfo->length = length;
 
@@ -1274,15 +1767,19 @@ void procmime_parse_mimepart(MimeInfo *parent,
        } else {
                mimeinfo->type = MIMETYPE_TEXT;
                mimeinfo->subtype = g_strdup("plain");
-               if (g_hash_table_lookup(mimeinfo->parameters,
-                                      "charset") == NULL)
-                       g_hash_table_insert(mimeinfo->parameters, g_strdup("charset"), g_strdup("us-ascii"));
+               if (g_hash_table_lookup(mimeinfo->typeparameters,
+                                      "charset") == NULL) {
+                       g_hash_table_insert(mimeinfo->typeparameters,
+                                   g_strdup("charset"),
+                                   g_strdup(
+                                       conv_get_locale_charset_str_no_utf8()));
+               }
        }
 
        if (content_encoding != NULL) {
                procmime_parse_content_encoding(content_encoding, mimeinfo);
        } else {
-               mimeinfo->encoding_type = ENC_7BIT;
+               mimeinfo->encoding_type = ENC_UNKNOWN;
        }
 
        if (content_description != NULL)
@@ -1295,6 +1792,11 @@ void procmime_parse_mimepart(MimeInfo *parent,
        else
                mimeinfo->id = NULL;
 
+       if (content_location != NULL)
+               mimeinfo->location = g_strdup(content_location);
+       else
+               mimeinfo->location = NULL;
+
        if (content_disposition != NULL) 
                procmime_parse_content_disposition(content_disposition, mimeinfo);
        else
@@ -1303,7 +1805,7 @@ void procmime_parse_mimepart(MimeInfo *parent,
        /* Call parser for mime type */
        switch (mimeinfo->type) {
                case MIMETYPE_MESSAGE:
-                       if (g_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
+                       if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
                                procmime_parse_message_rfc822(mimeinfo);
                        }
                        break;
@@ -1315,6 +1817,8 @@ void procmime_parse_mimepart(MimeInfo *parent,
                default:
                        break;
        }
+
+       return 0;
 }
 
 static gchar *typenames[] = {
@@ -1346,7 +1850,7 @@ static void output_mime_structure(MimeInfo *mimeinfo, int indent)
        g_node_traverse(mimeinfo->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1, output_func, NULL);
 }
 
-static MimeInfo *procmime_scan_file_with_offset(const gchar *filename, int offset)
+MimeInfo *procmime_scan_file_with_offset(const gchar *filename, int offset)
 {
        MimeInfo *mimeinfo;
        struct stat buf;
@@ -1354,10 +1858,11 @@ static MimeInfo *procmime_scan_file_with_offset(const gchar *filename, int offse
        stat(filename, &buf);
 
        mimeinfo = procmime_mimeinfo_new();
-       mimeinfo->encoding_type = ENC_BINARY;
+       mimeinfo->content = MIMECONTENT_FILE;
+       mimeinfo->encoding_type = ENC_UNKNOWN;
        mimeinfo->type = MIMETYPE_MESSAGE;
        mimeinfo->subtype = g_strdup("rfc822");
-       mimeinfo->filename = g_strdup(filename);
+       mimeinfo->data.filename = g_strdup(filename);
        mimeinfo->offset = offset;
        mimeinfo->length = buf.st_size - offset;
 
@@ -1368,7 +1873,7 @@ static MimeInfo *procmime_scan_file_with_offset(const gchar *filename, int offse
        return mimeinfo;
 }
 
-MimeInfo *procmime_scan_file(gchar *filename)
+MimeInfo *procmime_scan_file(const gchar *filename)
 {
        MimeInfo *mimeinfo;
 
@@ -1379,7 +1884,7 @@ MimeInfo *procmime_scan_file(gchar *filename)
        return mimeinfo;
 }
 
-MimeInfo *procmime_scan_queue_file(gchar *filename)
+MimeInfo *procmime_scan_queue_file(const gchar *filename)
 {
        FILE *fp;
        MimeInfo *mimeinfo;
@@ -1389,11 +1894,25 @@ MimeInfo *procmime_scan_queue_file(gchar *filename)
        g_return_val_if_fail(filename != NULL, NULL);
 
        /* Open file */
-       if ((fp = fopen(filename, "rb")) == NULL)
+       if ((fp = g_fopen(filename, "rb")) == NULL)
                return NULL;
        /* Skip queue header */
-       while (fgets(buf, sizeof(buf), fp) != NULL)
+       while (fgets(buf, sizeof(buf), fp) != NULL) {
+               /* new way */
+               if (!strncmp(buf, "X-Sylpheed-End-Special-Headers: 1",
+                       strlen("X-Sylpheed-End-Special-Headers:")))
+                       break;
+               /* old way */
                if (buf[0] == '\r' || buf[0] == '\n') break;
+               /* from other mailers */
+               if (!strncmp(buf, "Date: ", 6)
+               ||  !strncmp(buf, "To: ", 4)
+               ||  !strncmp(buf, "From: ", 6)
+               ||  !strncmp(buf, "Subject: ", 9)) {
+                       rewind(fp);
+                       break;
+               }
+       }
        offset = ftell(fp);
        fclose(fp);
 
@@ -1401,3 +1920,375 @@ MimeInfo *procmime_scan_queue_file(gchar *filename)
 
        return mimeinfo;
 }
+
+typedef enum {
+    ENC_AS_TOKEN,
+    ENC_AS_QUOTED_STRING,
+    ENC_AS_EXTENDED,
+    ENC_TO_ASCII,
+} EncodeAs;
+
+typedef struct _ParametersData {
+       FILE *fp;
+       guint len;
+       guint ascii_only;
+} ParametersData;
+
+static void write_parameters(gpointer key, gpointer value, gpointer user_data)
+{
+       gchar *param = key;
+       gchar *val = value, *valpos, *tmp;
+       ParametersData *pdata = (ParametersData *)user_data;
+       GString *buf = g_string_new("");
+
+       EncodeAs encas = ENC_AS_TOKEN;
+
+       for (valpos = val; *valpos != 0; valpos++) {
+               if (!IS_ASCII(*valpos) || *valpos == '"') {
+                       encas = ENC_AS_EXTENDED;
+                       break;
+               }
+           
+               /* CTLs */
+               if (((*valpos >= 0) && (*valpos < 037)) || (*valpos == 0177)) {
+                       encas = ENC_AS_QUOTED_STRING;
+                       continue;
+               }
+
+               /* tspecials + SPACE */
+               switch (*valpos) {
+               case ' ':
+               case '(': 
+               case ')':
+               case '<':
+               case '>':
+               case '@':
+               case ',':
+               case ';':
+               case ':':
+               case '\\':
+               case '\'':
+               case '/':
+               case '[':
+               case ']':
+               case '?':
+               case '=':
+                       encas = ENC_AS_QUOTED_STRING;
+                       continue;
+               }
+       }
+       
+       if (encas == ENC_AS_EXTENDED && pdata->ascii_only == TRUE) 
+               encas = ENC_TO_ASCII;
+
+       switch (encas) {
+       case ENC_AS_TOKEN:
+               g_string_append_printf(buf, "%s=%s", param, val);
+               break;
+
+       case ENC_TO_ASCII:
+               tmp = g_strdup(val);
+               g_strcanon(tmp, 
+                       " ()<>@,';:\\/[]?=.0123456789"
+                       "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+                       "abcdefghijklmnopqrstuvwxyz",
+                       '_');
+               g_string_append_printf(buf, "%s=\"%s\"", param, tmp);
+               g_free(tmp);
+               break;
+
+       case ENC_AS_QUOTED_STRING:
+               g_string_append_printf(buf, "%s=\"%s\"", param, val);
+               break;
+
+       case ENC_AS_EXTENDED:
+               if (!g_utf8_validate(val, -1, NULL))
+                       g_string_append_printf(buf, "%s*=%s''", param,
+                               conv_get_locale_charset_str());
+               else
+                       g_string_append_printf(buf, "%s*=%s''", param,
+                               CS_INTERNAL);
+               for (valpos = val; *valpos != '\0'; valpos++) {
+                       if (IS_ASCII(*valpos) && isalnum(*valpos)) {
+                               g_string_append_printf(buf, "%c", *valpos);
+                       } else {
+                               gchar hexstr[3] = "XX";
+                               get_hex_str(hexstr, *valpos);
+                               g_string_append_printf(buf, "%%%s", hexstr);
+                       }
+               }
+               break;          
+       }
+       
+       if (buf->str && strlen(buf->str)) {
+               if (pdata->len + strlen(buf->str) + 2 > 76) {
+                       fprintf(pdata->fp, ";\n %s", buf->str);
+                       pdata->len = strlen(buf->str) + 1;
+               } else {
+                       fprintf(pdata->fp, "; %s", buf->str);
+                       pdata->len += strlen(buf->str) + 2;
+               }
+       }
+       g_string_free(buf, TRUE);
+}
+
+void procmime_write_mime_header(MimeInfo *mimeinfo, FILE *fp)
+{
+       struct TypeTable *type_table;
+       ParametersData *pdata = g_new0(ParametersData, 1);
+       debug_print("procmime_write_mime_header\n");
+       
+       pdata->fp = fp;
+       pdata->ascii_only = FALSE;
+
+       for (type_table = mime_type_table; type_table->str != NULL; type_table++)
+               if (mimeinfo->type == type_table->type) {
+                       gchar *buf = g_strdup_printf(
+                               "Content-Type: %s/%s", type_table->str, mimeinfo->subtype);
+                       fprintf(fp, "%s", buf);
+                       pdata->len = strlen(buf);
+                       pdata->ascii_only = TRUE;
+                       g_free(buf);
+                       break;
+               }
+       g_hash_table_foreach(mimeinfo->typeparameters, write_parameters, pdata);
+       g_free(pdata);
+
+       fprintf(fp, "\n");
+
+       if (mimeinfo->encoding_type != ENC_UNKNOWN)
+               fprintf(fp, "Content-Transfer-Encoding: %s\n", procmime_get_encoding_str(mimeinfo->encoding_type));
+
+       if (mimeinfo->description != NULL)
+               fprintf(fp, "Content-Description: %s\n", mimeinfo->description);
+
+       if (mimeinfo->id != NULL)
+               fprintf(fp, "Content-ID: %s\n", mimeinfo->id);
+
+       if (mimeinfo->location != NULL)
+               fprintf(fp, "Content-Location: %s\n", mimeinfo->location);
+
+       if (mimeinfo->disposition != DISPOSITIONTYPE_UNKNOWN) {
+               ParametersData *pdata = g_new0(ParametersData, 1);
+               gchar *buf = NULL;
+               if (mimeinfo->disposition == DISPOSITIONTYPE_INLINE)
+                       buf = g_strdup("Content-Disposition: inline");
+               else if (mimeinfo->disposition == DISPOSITIONTYPE_ATTACHMENT)
+                       buf = g_strdup("Content-Disposition: attachment");
+               else
+                       buf = g_strdup("Content-Disposition: unknown");
+
+               fprintf(fp, "%s", buf);
+               pdata->len = strlen(buf);
+               g_free(buf);
+
+               pdata->fp = fp;
+               pdata->ascii_only = FALSE;
+
+               g_hash_table_foreach(mimeinfo->dispositionparameters, write_parameters, pdata);
+               g_free(pdata);
+               fprintf(fp, "\n");
+       }
+
+       fprintf(fp, "\n");
+}
+
+gint procmime_write_message_rfc822(MimeInfo *mimeinfo, FILE *fp)
+{
+       FILE *infp;
+       GNode *childnode;
+       MimeInfo *child;
+       gchar buf[BUFFSIZE];
+       gboolean skip = FALSE;;
+
+       debug_print("procmime_write_message_rfc822\n");
+
+       /* write header */
+       switch (mimeinfo->content) {
+       case MIMECONTENT_FILE:
+               if ((infp = g_fopen(mimeinfo->data.filename, "rb")) == NULL) {
+                       FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
+                       return -1;
+               }
+               fseek(infp, mimeinfo->offset, SEEK_SET);
+               while (fgets(buf, sizeof(buf), infp) == buf) {
+                       if (buf[0] == '\n' && buf[1] == '\0')
+                               break;
+                       if (skip && (buf[0] == ' ' || buf[0] == '\t'))
+                               continue;
+                       if (g_ascii_strncasecmp(buf, "Mime-Version:", 13) == 0 ||
+                           g_ascii_strncasecmp(buf, "Content-Type:", 13) == 0 ||
+                           g_ascii_strncasecmp(buf, "Content-Transfer-Encoding:", 26) == 0 ||
+                           g_ascii_strncasecmp(buf, "Content-Description:", 20) == 0 ||
+                           g_ascii_strncasecmp(buf, "Content-ID:", 11) == 0 ||
+                           g_ascii_strncasecmp(buf, "Content-Location:", 17) == 0 ||
+                           g_ascii_strncasecmp(buf, "Content-Disposition:", 20) == 0) {
+                               skip = TRUE;
+                               continue;
+                       }
+                       fwrite(buf, sizeof(gchar), strlen(buf), fp);
+                       skip = FALSE;
+               }
+               fclose(infp);
+               break;
+
+       case MIMECONTENT_MEM:
+               fwrite(mimeinfo->data.mem, 
+                               sizeof(gchar), 
+                               strlen(mimeinfo->data.mem), 
+                               fp);
+               break;
+
+       default:
+               break;
+       }
+
+       childnode = mimeinfo->node->children;
+       if (childnode == NULL)
+               return -1;
+
+       child = (MimeInfo *) childnode->data;
+       fprintf(fp, "Mime-Version: 1.0\n");
+       procmime_write_mime_header(child, fp);
+       return procmime_write_mimeinfo(child, fp);
+}
+
+gint procmime_write_multipart(MimeInfo *mimeinfo, FILE *fp)
+{
+       FILE *infp;
+       GNode *childnode;
+       gchar *boundary, *str, *str2;
+       gchar buf[BUFFSIZE];
+       gboolean firstboundary;
+
+       debug_print("procmime_write_multipart\n");
+
+       boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
+
+       switch (mimeinfo->content) {
+       case MIMECONTENT_FILE:
+               if ((infp = g_fopen(mimeinfo->data.filename, "rb")) == NULL) {
+                       FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
+                       return -1;
+               }
+               fseek(infp, mimeinfo->offset, SEEK_SET);
+               while (fgets(buf, sizeof(buf), infp) == buf) {
+                       if (IS_BOUNDARY(buf, boundary, strlen(boundary)))
+                               break;
+                       fwrite(buf, sizeof(gchar), strlen(buf), fp);
+               }
+               fclose(infp);
+               break;
+
+       case MIMECONTENT_MEM:
+               str = g_strdup(mimeinfo->data.mem);
+               if (((str2 = strstr(str, boundary)) != NULL) && ((str2 - str) >= 2) &&
+                   (*(str2 - 1) == '-') && (*(str2 - 2) == '-'))
+                       *(str2 - 2) = '\0';
+               fwrite(str, sizeof(gchar), strlen(str), fp);
+               g_free(str);
+               break;
+
+       default:
+               break;
+       }
+
+       childnode = mimeinfo->node->children;
+       firstboundary = TRUE;
+       while (childnode != NULL) {
+               MimeInfo *child = childnode->data;
+
+               if (firstboundary)
+                       firstboundary = FALSE;
+               else
+                       fprintf(fp, "\n");
+               fprintf(fp, "--%s\n", boundary);
+
+               procmime_write_mime_header(child, fp);
+               if (procmime_write_mimeinfo(child, fp) < 0)
+                       return -1;
+
+               childnode = g_node_next_sibling(childnode);
+       }       
+       fprintf(fp, "\n--%s--\n", boundary);
+
+       return 0;
+}
+
+gint procmime_write_mimeinfo(MimeInfo *mimeinfo, FILE *fp)
+{
+       FILE *infp;
+
+       debug_print("procmime_write_mimeinfo\n");
+
+       if (G_NODE_IS_LEAF(mimeinfo->node)) {
+               switch (mimeinfo->content) {
+               case MIMECONTENT_FILE:
+                       if ((infp = g_fopen(mimeinfo->data.filename, "rb")) == NULL) {
+                               FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
+                               return -1;
+                       }
+                       copy_file_part_to_fp(infp, mimeinfo->offset, mimeinfo->length, fp);
+                       fclose(infp);
+                       return 0;
+
+               case MIMECONTENT_MEM:
+                       fwrite(mimeinfo->data.mem, 
+                                       sizeof(gchar), 
+                                       strlen(mimeinfo->data.mem), 
+                                       fp);
+                       return 0;
+
+               default:
+                       return 0;
+               }
+       } else {
+               /* Call writer for mime type */
+               switch (mimeinfo->type) {
+               case MIMETYPE_MESSAGE:
+                       if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
+                               return procmime_write_message_rfc822(mimeinfo, fp);
+                       }
+                       break;
+                       
+               case MIMETYPE_MULTIPART:
+                       return procmime_write_multipart(mimeinfo, fp);
+                       
+               default:
+                       break;
+               }
+
+               return -1;
+       }
+
+       return 0;
+}
+
+gchar *procmime_get_part_file_name(MimeInfo *mimeinfo)
+{
+       gchar *base;
+
+       if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
+               base = g_strdup("mimetmp.html");
+       else {
+               const gchar *basetmp;
+               gchar *basename;
+
+               basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
+               if (basetmp == NULL)
+                       basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
+               if (basetmp == NULL)
+                       basetmp = "mimetmp";
+               basename = g_path_get_basename(basetmp);
+               if (*basename == '\0') {
+                       g_free(basename);
+                       basename = g_strdup("mimetmp");
+               }
+               base = conv_filename_from_utf8(basename);
+               g_free(basename);
+               subst_for_shellsafe_filename(base);
+       }
+       
+       return base;
+}
+