72602898dbc56558c19872ac8974361c4bcfc7ce
[claws.git] / src / procmime.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2006 Hiroyuki Yamamoto & The Sylpheed-Claws Team
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include "defs.h"
25
26 #include <stdio.h>
27 #include <glib.h>
28 #include <glib/gi18n.h>
29 #include <stdio.h>
30 #include <string.h>
31 #if HAVE_LOCALE_H
32 #  include <locale.h>
33 #endif
34 #include <ctype.h>
35 #include <sys/types.h>
36 #include <sys/stat.h>
37 #include <unistd.h>
38
39 #include "procmime.h"
40 #include "procheader.h"
41 #include "base64.h"
42 #include "quoted-printable.h"
43 #include "uuencode.h"
44 #include "unmime.h"
45 #include "html.h"
46 #include "enriched.h"
47 #include "codeconv.h"
48 #include "utils.h"
49 #include "prefs_common.h"
50 #include "prefs_gtk.h"
51
52 static GHashTable *procmime_get_mime_type_table (void);
53
54 MimeInfo *procmime_mimeinfo_new(void)
55 {
56         MimeInfo *mimeinfo;
57
58         mimeinfo = g_new0(MimeInfo, 1);
59         mimeinfo->content        = MIMECONTENT_EMPTY;
60         mimeinfo->data.filename  = NULL;
61
62         mimeinfo->type           = MIMETYPE_UNKNOWN;
63         mimeinfo->encoding_type  = ENC_UNKNOWN;
64         mimeinfo->typeparameters = g_hash_table_new(g_str_hash, g_str_equal);
65
66         mimeinfo->disposition    = DISPOSITIONTYPE_UNKNOWN;
67         mimeinfo->dispositionparameters 
68                                  = g_hash_table_new(g_str_hash, g_str_equal);
69
70         mimeinfo->node           = g_node_new(mimeinfo);
71         
72         return mimeinfo;
73 }
74
75 static gboolean procmime_mimeinfo_parameters_destroy(gpointer key, gpointer value, gpointer user_data)
76 {
77         g_free(key);
78         g_free(value);
79         
80         return TRUE;
81 }
82
83 static gchar *forced_charset = NULL;
84
85 void procmime_force_charset(const gchar *str)
86 {
87         g_free(forced_charset);
88         forced_charset = NULL;
89         if (str)
90                 forced_charset = g_strdup(str);
91 }
92
93 static EncodingType forced_encoding = 0;
94
95 void procmime_force_encoding(EncodingType encoding)
96 {
97         forced_encoding = encoding;
98 }
99
100 static gboolean free_func(GNode *node, gpointer data)
101 {
102         MimeInfo *mimeinfo = (MimeInfo *) node->data;
103
104         switch (mimeinfo->content) {
105         case MIMECONTENT_FILE:
106                 if (mimeinfo->tmp)
107                         g_unlink(mimeinfo->data.filename);
108                 g_free(mimeinfo->data.filename);
109                 break;
110
111         case MIMECONTENT_MEM:
112                 if (mimeinfo->tmp)
113                         g_free(mimeinfo->data.mem);
114         default:
115                 break;
116         }
117
118         g_free(mimeinfo->subtype);
119         g_free(mimeinfo->description);
120         g_free(mimeinfo->id);
121         g_free(mimeinfo->location);
122
123         g_hash_table_foreach_remove(mimeinfo->typeparameters,
124                 procmime_mimeinfo_parameters_destroy, NULL);
125         g_hash_table_destroy(mimeinfo->typeparameters);
126         g_hash_table_foreach_remove(mimeinfo->dispositionparameters,
127                 procmime_mimeinfo_parameters_destroy, NULL);
128         g_hash_table_destroy(mimeinfo->dispositionparameters);
129
130         if (mimeinfo->privacy)
131                 privacy_free_privacydata(mimeinfo->privacy);
132
133         g_free(mimeinfo);
134
135         return FALSE;
136 }
137
138 void procmime_mimeinfo_free_all(MimeInfo *mimeinfo)
139 {
140         GNode *node;
141
142         if (!mimeinfo)
143                 return;
144
145         node = mimeinfo->node;
146         g_node_traverse(node, G_IN_ORDER, G_TRAVERSE_ALL, -1, free_func, NULL);
147
148         g_node_destroy(node);
149 }
150
151 MimeInfo *procmime_mimeinfo_parent(MimeInfo *mimeinfo)
152 {
153         g_return_val_if_fail(mimeinfo != NULL, NULL);
154         g_return_val_if_fail(mimeinfo->node != NULL, NULL);
155
156         if (mimeinfo->node->parent == NULL)
157                 return NULL;
158         return (MimeInfo *) mimeinfo->node->parent->data;
159 }
160
161 MimeInfo *procmime_mimeinfo_next(MimeInfo *mimeinfo)
162 {
163         g_return_val_if_fail(mimeinfo != NULL, NULL);
164         g_return_val_if_fail(mimeinfo->node != NULL, NULL);
165
166         if (mimeinfo->node->children)
167                 return (MimeInfo *) mimeinfo->node->children->data;
168         if (mimeinfo->node->next)
169                 return (MimeInfo *) mimeinfo->node->next->data;
170
171         if (mimeinfo->node->parent == NULL)
172                 return NULL;
173
174         while (mimeinfo->node->parent != NULL) {
175                 mimeinfo = (MimeInfo *) mimeinfo->node->parent->data;
176                 if (mimeinfo->node->next)
177                         return (MimeInfo *) mimeinfo->node->next->data;
178         }
179
180         return NULL;
181 }
182
183 MimeInfo *procmime_scan_message(MsgInfo *msginfo)
184 {
185         gchar *filename;
186         MimeInfo *mimeinfo;
187
188         filename = procmsg_get_message_file_path(msginfo);
189         if (!filename || !is_file_exist(filename)) {
190                 g_free(filename);
191                 filename = procmsg_get_message_file(msginfo);
192         }
193         if (!filename || !is_file_exist(filename)) 
194                 return NULL;
195
196         if (!folder_has_parent_of_type(msginfo->folder, F_QUEUE) &&
197             !folder_has_parent_of_type(msginfo->folder, F_DRAFT))
198                 mimeinfo = procmime_scan_file(filename);
199         else
200                 mimeinfo = procmime_scan_queue_file(filename);
201         g_free(filename);
202
203         return mimeinfo;
204 }
205
206 enum
207 {
208         H_CONTENT_TRANSFER_ENCODING = 0,
209         H_CONTENT_TYPE              = 1,
210         H_CONTENT_DISPOSITION       = 2,
211         H_CONTENT_DESCRIPTION       = 3,
212         H_SUBJECT                   = 4
213 };
214
215 const gchar *procmime_mimeinfo_get_parameter(MimeInfo *mimeinfo, const gchar *name)
216 {
217         const gchar *value;
218
219         g_return_val_if_fail(mimeinfo != NULL, NULL);
220         g_return_val_if_fail(name != NULL, NULL);
221
222         value = g_hash_table_lookup(mimeinfo->dispositionparameters, name);
223         if (value == NULL)
224                 value = g_hash_table_lookup(mimeinfo->typeparameters, name);
225         
226         return value;
227 }
228
229 gboolean procmime_decode_content(MimeInfo *mimeinfo)
230 {
231         gchar buf[BUFFSIZE];
232         gint readend;
233         gchar *tmpfilename;
234         FILE *outfp, *infp;
235         struct stat statbuf;
236         gboolean tmp_file = FALSE;
237
238         EncodingType encoding = forced_encoding 
239                                 ? forced_encoding
240                                 : mimeinfo->encoding_type;
241                    
242         g_return_val_if_fail(mimeinfo != NULL, FALSE);
243
244         if (encoding == ENC_UNKNOWN ||
245             encoding == ENC_BINARY)
246                 return TRUE;
247
248         infp = g_fopen(mimeinfo->data.filename, "rb");
249         if (!infp) {
250                 perror("fopen");
251                 return FALSE;
252         }
253         fseek(infp, mimeinfo->offset, SEEK_SET);
254
255         outfp = get_tmpfile_in_dir(get_mime_tmp_dir(), &tmpfilename);
256         if (!outfp) {
257                 perror("tmpfile");
258                 fclose(infp);
259                 return FALSE;
260         }
261         tmp_file = TRUE;
262         readend = mimeinfo->offset + mimeinfo->length;
263
264         if (encoding == ENC_QUOTED_PRINTABLE) {
265                 while ((ftell(infp) < readend) && (fgets(buf, sizeof(buf), infp) != NULL)) {
266                         gint len;
267                         len = qp_decode_line(buf);
268                         fwrite(buf, 1, len, outfp);
269                 }
270         } else if (encoding == ENC_BASE64) {
271                 gchar outbuf[BUFFSIZE];
272                 gint len;
273                 Base64Decoder *decoder;
274                 gboolean got_error = FALSE;
275                 gboolean uncanonicalize = FALSE;
276                 FILE *tmpfp = outfp;
277
278                 if (mimeinfo->type == MIMETYPE_TEXT ||
279                     mimeinfo->type == MIMETYPE_MESSAGE) {
280                         uncanonicalize = TRUE;
281                         tmpfp = my_tmpfile();
282                         if (!tmpfp) {
283                                 perror("tmpfile");
284                                 if (tmp_file) fclose(outfp);
285                                 fclose(infp);
286                                 return FALSE;
287                         }
288                 }
289
290                 decoder = base64_decoder_new();
291                 while ((ftell(infp) < readend) && (fgets(buf, sizeof(buf), infp) != NULL)) {
292                         len = base64_decoder_decode(decoder, buf, outbuf);
293                         if (len < 0 && !got_error) {
294                                 g_warning("Bad BASE64 content.\n");
295                                 fwrite(_("[Error decoding BASE64]\n"),
296                                         sizeof(gchar),
297                                         strlen(_("[Error decoding BASE64]\n")),
298                                         tmpfp);
299                                 got_error = TRUE;
300                                 continue;
301                         } else if (len >= 0) {
302                                 /* print out the error message only once 
303                                  * per block */
304                                 fwrite(outbuf, sizeof(gchar), len, tmpfp);
305                                 got_error = FALSE;
306                         }
307                 }
308                 base64_decoder_free(decoder);
309
310                 if (uncanonicalize) {
311                         rewind(tmpfp);
312                         while (fgets(buf, sizeof(buf), tmpfp) != NULL) {
313                                 strcrchomp(buf);
314                                 fputs(buf, outfp);
315                         }
316                         fclose(tmpfp);
317                 }
318         } else if (encoding == ENC_X_UUENCODE) {
319                 gchar outbuf[BUFFSIZE];
320                 gint len;
321                 gboolean flag = FALSE;
322
323                 while ((ftell(infp) < readend) && (fgets(buf, sizeof(buf), infp) != NULL)) {
324                         if (!flag && strncmp(buf,"begin ", 6)) continue;
325
326                         if (flag) {
327                                 len = fromuutobits(outbuf, buf);
328                                 if (len <= 0) {
329                                         if (len < 0) 
330                                                 g_warning("Bad UUENCODE content(%d)\n", len);
331                                         break;
332                                 }
333                                 fwrite(outbuf, sizeof(gchar), len, outfp);
334                         } else
335                                 flag = TRUE;
336                 }
337         } else {
338                 while ((ftell(infp) < readend) && (fgets(buf, sizeof(buf), infp) != NULL)) {
339                         fputs(buf, outfp);
340                 }
341         }
342
343         fclose(outfp);
344         fclose(infp);
345
346         stat(tmpfilename, &statbuf);
347         if (mimeinfo->tmp && (mimeinfo->data.filename != NULL))
348                 g_unlink(mimeinfo->data.filename);
349         if (mimeinfo->data.filename != NULL)
350                 g_free(mimeinfo->data.filename);
351         mimeinfo->data.filename = tmpfilename;
352         mimeinfo->tmp = TRUE;
353         mimeinfo->offset = 0;
354         mimeinfo->length = statbuf.st_size;
355         mimeinfo->encoding_type = ENC_BINARY;
356
357         return TRUE;
358 }
359
360 #define B64_LINE_SIZE           57
361 #define B64_BUFFSIZE            77
362
363 gboolean procmime_encode_content(MimeInfo *mimeinfo, EncodingType encoding)
364 {
365         FILE *infp = NULL, *outfp;
366         gint len;
367         gchar *tmpfilename;
368         struct stat statbuf;
369
370         if (mimeinfo->content == MIMECONTENT_EMPTY)
371                 return TRUE;
372
373         if (mimeinfo->encoding_type != ENC_UNKNOWN &&
374             mimeinfo->encoding_type != ENC_BINARY &&
375             mimeinfo->encoding_type != ENC_7BIT &&
376             mimeinfo->encoding_type != ENC_8BIT)
377                 if(!procmime_decode_content(mimeinfo))
378                         return FALSE;
379
380         outfp = get_tmpfile_in_dir(get_mime_tmp_dir(), &tmpfilename);
381         if (!outfp) {
382                 perror("tmpfile");
383                 return FALSE;
384         }
385
386         if (mimeinfo->content == MIMECONTENT_FILE) {
387                 if ((infp = g_fopen(mimeinfo->data.filename, "rb")) == NULL) {
388                         g_warning("Can't open file %s\n", mimeinfo->data.filename);
389                         return FALSE;
390                 }
391         } else if (mimeinfo->content == MIMECONTENT_MEM) {
392                 infp = str_open_as_stream(mimeinfo->data.mem);
393                 if (infp == NULL)
394                         return FALSE;
395         }
396
397         if (encoding == ENC_BASE64) {
398                 gchar inbuf[B64_LINE_SIZE], outbuf[B64_BUFFSIZE];
399                 FILE *tmp_fp = infp;
400                 gchar *tmp_file = NULL;
401
402                 if (mimeinfo->type == MIMETYPE_TEXT ||
403                      mimeinfo->type == MIMETYPE_MESSAGE) {
404                         if (mimeinfo->content == MIMECONTENT_FILE) {
405                                 tmp_file = get_tmp_file();
406                                 if (canonicalize_file(mimeinfo->data.filename, tmp_file) < 0) {
407                                         g_free(tmp_file);
408                                         fclose(infp);
409                                         return FALSE;
410                                 }
411                                 if ((tmp_fp = g_fopen(tmp_file, "rb")) == NULL) {
412                                         FILE_OP_ERROR(tmp_file, "fopen");
413                                         g_unlink(tmp_file);
414                                         g_free(tmp_file);
415                                         fclose(infp);
416                                         return FALSE;
417                                 }
418                         } else {
419                                 gchar *out = canonicalize_str(mimeinfo->data.mem);
420                                 fclose(infp);
421                                 infp = str_open_as_stream(out);
422                                 tmp_fp = infp;
423                                 g_free(out);
424                                 if (infp == NULL)
425                                         return FALSE;
426                         }
427                 }
428
429                 while ((len = fread(inbuf, sizeof(gchar),
430                                     B64_LINE_SIZE, tmp_fp))
431                        == B64_LINE_SIZE) {
432                         base64_encode(outbuf, inbuf, B64_LINE_SIZE);
433                         fputs(outbuf, outfp);
434                         fputc('\n', outfp);
435                 }
436                 if (len > 0 && feof(tmp_fp)) {
437                         base64_encode(outbuf, inbuf, len);
438                         fputs(outbuf, outfp);
439                         fputc('\n', outfp);
440                 }
441
442                 if (tmp_file) {
443                         fclose(tmp_fp);
444                         g_unlink(tmp_file);
445                         g_free(tmp_file);
446                 }
447         } else if (encoding == ENC_QUOTED_PRINTABLE) {
448                 gchar inbuf[BUFFSIZE], outbuf[BUFFSIZE * 4];
449
450                 while (fgets(inbuf, sizeof(inbuf), infp) != NULL) {
451                         qp_encode_line(outbuf, inbuf);
452
453                         if (!strncmp("From ", outbuf, sizeof("From ")-1)) {
454                                 gchar *tmpbuf = outbuf;
455                                 
456                                 tmpbuf += sizeof("From ")-1;
457                                 
458                                 fputs("=46rom ", outfp);
459                                 fputs(tmpbuf, outfp);
460                         } else 
461                                 fputs(outbuf, outfp);
462                 }
463         } else {
464                 gchar buf[BUFFSIZE];
465
466                 while (fgets(buf, sizeof(buf), infp) != NULL) {
467                         strcrchomp(buf);
468                         fputs(buf, outfp);
469                 }
470         }
471
472         fclose(outfp);
473         fclose(infp);
474
475         if (mimeinfo->content == MIMECONTENT_FILE) {
476                 if (mimeinfo->tmp && (mimeinfo->data.filename != NULL))
477                         g_unlink(mimeinfo->data.filename);
478                 g_free(mimeinfo->data.filename);
479         } else if (mimeinfo->content == MIMECONTENT_MEM) {
480                 if (mimeinfo->tmp && (mimeinfo->data.mem != NULL))
481                         g_free(mimeinfo->data.mem);
482         }
483
484         stat(tmpfilename, &statbuf);
485         mimeinfo->content = MIMECONTENT_FILE;
486         mimeinfo->data.filename = tmpfilename;
487         mimeinfo->tmp = TRUE;
488         mimeinfo->offset = 0;
489         mimeinfo->length = statbuf.st_size;
490         mimeinfo->encoding_type = encoding;
491
492         return TRUE;
493 }
494
495 gint procmime_get_part(const gchar *outfile, MimeInfo *mimeinfo)
496 {
497         FILE *infp, *outfp;
498         gchar buf[BUFFSIZE];
499         gint restlength, readlength;
500
501         g_return_val_if_fail(outfile != NULL, -1);
502         g_return_val_if_fail(mimeinfo != NULL, -1);
503
504         if (mimeinfo->encoding_type != ENC_BINARY && !procmime_decode_content(mimeinfo))
505                 return -1;
506
507         if ((infp = g_fopen(mimeinfo->data.filename, "rb")) == NULL) {
508                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
509                 return -1;
510         }
511         if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
512                 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
513                 fclose(infp);
514                 return -1;
515         }
516         if ((outfp = g_fopen(outfile, "wb")) == NULL) {
517                 FILE_OP_ERROR(outfile, "fopen");
518                 fclose(infp);
519                 return -1;
520         }
521
522         restlength = mimeinfo->length;
523
524         while ((restlength > 0) && ((readlength = fread(buf, 1, restlength > BUFFSIZE ? BUFFSIZE : restlength, infp)) > 0)) {
525                 fwrite(buf, 1, readlength, outfp);
526                 restlength -= readlength;
527         }
528
529         fclose(infp);
530         if (fclose(outfp) == EOF) {
531                 FILE_OP_ERROR(outfile, "fclose");
532                 g_unlink(outfile);
533                 return -1;
534         }
535
536         return 0;
537 }
538
539 struct ContentRenderer {
540         char * content_type;
541         char * renderer;
542 };
543
544 static GList * renderer_list = NULL;
545
546 static struct ContentRenderer *
547 content_renderer_new(char * content_type, char * renderer)
548 {
549         struct ContentRenderer * cr;
550
551         cr = g_new(struct ContentRenderer, 1);
552         if (cr == NULL)
553                 return NULL;
554
555         cr->content_type = g_strdup(content_type);
556         cr->renderer = g_strdup(renderer);
557
558         return cr;
559 }
560
561 static void content_renderer_free(struct ContentRenderer * cr)
562 {
563         g_free(cr->content_type);
564         g_free(cr->renderer);
565         g_free(cr);
566 }
567
568 void renderer_read_config(void)
569 {
570         gchar buf[BUFFSIZE];
571         FILE * f;
572         gchar * rcpath;
573
574         g_list_foreach(renderer_list, (GFunc) content_renderer_free, NULL);
575         renderer_list = NULL;
576
577         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, RENDERER_RC, NULL);
578         f = g_fopen(rcpath, "rb");
579         g_free(rcpath);
580         
581         if (f == NULL)
582                 return;
583
584         while (fgets(buf, BUFFSIZE, f)) {
585                 char * p;
586                 struct ContentRenderer * cr;
587
588                 strretchomp(buf);
589                 p = strchr(buf, ' ');
590                 if (p == NULL)
591                         continue;
592                 * p = 0;
593
594                 cr = content_renderer_new(buf, p + 1);
595                 if (cr == NULL)
596                         continue;
597
598                 renderer_list = g_list_append(renderer_list, cr);
599         }
600
601         fclose(f);
602 }
603
604 void renderer_write_config(void)
605 {
606         gchar * rcpath;
607         PrefFile *pfile;
608         GList * cur;
609
610         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, RENDERER_RC, NULL);
611         
612         if ((pfile = prefs_write_open(rcpath)) == NULL) {
613                 g_warning("failed to write configuration to file\n");
614                 g_free(rcpath);
615                 return;
616         }
617
618         g_free(rcpath);
619
620         for (cur = renderer_list ; cur != NULL ; cur = cur->next) {
621                 struct ContentRenderer * renderer;
622                 renderer = cur->data;
623                 fprintf(pfile->fp, "%s %s\n", renderer->content_type,
624                         renderer->renderer);
625         }
626
627         if (prefs_file_close(pfile) < 0) {
628                 g_warning("failed to write configuration to file\n");
629                 return;
630         }
631 }
632
633 FILE *procmime_get_text_content(MimeInfo *mimeinfo)
634 {
635         FILE *tmpfp, *outfp;
636         const gchar *src_codeset;
637         gboolean conv_fail = FALSE;
638         gchar buf[BUFFSIZE];
639         gchar *str;
640         struct ContentRenderer * renderer;
641         GList * cur;
642         gchar *tmpfile, *content_type;
643     
644         g_return_val_if_fail(mimeinfo != NULL, NULL);
645
646         if (!procmime_decode_content(mimeinfo))
647                 return NULL;
648
649         tmpfile = procmime_get_tmp_file_name(mimeinfo);
650         if (tmpfile == NULL)
651                 return NULL;
652
653         if (procmime_get_part(tmpfile, mimeinfo) < 0) {
654                 g_free(tmpfile);
655                 return NULL;
656         }
657
658         tmpfp = g_fopen(tmpfile, "rb");
659         if (tmpfp == NULL) {
660                 g_free(tmpfile);
661                 return NULL;
662         }
663
664         if ((outfp = my_tmpfile()) == NULL) {
665                 perror("tmpfile");
666                 fclose(tmpfp);
667                 g_free(tmpfile);
668                 return NULL;
669         }
670
671         src_codeset = forced_charset
672                       ? forced_charset : 
673                       procmime_mimeinfo_get_parameter(mimeinfo, "charset");
674
675         renderer = NULL;
676
677         content_type = procmime_get_content_type_str(mimeinfo->type,
678                                                      mimeinfo->subtype);
679         for (cur = renderer_list ; cur != NULL ; cur = cur->next) {
680                 struct ContentRenderer * cr;
681
682                 cr = cur->data;
683                 if (g_ascii_strcasecmp(cr->content_type, content_type) == 0) {
684                         renderer = cr;
685                         break;
686                 }
687         }
688         g_free(content_type);
689
690         if (renderer != NULL) {
691                 FILE * p;
692                 int oldout;
693                 
694                 oldout = dup(1);
695                 
696                 dup2(fileno(outfp), 1);
697
698                 p = popen(renderer->renderer, "w");
699                 if (p != NULL) {
700                         size_t count;
701                         
702                         while ((count =
703                                 fread(buf, sizeof(char), sizeof(buf),
704                                       tmpfp)) > 0)
705                                 fwrite(buf, sizeof(char), count, p);
706                         pclose(p);
707                 }
708                 
709                 dup2(oldout, 1);
710 /* CodeConverter seems to have no effect here */
711         } else if (mimeinfo->type == MIMETYPE_TEXT && !g_ascii_strcasecmp(mimeinfo->subtype, "html")) {
712                 SC_HTMLParser *parser;
713                 CodeConverter *conv;
714
715                 conv = conv_code_converter_new(src_codeset);
716                 parser = sc_html_parser_new(tmpfp, conv);
717                 while ((str = sc_html_parse(parser)) != NULL) {
718                         fputs(str, outfp);
719                 }
720                 sc_html_parser_destroy(parser);
721                 conv_code_converter_destroy(conv);
722         } else if (mimeinfo->type == MIMETYPE_TEXT && !g_ascii_strcasecmp(mimeinfo->subtype, "enriched")) {
723                 ERTFParser *parser;
724                 CodeConverter *conv;
725
726                 conv = conv_code_converter_new(src_codeset);
727                 parser = ertf_parser_new(tmpfp, conv);
728                 while ((str = ertf_parse(parser)) != NULL) {
729                         fputs(str, outfp);
730                 }
731                 ertf_parser_destroy(parser);
732                 conv_code_converter_destroy(conv);
733         } else if (mimeinfo->type == MIMETYPE_TEXT) {
734                 while (fgets(buf, sizeof(buf), tmpfp) != NULL) {
735                         str = conv_codeset_strdup(buf, src_codeset, CS_UTF_8);
736                         if (str) {
737                                 fputs(str, outfp);
738                                 g_free(str);
739                         } else {
740                                 conv_fail = TRUE;
741                                 fputs(buf, outfp);
742                         }
743                 }
744         }
745
746         if (conv_fail)
747                 g_warning("procmime_get_text_content(): Code conversion failed.\n");
748
749         fclose(tmpfp);
750         rewind(outfp);
751         g_unlink(tmpfile);
752         g_free(tmpfile);
753
754         return outfp;
755 }
756
757 /* search the first text part of (multipart) MIME message,
758    decode, convert it and output to outfp. */
759 FILE *procmime_get_first_text_content(MsgInfo *msginfo)
760 {
761         FILE *outfp = NULL;
762         MimeInfo *mimeinfo, *partinfo;
763
764         g_return_val_if_fail(msginfo != NULL, NULL);
765
766         mimeinfo = procmime_scan_message(msginfo);
767         if (!mimeinfo) return NULL;
768
769         partinfo = mimeinfo;
770         while (partinfo && partinfo->type != MIMETYPE_TEXT) {
771                 partinfo = procmime_mimeinfo_next(partinfo);
772         }
773         if (partinfo)
774                 outfp = procmime_get_text_content(partinfo);
775
776         procmime_mimeinfo_free_all(mimeinfo);
777
778         return outfp;
779 }
780
781
782 static gboolean find_encrypted_func(GNode *node, gpointer data)
783 {
784         MimeInfo *mimeinfo = (MimeInfo *) node->data;
785         MimeInfo **encinfo = (MimeInfo **) data;
786         
787         if (privacy_mimeinfo_is_encrypted(mimeinfo)) {
788                 *encinfo = mimeinfo;
789                 return TRUE;
790         }
791         
792         return FALSE;
793 }
794
795 static MimeInfo *find_encrypted_part(MimeInfo *rootinfo)
796 {
797         MimeInfo *encinfo = NULL;
798
799         g_node_traverse(rootinfo->node, G_IN_ORDER, G_TRAVERSE_ALL, -1,
800                 find_encrypted_func, &encinfo);
801         
802         return encinfo;
803 }
804
805 /* search the first encrypted text part of (multipart) MIME message,
806    decode, convert it and output to outfp. */
807 FILE *procmime_get_first_encrypted_text_content(MsgInfo *msginfo)
808 {
809         FILE *outfp = NULL;
810         MimeInfo *mimeinfo, *partinfo, *encinfo;
811
812         g_return_val_if_fail(msginfo != NULL, NULL);
813
814         mimeinfo = procmime_scan_message(msginfo);
815         if (!mimeinfo) {
816                 return NULL;
817         }
818
819         partinfo = mimeinfo;
820         if ((encinfo = find_encrypted_part(partinfo)) != NULL) {
821                 debug_print("decrypting message part\n");
822                 if (privacy_mimeinfo_decrypt(encinfo) < 0)
823                         return NULL;
824         }
825         partinfo = mimeinfo;
826         while (partinfo && partinfo->type != MIMETYPE_TEXT) {
827                 partinfo = procmime_mimeinfo_next(partinfo);
828         }
829
830         if (partinfo)
831                 outfp = procmime_get_text_content(partinfo);
832
833         procmime_mimeinfo_free_all(mimeinfo);
834
835         return outfp;
836 }
837
838 gboolean procmime_msginfo_is_encrypted(MsgInfo *msginfo)
839 {
840         MimeInfo *mimeinfo, *partinfo;
841         gboolean result = FALSE;
842
843         g_return_val_if_fail(msginfo != NULL, FALSE);
844
845         mimeinfo = procmime_scan_message(msginfo);
846         if (!mimeinfo) {
847                 return FALSE;
848         }
849
850         partinfo = mimeinfo;
851         result = (find_encrypted_part(partinfo) != NULL);
852         procmime_mimeinfo_free_all(mimeinfo);
853
854         return result;
855 }
856
857 gboolean procmime_find_string_part(MimeInfo *mimeinfo, const gchar *filename,
858                                    const gchar *str, StrFindFunc find_func)
859 {
860         FILE *outfp;
861         gchar buf[BUFFSIZE];
862
863         g_return_val_if_fail(mimeinfo != NULL, FALSE);
864         g_return_val_if_fail(mimeinfo->type == MIMETYPE_TEXT, FALSE);
865         g_return_val_if_fail(str != NULL, FALSE);
866         g_return_val_if_fail(find_func != NULL, FALSE);
867
868         outfp = procmime_get_text_content(mimeinfo);
869
870         if (!outfp)
871                 return FALSE;
872
873         while (fgets(buf, sizeof(buf), outfp) != NULL) {
874                 strretchomp(buf);
875                 if (find_func(buf, str)) {
876                         fclose(outfp);
877                         return TRUE;
878                 }
879         }
880
881         fclose(outfp);
882
883         return FALSE;
884 }
885
886 gboolean procmime_find_string(MsgInfo *msginfo, const gchar *str,
887                               StrFindFunc find_func)
888 {
889         MimeInfo *mimeinfo;
890         MimeInfo *partinfo;
891         gchar *filename;
892         gboolean found = FALSE;
893
894         g_return_val_if_fail(msginfo != NULL, FALSE);
895         g_return_val_if_fail(str != NULL, FALSE);
896         g_return_val_if_fail(find_func != NULL, FALSE);
897
898         filename = procmsg_get_message_file(msginfo);
899         if (!filename) return FALSE;
900         mimeinfo = procmime_scan_message(msginfo);
901
902         for (partinfo = mimeinfo; partinfo != NULL;
903              partinfo = procmime_mimeinfo_next(partinfo)) {
904                 if (partinfo->type == MIMETYPE_TEXT) {
905                         if (procmime_find_string_part
906                                 (partinfo, filename, str, find_func) == TRUE) {
907                                 found = TRUE;
908                                 break;
909                         }
910                 }
911         }
912
913         procmime_mimeinfo_free_all(mimeinfo);
914         g_free(filename);
915
916         return found;
917 }
918
919 gchar *procmime_get_tmp_file_name(MimeInfo *mimeinfo)
920 {
921         static guint32 id = 0;
922         gchar *base;
923         gchar *filename;
924         gchar f_prefix[10];
925
926         g_return_val_if_fail(mimeinfo != NULL, NULL);
927
928         g_snprintf(f_prefix, sizeof(f_prefix), "%08x.", id++);
929
930         if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
931                 base = g_strdup("mimetmp.html");
932         else {
933                 const gchar *basetmp;
934
935                 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
936                 if (basetmp == NULL)
937                         basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
938                 if (basetmp == NULL)
939                         basetmp = "mimetmp";
940                 basetmp = g_path_get_basename(basetmp);
941                 if (*basetmp == '\0') 
942                         basetmp = g_strdup("mimetmp");
943                 base = conv_filename_from_utf8(basetmp);
944                 g_free((gchar*)basetmp);
945                 subst_for_shellsafe_filename(base);
946         }
947
948         filename = g_strconcat(get_mime_tmp_dir(), G_DIR_SEPARATOR_S,
949                                f_prefix, base, NULL);
950
951         g_free(base);
952         
953         return filename;
954 }
955
956 static GList *mime_type_list = NULL;
957
958 gchar *procmime_get_mime_type(const gchar *filename)
959 {
960         static GHashTable *mime_type_table = NULL;
961         MimeType *mime_type;
962         const gchar *p;
963         gchar *ext = NULL;
964         gchar *base;
965
966         if (!mime_type_table) {
967                 mime_type_table = procmime_get_mime_type_table();
968                 if (!mime_type_table) return NULL;
969         }
970
971         base = g_path_get_basename(filename);
972         if ((p = strrchr(base, '.')) != NULL)
973                 Xstrdup_a(ext, p + 1, p = NULL );
974         g_free(base);
975         if (!p) return NULL;
976
977         g_strdown(ext);
978         mime_type = g_hash_table_lookup(mime_type_table, ext);
979         if (mime_type) {
980                 gchar *str;
981
982                 str = g_strconcat(mime_type->type, "/", mime_type->sub_type,
983                                   NULL);
984                 return str;
985         }
986
987         return NULL;
988 }
989
990 static guint procmime_str_hash(gconstpointer gptr)
991 {
992         guint hash_result = 0;
993         const char *str;
994
995         for (str = gptr; str && *str; str++) {
996                 if (isupper(*str)) hash_result += (*str + ' ');
997                 else hash_result += *str;
998         }
999
1000         return hash_result;
1001 }
1002
1003 static gint procmime_str_equal(gconstpointer gptr1, gconstpointer gptr2)
1004 {
1005         const char *str1 = gptr1;
1006         const char *str2 = gptr2;
1007
1008         return !g_utf8_collate(str1, str2);
1009 }
1010
1011 static GHashTable *procmime_get_mime_type_table(void)
1012 {
1013         GHashTable *table = NULL;
1014         GList *cur;
1015         MimeType *mime_type;
1016         gchar **exts;
1017
1018         if (!mime_type_list) {
1019                 mime_type_list = procmime_get_mime_type_list();
1020                 if (!mime_type_list) return NULL;
1021         }
1022
1023         table = g_hash_table_new(procmime_str_hash, procmime_str_equal);
1024
1025         for (cur = mime_type_list; cur != NULL; cur = cur->next) {
1026                 gint i;
1027                 gchar *key;
1028
1029                 mime_type = (MimeType *)cur->data;
1030
1031                 if (!mime_type->extension) continue;
1032
1033                 exts = g_strsplit(mime_type->extension, " ", 16);
1034                 for (i = 0; exts[i] != NULL; i++) {
1035                         /* make the key case insensitive */
1036                         g_strdown(exts[i]);
1037                         /* use previously dup'd key on overwriting */
1038                         if (g_hash_table_lookup(table, exts[i]))
1039                                 key = exts[i];
1040                         else
1041                                 key = g_strdup(exts[i]);
1042                         g_hash_table_insert(table, key, mime_type);
1043                 }
1044                 g_strfreev(exts);
1045         }
1046
1047         return table;
1048 }
1049
1050 GList *procmime_get_mime_type_list(void)
1051 {
1052         GList *list = NULL;
1053         FILE *fp;
1054         gchar buf[BUFFSIZE];
1055         gchar *p;
1056         gchar *delim;
1057         MimeType *mime_type;
1058         gboolean fp_is_glob_file = TRUE;
1059
1060         if (mime_type_list) 
1061                 return mime_type_list;
1062         
1063         if ((fp = g_fopen("/usr/share/mime/globs", "rb")) == NULL) {
1064                 fp_is_glob_file = FALSE;
1065                 if ((fp = g_fopen("/etc/mime.types", "rb")) == NULL) {
1066                         if ((fp = g_fopen(SYSCONFDIR "/mime.types", "rb")) 
1067                                 == NULL) {
1068                                 FILE_OP_ERROR(SYSCONFDIR "/mime.types", 
1069                                         "fopen");
1070                                 return NULL;
1071                         }
1072                 }
1073         }
1074
1075         while (fgets(buf, sizeof(buf), fp) != NULL) {
1076                 p = strchr(buf, '#');
1077                 if (p) *p = '\0';
1078                 g_strstrip(buf);
1079
1080                 p = buf;
1081                 
1082                 if (fp_is_glob_file) {
1083                         while (*p && !g_ascii_isspace(*p) && (*p!=':')) p++;
1084                 } else {
1085                         while (*p && !g_ascii_isspace(*p)) p++;
1086                 }
1087
1088                 if (*p) {
1089                         *p = '\0';
1090                         p++;
1091                 }
1092                 delim = strchr(buf, '/');
1093                 if (delim == NULL) continue;
1094                 *delim = '\0';
1095
1096                 mime_type = g_new(MimeType, 1);
1097                 mime_type->type = g_strdup(buf);
1098                 mime_type->sub_type = g_strdup(delim + 1);
1099
1100                 if (fp_is_glob_file) {
1101                         while (*p && (g_ascii_isspace(*p)||(*p=='*')||(*p=='.'))) p++;
1102                 } else {
1103                         while (*p && g_ascii_isspace(*p)) p++;
1104                 }
1105
1106                 if (*p)
1107                         mime_type->extension = g_strdup(p);
1108                 else
1109                         mime_type->extension = NULL;
1110
1111                 list = g_list_append(list, mime_type);
1112         }
1113
1114         fclose(fp);
1115
1116         if (!list)
1117                 g_warning("Can't read mime.types\n");
1118
1119         return list;
1120 }
1121
1122 EncodingType procmime_get_encoding_for_charset(const gchar *charset)
1123 {
1124         if (!charset)
1125                 return ENC_8BIT;
1126         else if (!g_ascii_strncasecmp(charset, "ISO-2022-", 9) ||
1127                  !g_ascii_strcasecmp(charset, "US-ASCII"))
1128                 return ENC_7BIT;
1129         else if (!g_ascii_strcasecmp(charset, "ISO-8859-5") ||
1130                  !g_ascii_strncasecmp(charset, "KOI8-", 5) ||
1131                  !g_ascii_strcasecmp(charset, "Windows-1251"))
1132                 return ENC_8BIT;
1133         else if (!g_ascii_strncasecmp(charset, "ISO-8859-", 9))
1134                 return ENC_QUOTED_PRINTABLE;
1135         else
1136                 return ENC_8BIT;
1137 }
1138
1139 EncodingType procmime_get_encoding_for_text_file(const gchar *file, gboolean *has_binary)
1140 {
1141         FILE *fp;
1142         guchar buf[BUFFSIZE];
1143         size_t len;
1144         size_t octet_chars = 0;
1145         size_t total_len = 0;
1146         gfloat octet_percentage;
1147         gboolean force_b64 = FALSE;
1148
1149         if ((fp = g_fopen(file, "rb")) == NULL) {
1150                 FILE_OP_ERROR(file, "fopen");
1151                 return ENC_UNKNOWN;
1152         }
1153
1154         while ((len = fread(buf, sizeof(guchar), sizeof(buf), fp)) > 0) {
1155                 guchar *p;
1156                 gint i;
1157
1158                 for (p = buf, i = 0; i < len; ++p, ++i) {
1159                         if (*p & 0x80)
1160                                 ++octet_chars;
1161                         if (*p == '\0') {
1162                                 force_b64 = TRUE;
1163                                 *has_binary = TRUE;
1164                         }
1165                 }
1166                 total_len += len;
1167         }
1168
1169         fclose(fp);
1170         
1171         if (total_len > 0)
1172                 octet_percentage = (gfloat)octet_chars / (gfloat)total_len;
1173         else
1174                 octet_percentage = 0.0;
1175
1176         debug_print("procmime_get_encoding_for_text_file(): "
1177                     "8bit chars: %d / %d (%f%%)\n", octet_chars, total_len,
1178                     100.0 * octet_percentage);
1179
1180         if (octet_percentage > 0.20 || force_b64) {
1181                 debug_print("using BASE64\n");
1182                 return ENC_BASE64;
1183         } else if (octet_chars > 0) {
1184                 debug_print("using quoted-printable\n");
1185                 return ENC_QUOTED_PRINTABLE;
1186         } else {
1187                 debug_print("using 7bit\n");
1188                 return ENC_7BIT;
1189         }
1190 }
1191
1192 struct EncodingTable 
1193 {
1194         gchar *str;
1195         EncodingType enc_type;
1196 };
1197
1198 struct EncodingTable encoding_table[] = {
1199         {"7bit", ENC_7BIT},
1200         {"8bit", ENC_8BIT},
1201         {"binary", ENC_BINARY},
1202         {"quoted-printable", ENC_QUOTED_PRINTABLE},
1203         {"base64", ENC_BASE64},
1204         {"x-uuencode", ENC_UNKNOWN},
1205         {NULL, ENC_UNKNOWN},
1206 };
1207
1208 const gchar *procmime_get_encoding_str(EncodingType encoding)
1209 {
1210         struct EncodingTable *enc_table;
1211         
1212         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1213                 if (enc_table->enc_type == encoding)
1214                         return enc_table->str;
1215         }
1216         return NULL;
1217 }
1218
1219 /* --- NEW MIME STUFF --- */
1220 struct TypeTable
1221 {
1222         gchar *str;
1223         MimeMediaType type;
1224 };
1225
1226 static struct TypeTable mime_type_table[] = {
1227         {"text", MIMETYPE_TEXT},
1228         {"image", MIMETYPE_IMAGE},
1229         {"audio", MIMETYPE_AUDIO},
1230         {"video", MIMETYPE_VIDEO},
1231         {"application", MIMETYPE_APPLICATION},
1232         {"message", MIMETYPE_MESSAGE},
1233         {"multipart", MIMETYPE_MULTIPART},
1234         {NULL, 0},
1235 };
1236
1237 const gchar *procmime_get_media_type_str(MimeMediaType type)
1238 {
1239         struct TypeTable *type_table;
1240         
1241         for (type_table = mime_type_table; type_table->str != NULL; type_table++) {
1242                 if (type_table->type == type)
1243                         return type_table->str;
1244         }
1245         return NULL;
1246 }
1247
1248 MimeMediaType procmime_get_media_type(const gchar *str)
1249 {
1250         struct TypeTable *typetablearray;
1251
1252         for (typetablearray = mime_type_table; typetablearray->str != NULL; typetablearray++)
1253                 if (g_ascii_strncasecmp(str, typetablearray->str, strlen(typetablearray->str)) == 0)
1254                         return typetablearray->type;
1255
1256         return MIMETYPE_UNKNOWN;
1257 }
1258
1259 /*!
1260  *\brief        Safe wrapper for content type string.
1261  *
1262  *\return       const gchar * Pointer to content type string. 
1263  */
1264 gchar *procmime_get_content_type_str(MimeMediaType type,
1265                                            const char *subtype)
1266 {
1267         const gchar *type_str = NULL;
1268
1269         if (subtype == NULL || !(type_str = procmime_get_media_type_str(type)))
1270                 return g_strdup("unknown");
1271         return g_strdup_printf("%s/%s", type_str, subtype);
1272 }
1273
1274 static int procmime_parse_mimepart(MimeInfo *parent,
1275                              gchar *content_type,
1276                              gchar *content_encoding,
1277                              gchar *content_description,
1278                              gchar *content_id,
1279                              gchar *content_disposition,
1280                              gchar *content_location,
1281                              const gchar *filename,
1282                              guint offset,
1283                              guint length);
1284
1285 void procmime_parse_message_rfc822(MimeInfo *mimeinfo)
1286 {
1287         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1288                                 {"Content-Transfer-Encoding:",
1289                                                    NULL, FALSE},
1290                                 {"Content-Description:",
1291                                                    NULL, TRUE},
1292                                 {"Content-ID:",
1293                                                    NULL, TRUE},
1294                                 {"Content-Disposition:",
1295                                                    NULL, TRUE},
1296                                 {"Content-Location:",
1297                                                    NULL, TRUE},
1298                                 {"MIME-Version:",
1299                                                    NULL, TRUE},
1300                                 {NULL,             NULL, FALSE}};
1301         guint content_start, i;
1302         FILE *fp;
1303         gchar *tmp;
1304
1305         procmime_decode_content(mimeinfo);
1306
1307         fp = g_fopen(mimeinfo->data.filename, "rb");
1308         if (fp == NULL) {
1309                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1310                 return;
1311         }
1312         fseek(fp, mimeinfo->offset, SEEK_SET);
1313         procheader_get_header_fields(fp, hentry);
1314         if (hentry[0].body != NULL) {
1315                 tmp = conv_unmime_header(hentry[0].body, NULL);
1316                 g_free(hentry[0].body);
1317                 hentry[0].body = tmp;
1318         }                
1319         if (hentry[2].body != NULL) {
1320                 tmp = conv_unmime_header(hentry[2].body, NULL);
1321                 g_free(hentry[2].body);
1322                 hentry[2].body = tmp;
1323         }                
1324         if (hentry[4].body != NULL) {
1325                 tmp = conv_unmime_header(hentry[4].body, NULL);
1326                 g_free(hentry[4].body);
1327                 hentry[4].body = tmp;
1328         }                
1329         if (hentry[5].body != NULL) {
1330                 tmp = conv_unmime_header(hentry[5].body, NULL);
1331                 g_free(hentry[5].body);
1332                 hentry[5].body = tmp;
1333         }                
1334         content_start = ftell(fp);
1335         fclose(fp);
1336         
1337         procmime_parse_mimepart(mimeinfo,
1338                                 hentry[0].body, hentry[1].body,
1339                                 hentry[2].body, hentry[3].body,
1340                                 hentry[4].body, hentry[5].body,
1341                                 mimeinfo->data.filename, content_start,
1342                                 mimeinfo->length - (content_start - mimeinfo->offset));
1343         
1344         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1345                 g_free(hentry[i].body);
1346                 hentry[i].body = NULL;
1347         }
1348 }
1349
1350 void procmime_parse_multipart(MimeInfo *mimeinfo)
1351 {
1352         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1353                                 {"Content-Transfer-Encoding:",
1354                                                    NULL, FALSE},
1355                                 {"Content-Description:",
1356                                                    NULL, TRUE},
1357                                 {"Content-ID:",
1358                                                    NULL, TRUE},
1359                                 {"Content-Disposition:",
1360                                                    NULL, TRUE},
1361                                 {"Content-Location:",
1362                                                    NULL, TRUE},
1363                                 {NULL,             NULL, FALSE}};
1364         gchar *p, *tmp;
1365         gchar *boundary;
1366         gint boundary_len = 0, lastoffset = -1, i;
1367         gchar buf[BUFFSIZE];
1368         FILE *fp;
1369         int result = 0;
1370
1371         boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
1372         if (!boundary)
1373                 return;
1374         boundary_len = strlen(boundary);
1375
1376         procmime_decode_content(mimeinfo);
1377
1378         fp = g_fopen(mimeinfo->data.filename, "rb");
1379         if (fp == NULL) {
1380                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1381                 return;
1382         }
1383         fseek(fp, mimeinfo->offset, SEEK_SET);
1384         while ((p = fgets(buf, sizeof(buf), fp)) != NULL && result == 0) {
1385                 if (ftell(fp) > (mimeinfo->offset + mimeinfo->length))
1386                         break;
1387
1388                 if (IS_BOUNDARY(buf, boundary, boundary_len)) {
1389                         if (lastoffset != -1) {
1390                                 result = procmime_parse_mimepart(mimeinfo,
1391                                                         hentry[0].body, hentry[1].body,
1392                                                         hentry[2].body, hentry[3].body, 
1393                                                         hentry[4].body, hentry[5].body,
1394                                                         mimeinfo->data.filename, lastoffset,
1395                                                         (ftell(fp) - strlen(buf)) - lastoffset - 1);
1396                         }
1397                         
1398                         if (buf[2 + boundary_len]     == '-' &&
1399                             buf[2 + boundary_len + 1] == '-')
1400                                 break;
1401
1402                         for (i = 0; i < (sizeof hentry / sizeof hentry[0]) ; i++) {
1403                                 g_free(hentry[i].body);
1404                                 hentry[i].body = NULL;
1405                         }
1406                         procheader_get_header_fields(fp, hentry);
1407                         if (hentry[0].body != NULL) {
1408                                 tmp = conv_unmime_header(hentry[0].body, NULL);
1409                                 g_free(hentry[0].body);
1410                                 hentry[0].body = tmp;
1411                         }                
1412                         if (hentry[2].body != NULL) {
1413                                 tmp = conv_unmime_header(hentry[2].body, NULL);
1414                                 g_free(hentry[2].body);
1415                                 hentry[2].body = tmp;
1416                         }                
1417                         if (hentry[4].body != NULL) {
1418                                 tmp = conv_unmime_header(hentry[4].body, NULL);
1419                                 g_free(hentry[4].body);
1420                                 hentry[4].body = tmp;
1421                         }                
1422                         if (hentry[5].body != NULL) {
1423                                 tmp = conv_unmime_header(hentry[5].body, NULL);
1424                                 g_free(hentry[5].body);
1425                                 hentry[5].body = tmp;
1426                         }                
1427                         lastoffset = ftell(fp);
1428                 }
1429         }
1430         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1431                 g_free(hentry[i].body);
1432                 hentry[i].body = NULL;
1433         }
1434         fclose(fp);
1435 }
1436
1437 static void parse_parameters(const gchar *parameters, GHashTable *table)
1438 {
1439         gchar *params, *param, *next;
1440         GSList *convlist = NULL, *concatlist = NULL, *cur;
1441
1442         params = g_strdup(parameters);
1443         param = params;
1444         next = params;
1445         for (; next != NULL; param = next) {
1446                 gchar *attribute, *value, *tmp;
1447                 gint len;
1448                 gboolean convert = FALSE;
1449
1450                 next = strchr_with_skip_quote(param, '"', ';');
1451                 if (next != NULL) {
1452                         next[0] = '\0';
1453                         next++;
1454                 }
1455
1456                 g_strstrip(param);
1457
1458                 attribute = param;
1459                 value = strchr(attribute, '=');
1460                 if (value == NULL)
1461                         continue;
1462
1463                 value[0] = '\0';
1464                 value++;
1465                 while (value[0] == ' ')
1466                         value++;
1467
1468                 g_strdown(attribute);
1469
1470                 len = strlen(attribute);
1471                 if (attribute[len - 1] == '*') {
1472                         gchar *srcpos, *dstpos, *endpos;
1473
1474                         convert = TRUE;
1475                         attribute[len - 1] = '\0';
1476
1477                         srcpos = value;
1478                         dstpos = value;
1479                         endpos = value + strlen(value);
1480                         while (srcpos < endpos) {
1481                                 if (*srcpos != '%')
1482                                         *dstpos = *srcpos;
1483                                 else {
1484                                         guchar dstvalue;
1485
1486                                         if (!get_hex_value(&dstvalue, srcpos[1], srcpos[2]))
1487                                                 *dstpos = '?';
1488                                         else
1489                                                 *dstpos = dstvalue;
1490                                         srcpos += 2;
1491                                 }
1492                                 srcpos++;
1493                                 dstpos++;
1494                         }
1495                         *dstpos = '\0';
1496                 } else {
1497                         if (value[0] == '"')
1498                                 extract_quote(value, '"');
1499                         else if ((tmp = strchr(value, ' ')) != NULL)
1500                                 *tmp = '\0';
1501                 }
1502
1503                 if (attribute) {
1504                         while (attribute[0] == ' ')
1505                                 attribute++;
1506                         while (attribute[strlen(attribute)-1] == ' ') 
1507                                 attribute[strlen(attribute)-1] = '\0';
1508                 } 
1509                 if (value) {
1510                         while (value[0] == ' ')
1511                                 value++;
1512                         while (value[strlen(value)-1] == ' ') 
1513                                 value[strlen(value)-1] = '\0';
1514                 }               
1515                 if (strrchr(attribute, '*') != NULL) {
1516                         gchar *tmpattr;
1517
1518                         tmpattr = g_strdup(attribute);
1519                         tmp = strrchr(tmpattr, '*');
1520                         tmp[0] = '\0';
1521
1522                         if ((tmp[1] == '0') && (tmp[2] == '\0') && 
1523                             (g_slist_find_custom(concatlist, attribute, g_str_equal) == NULL))
1524                                 concatlist = g_slist_prepend(concatlist, g_strdup(tmpattr));
1525
1526                         if (convert && (g_slist_find_custom(convlist, attribute, g_str_equal) == NULL))
1527                                 convlist = g_slist_prepend(convlist, g_strdup(tmpattr));
1528
1529                         g_free(tmpattr);
1530                 } else if (convert) {
1531                         if (g_slist_find_custom(convlist, attribute, g_str_equal) == NULL)
1532                                 convlist = g_slist_prepend(convlist, g_strdup(attribute));
1533                 }
1534
1535                 if (g_hash_table_lookup(table, attribute) == NULL)
1536                         g_hash_table_insert(table, g_strdup(attribute), g_strdup(value));
1537         }
1538
1539         for (cur = concatlist; cur != NULL; cur = g_slist_next(cur)) {
1540                 gchar *attribute, *attrwnum, *partvalue;
1541                 gint n = 0;
1542                 GString *value;
1543
1544                 attribute = (gchar *) cur->data;
1545                 value = g_string_sized_new(64);
1546
1547                 attrwnum = g_strdup_printf("%s*%d", attribute, n);
1548                 while ((partvalue = g_hash_table_lookup(table, attrwnum)) != NULL) {
1549                         g_string_append(value, partvalue);
1550
1551                         g_free(attrwnum);
1552                         n++;
1553                         attrwnum = g_strdup_printf("%s*%d", attribute, n);
1554                 }
1555                 g_free(attrwnum);
1556
1557                 g_hash_table_insert(table, g_strdup(attribute), g_strdup(value->str));
1558                 g_string_free(value, TRUE);
1559         }
1560         slist_free_strings(concatlist);
1561         g_slist_free(concatlist);
1562
1563         for (cur = convlist; cur != NULL; cur = g_slist_next(cur)) {
1564                 gchar *attribute, *key, *value;
1565                 gchar *charset, *lang, *oldvalue, *newvalue;
1566
1567                 attribute = (gchar *) cur->data;
1568                 if (!g_hash_table_lookup_extended(
1569                         table, attribute, (gpointer *)(gchar *) &key, (gpointer *)(gchar *) &value))
1570                         continue;
1571
1572                 charset = value;
1573                 lang = strchr(charset, '\'');
1574                 if (lang == NULL)
1575                         continue;
1576                 lang[0] = '\0';
1577                 lang++;
1578                 oldvalue = strchr(lang, '\'');
1579                 if (oldvalue == NULL)
1580                         continue;
1581                 oldvalue[0] = '\0';
1582                 oldvalue++;
1583
1584                 newvalue = conv_codeset_strdup(oldvalue, charset, CS_UTF_8);
1585
1586                 g_hash_table_remove(table, attribute);
1587                 g_free(key);
1588                 g_free(value);
1589
1590                 g_hash_table_insert(table, g_strdup(attribute), newvalue);
1591         }
1592         slist_free_strings(convlist);
1593         g_slist_free(convlist);
1594
1595         g_free(params);
1596 }       
1597
1598 static void procmime_parse_content_type(const gchar *content_type, MimeInfo *mimeinfo)
1599 {
1600         g_return_if_fail(content_type != NULL);
1601         g_return_if_fail(mimeinfo != NULL);
1602
1603         /* RFC 2045, page 13 says that the mime subtype is MANDATORY;
1604          * if it's not available we use the default Content-Type */
1605         if ((content_type[0] == '\0') || (strchr(content_type, '/') == NULL)) {
1606                 mimeinfo->type = MIMETYPE_TEXT;
1607                 mimeinfo->subtype = g_strdup("plain");
1608                 if (g_hash_table_lookup(mimeinfo->typeparameters,
1609                                        "charset") == NULL) {
1610                         g_hash_table_insert(mimeinfo->typeparameters,
1611                                     g_strdup("charset"),
1612                                     g_strdup(
1613                                         conv_get_locale_charset_str_no_utf8()));
1614                 }
1615         } else {
1616                 gchar *type, *subtype, *params;
1617
1618                 type = g_strdup(content_type);
1619                 subtype = strchr(type, '/') + 1;
1620                 *(subtype - 1) = '\0';
1621                 if ((params = strchr(subtype, ';')) != NULL) {
1622                         params[0] = '\0';
1623                         params++;
1624                 }
1625
1626                 mimeinfo->type = procmime_get_media_type(type);
1627                 mimeinfo->subtype = g_strdup(subtype);
1628
1629                 /* Get mimeinfo->typeparameters */
1630                 if (params != NULL)
1631                         parse_parameters(params, mimeinfo->typeparameters);
1632
1633                 g_free(type);
1634         }
1635 }
1636
1637 static void procmime_parse_content_disposition(const gchar *content_disposition, MimeInfo *mimeinfo)
1638 {
1639         gchar *tmp, *params;
1640
1641         g_return_if_fail(content_disposition != NULL);
1642         g_return_if_fail(mimeinfo != NULL);
1643
1644         tmp = g_strdup(content_disposition);
1645         if ((params = strchr(tmp, ';')) != NULL) {
1646                 params[0] = '\0';
1647                 params++;
1648         }       
1649         g_strstrip(tmp);
1650
1651         if (!g_ascii_strcasecmp(tmp, "inline")) 
1652                 mimeinfo->disposition = DISPOSITIONTYPE_INLINE;
1653         else if (!g_ascii_strcasecmp(tmp, "attachment"))
1654                 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1655         else
1656                 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1657         
1658         if (params != NULL)
1659                 parse_parameters(params, mimeinfo->dispositionparameters);
1660
1661         g_free(tmp);
1662 }
1663
1664
1665 static void procmime_parse_content_encoding(const gchar *content_encoding, MimeInfo *mimeinfo)
1666 {
1667         struct EncodingTable *enc_table;
1668         
1669         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1670                 if (g_ascii_strcasecmp(enc_table->str, content_encoding) == 0) {
1671                         mimeinfo->encoding_type = enc_table->enc_type;
1672                         return;
1673                 }
1674         }
1675         mimeinfo->encoding_type = ENC_UNKNOWN;
1676         return;
1677 }
1678
1679 static int procmime_parse_mimepart(MimeInfo *parent,
1680                              gchar *content_type,
1681                              gchar *content_encoding,
1682                              gchar *content_description,
1683                              gchar *content_id,
1684                              gchar *content_disposition,
1685                              gchar *content_location,
1686                              const gchar *filename,
1687                              guint offset,
1688                              guint length)
1689 {
1690         MimeInfo *mimeinfo;
1691
1692         /* Create MimeInfo */
1693         mimeinfo = procmime_mimeinfo_new();
1694         mimeinfo->content = MIMECONTENT_FILE;
1695         if (parent != NULL) {
1696                 if (g_node_depth(parent->node) > 32) {
1697                         /* 32 is an arbitrary value
1698                          * this avoids DOSsing ourselves 
1699                          * with enormous messages
1700                          */
1701                         procmime_mimeinfo_free_all(mimeinfo);
1702                         return -1;                      
1703                 }
1704                 g_node_append(parent->node, mimeinfo->node);
1705         }
1706         mimeinfo->data.filename = g_strdup(filename);
1707         mimeinfo->offset = offset;
1708         mimeinfo->length = length;
1709
1710         if (content_type != NULL) {
1711                 procmime_parse_content_type(content_type, mimeinfo);
1712         } else {
1713                 mimeinfo->type = MIMETYPE_TEXT;
1714                 mimeinfo->subtype = g_strdup("plain");
1715                 if (g_hash_table_lookup(mimeinfo->typeparameters,
1716                                        "charset") == NULL) {
1717                         g_hash_table_insert(mimeinfo->typeparameters,
1718                                     g_strdup("charset"),
1719                                     g_strdup(
1720                                         conv_get_locale_charset_str_no_utf8()));
1721                 }
1722         }
1723
1724         if (content_encoding != NULL) {
1725                 procmime_parse_content_encoding(content_encoding, mimeinfo);
1726         } else {
1727                 mimeinfo->encoding_type = ENC_UNKNOWN;
1728         }
1729
1730         if (content_description != NULL)
1731                 mimeinfo->description = g_strdup(content_description);
1732         else
1733                 mimeinfo->description = NULL;
1734
1735         if (content_id != NULL)
1736                 mimeinfo->id = g_strdup(content_id);
1737         else
1738                 mimeinfo->id = NULL;
1739
1740         if (content_location != NULL)
1741                 mimeinfo->location = g_strdup(content_location);
1742         else
1743                 mimeinfo->location = NULL;
1744
1745         if (content_disposition != NULL) 
1746                 procmime_parse_content_disposition(content_disposition, mimeinfo);
1747         else
1748                 mimeinfo->disposition = DISPOSITIONTYPE_UNKNOWN;
1749
1750         /* Call parser for mime type */
1751         switch (mimeinfo->type) {
1752                 case MIMETYPE_MESSAGE:
1753                         if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
1754                                 procmime_parse_message_rfc822(mimeinfo);
1755                         }
1756                         break;
1757                         
1758                 case MIMETYPE_MULTIPART:
1759                         procmime_parse_multipart(mimeinfo);
1760                         break;
1761                         
1762                 default:
1763                         break;
1764         }
1765
1766         return 0;
1767 }
1768
1769 static gchar *typenames[] = {
1770     "text",
1771     "image",
1772     "audio",
1773     "video",
1774     "application",
1775     "message",
1776     "multipart",
1777     "unknown",
1778 };
1779
1780 static gboolean output_func(GNode *node, gpointer data)
1781 {
1782         guint i, depth;
1783         MimeInfo *mimeinfo = (MimeInfo *) node->data;
1784
1785         depth = g_node_depth(node);
1786         for (i = 0; i < depth; i++)
1787                 printf("    ");
1788         printf("%s/%s (offset:%d length:%d encoding: %d)\n", typenames[mimeinfo->type], mimeinfo->subtype, mimeinfo->offset, mimeinfo->length, mimeinfo->encoding_type);
1789
1790         return FALSE;
1791 }
1792
1793 static void output_mime_structure(MimeInfo *mimeinfo, int indent)
1794 {
1795         g_node_traverse(mimeinfo->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1, output_func, NULL);
1796 }
1797
1798 MimeInfo *procmime_scan_file_with_offset(const gchar *filename, int offset)
1799 {
1800         MimeInfo *mimeinfo;
1801         struct stat buf;
1802
1803         stat(filename, &buf);
1804
1805         mimeinfo = procmime_mimeinfo_new();
1806         mimeinfo->content = MIMECONTENT_FILE;
1807         mimeinfo->encoding_type = ENC_UNKNOWN;
1808         mimeinfo->type = MIMETYPE_MESSAGE;
1809         mimeinfo->subtype = g_strdup("rfc822");
1810         mimeinfo->data.filename = g_strdup(filename);
1811         mimeinfo->offset = offset;
1812         mimeinfo->length = buf.st_size - offset;
1813
1814         procmime_parse_message_rfc822(mimeinfo);
1815         if (debug_get_mode())
1816                 output_mime_structure(mimeinfo, 0);
1817
1818         return mimeinfo;
1819 }
1820
1821 MimeInfo *procmime_scan_file(const gchar *filename)
1822 {
1823         MimeInfo *mimeinfo;
1824
1825         g_return_val_if_fail(filename != NULL, NULL);
1826
1827         mimeinfo = procmime_scan_file_with_offset(filename, 0);
1828
1829         return mimeinfo;
1830 }
1831
1832 MimeInfo *procmime_scan_queue_file(const gchar *filename)
1833 {
1834         FILE *fp;
1835         MimeInfo *mimeinfo;
1836         gchar buf[BUFFSIZE];
1837         gint offset = 0;
1838
1839         g_return_val_if_fail(filename != NULL, NULL);
1840
1841         /* Open file */
1842         if ((fp = g_fopen(filename, "rb")) == NULL)
1843                 return NULL;
1844         /* Skip queue header */
1845         while (fgets(buf, sizeof(buf), fp) != NULL)
1846                 if (buf[0] == '\r' || buf[0] == '\n') break;
1847         offset = ftell(fp);
1848         fclose(fp);
1849
1850         mimeinfo = procmime_scan_file_with_offset(filename, offset);
1851
1852         return mimeinfo;
1853 }
1854
1855 typedef enum {
1856     ENC_AS_TOKEN,
1857     ENC_AS_QUOTED_STRING,
1858     ENC_AS_EXTENDED,
1859     ENC_TO_ASCII,
1860 } EncodeAs;
1861
1862 typedef struct _ParametersData {
1863         FILE *fp;
1864         guint len;
1865         guint ascii_only;
1866 } ParametersData;
1867
1868 static void write_parameters(gpointer key, gpointer value, gpointer user_data)
1869 {
1870         gchar *param = key;
1871         gchar *val = value, *valpos, *tmp;
1872         ParametersData *pdata = (ParametersData *)user_data;
1873         GString *buf = g_string_new("");
1874
1875         EncodeAs encas = ENC_AS_TOKEN;
1876
1877         for (valpos = val; *valpos != 0; valpos++) {
1878                 if (!IS_ASCII(*valpos) || *valpos == '"') {
1879                         encas = ENC_AS_EXTENDED;
1880                         break;
1881                 }
1882             
1883                 /* CTLs */
1884                 if (((*valpos >= 0) && (*valpos < 037)) || (*valpos == 0177)) {
1885                         encas = ENC_AS_QUOTED_STRING;
1886                         continue;
1887                 }
1888
1889                 /* tspecials + SPACE */
1890                 switch (*valpos) {
1891                 case ' ':
1892                 case '(': 
1893                 case ')':
1894                 case '<':
1895                 case '>':
1896                 case '@':
1897                 case ',':
1898                 case ';':
1899                 case ':':
1900                 case '\\':
1901                 case '\'':
1902                 case '/':
1903                 case '[':
1904                 case ']':
1905                 case '?':
1906                 case '=':
1907                         encas = ENC_AS_QUOTED_STRING;
1908                         continue;
1909                 }
1910         }
1911         
1912         if (encas == ENC_AS_EXTENDED && pdata->ascii_only == TRUE) 
1913                 encas = ENC_TO_ASCII;
1914
1915         switch (encas) {
1916         case ENC_AS_TOKEN:
1917                 g_string_append_printf(buf, "%s=%s", param, val);
1918                 break;
1919
1920         case ENC_TO_ASCII:
1921                 tmp = g_strdup(val);
1922                 g_strcanon(tmp, 
1923                         " ()<>@,';:\\/[]?=.0123456789"
1924                         "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1925                         "abcdefghijklmnopqrstuvwxyz",
1926                         '_');
1927                 g_string_append_printf(buf, "%s=\"%s\"", param, tmp);
1928                 g_free(tmp);
1929                 break;
1930
1931         case ENC_AS_QUOTED_STRING:
1932                 g_string_append_printf(buf, "%s=\"%s\"", param, val);
1933                 break;
1934
1935         case ENC_AS_EXTENDED:
1936                 if (!g_utf8_validate(val, -1, NULL))
1937                         g_string_append_printf(buf, "%s*=%s''", param,
1938                                 conv_get_locale_charset_str());
1939                 else
1940                         g_string_append_printf(buf, "%s*=%s''", param,
1941                                 CS_INTERNAL);
1942                 for (valpos = val; *valpos != '\0'; valpos++) {
1943                         if (IS_ASCII(*valpos) && isalnum(*valpos)) {
1944                                 g_string_append_printf(buf, "%c", *valpos);
1945                         } else {
1946                                 gchar hexstr[3] = "XX";
1947                                 get_hex_str(hexstr, *valpos);
1948                                 g_string_append_printf(buf, "%%%s", hexstr);
1949                         }
1950                 }
1951                 break;          
1952         }
1953         
1954         if (buf->str && strlen(buf->str)) {
1955                 if (pdata->len + strlen(buf->str) + 2 > 76) {
1956                         fprintf(pdata->fp, ";\n %s", buf->str);
1957                         pdata->len = strlen(buf->str) + 1;
1958                 } else {
1959                         fprintf(pdata->fp, "; %s", buf->str);
1960                         pdata->len += strlen(buf->str) + 2;
1961                 }
1962         }
1963         g_string_free(buf, TRUE);
1964 }
1965
1966 void procmime_write_mime_header(MimeInfo *mimeinfo, FILE *fp)
1967 {
1968         struct TypeTable *type_table;
1969         ParametersData *pdata = g_new0(ParametersData, 1);
1970         debug_print("procmime_write_mime_header\n");
1971         
1972         pdata->fp = fp;
1973         pdata->ascii_only = FALSE;
1974
1975         for (type_table = mime_type_table; type_table->str != NULL; type_table++)
1976                 if (mimeinfo->type == type_table->type) {
1977                         gchar *buf = g_strdup_printf(
1978                                 "Content-Type: %s/%s", type_table->str, mimeinfo->subtype);
1979                         fprintf(fp, "%s", buf);
1980                         pdata->len = strlen(buf);
1981                         pdata->ascii_only = TRUE;
1982                         g_free(buf);
1983                         break;
1984                 }
1985         g_hash_table_foreach(mimeinfo->typeparameters, write_parameters, pdata);
1986         g_free(pdata);
1987
1988         fprintf(fp, "\n");
1989
1990         if (mimeinfo->encoding_type != ENC_UNKNOWN)
1991                 fprintf(fp, "Content-Transfer-Encoding: %s\n", procmime_get_encoding_str(mimeinfo->encoding_type));
1992
1993         if (mimeinfo->description != NULL)
1994                 fprintf(fp, "Content-Description: %s\n", mimeinfo->description);
1995
1996         if (mimeinfo->id != NULL)
1997                 fprintf(fp, "Content-ID: %s\n", mimeinfo->id);
1998
1999         if (mimeinfo->location != NULL)
2000                 fprintf(fp, "Content-Location: %s\n", mimeinfo->location);
2001
2002         if (mimeinfo->disposition != DISPOSITIONTYPE_UNKNOWN) {
2003                 ParametersData *pdata = g_new0(ParametersData, 1);
2004                 gchar *buf = NULL;
2005                 if (mimeinfo->disposition == DISPOSITIONTYPE_INLINE)
2006                         buf = g_strdup("Content-Disposition: inline");
2007                 else if (mimeinfo->disposition == DISPOSITIONTYPE_ATTACHMENT)
2008                         buf = g_strdup("Content-Disposition: attachment");
2009                 else
2010                         buf = g_strdup("Content-Disposition: unknown");
2011
2012                 fprintf(fp, "%s", buf);
2013                 pdata->len = strlen(buf);
2014                 g_free(buf);
2015
2016                 pdata->fp = fp;
2017                 pdata->ascii_only = FALSE;
2018
2019                 g_hash_table_foreach(mimeinfo->dispositionparameters, write_parameters, pdata);
2020                 g_free(pdata);
2021                 fprintf(fp, "\n");
2022         }
2023
2024         fprintf(fp, "\n");
2025 }
2026
2027 gint procmime_write_message_rfc822(MimeInfo *mimeinfo, FILE *fp)
2028 {
2029         FILE *infp;
2030         GNode *childnode;
2031         MimeInfo *child;
2032         gchar buf[BUFFSIZE];
2033         gboolean skip = FALSE;;
2034
2035         debug_print("procmime_write_message_rfc822\n");
2036
2037         /* write header */
2038         switch (mimeinfo->content) {
2039         case MIMECONTENT_FILE:
2040                 if ((infp = g_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2041                         FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2042                         return -1;
2043                 }
2044                 fseek(infp, mimeinfo->offset, SEEK_SET);
2045                 while (fgets(buf, sizeof(buf), infp) == buf) {
2046                         if (buf[0] == '\n' && buf[1] == '\0')
2047                                 break;
2048                         if (skip && (buf[0] == ' ' || buf[0] == '\t'))
2049                                 continue;
2050                         if (g_ascii_strncasecmp(buf, "Mime-Version:", 13) == 0 ||
2051                             g_ascii_strncasecmp(buf, "Content-Type:", 13) == 0 ||
2052                             g_ascii_strncasecmp(buf, "Content-Transfer-Encoding:", 26) == 0 ||
2053                             g_ascii_strncasecmp(buf, "Content-Description:", 20) == 0 ||
2054                             g_ascii_strncasecmp(buf, "Content-ID:", 11) == 0 ||
2055                             g_ascii_strncasecmp(buf, "Content-Location:", 17) == 0 ||
2056                             g_ascii_strncasecmp(buf, "Content-Disposition:", 20) == 0) {
2057                                 skip = TRUE;
2058                                 continue;
2059                         }
2060                         fwrite(buf, sizeof(gchar), strlen(buf), fp);
2061                         skip = FALSE;
2062                 }
2063                 fclose(infp);
2064                 break;
2065
2066         case MIMECONTENT_MEM:
2067                 fwrite(mimeinfo->data.mem, 
2068                                 sizeof(gchar), 
2069                                 strlen(mimeinfo->data.mem), 
2070                                 fp);
2071                 break;
2072
2073         default:
2074                 break;
2075         }
2076
2077         childnode = mimeinfo->node->children;
2078         if (childnode == NULL)
2079                 return -1;
2080
2081         child = (MimeInfo *) childnode->data;
2082         fprintf(fp, "Mime-Version: 1.0\n");
2083         procmime_write_mime_header(child, fp);
2084         return procmime_write_mimeinfo(child, fp);
2085 }
2086
2087 gint procmime_write_multipart(MimeInfo *mimeinfo, FILE *fp)
2088 {
2089         FILE *infp;
2090         GNode *childnode;
2091         gchar *boundary, *str, *str2;
2092         gchar buf[BUFFSIZE];
2093         gboolean firstboundary;
2094
2095         debug_print("procmime_write_multipart\n");
2096
2097         boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
2098
2099         switch (mimeinfo->content) {
2100         case MIMECONTENT_FILE:
2101                 if ((infp = g_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2102                         FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2103                         return -1;
2104                 }
2105                 fseek(infp, mimeinfo->offset, SEEK_SET);
2106                 while (fgets(buf, sizeof(buf), infp) == buf) {
2107                         if (IS_BOUNDARY(buf, boundary, strlen(boundary)))
2108                                 break;
2109                         fwrite(buf, sizeof(gchar), strlen(buf), fp);
2110                 }
2111                 fclose(infp);
2112                 break;
2113
2114         case MIMECONTENT_MEM:
2115                 str = g_strdup(mimeinfo->data.mem);
2116                 if (((str2 = strstr(str, boundary)) != NULL) && ((str2 - str) >= 2) &&
2117                     (*(str2 - 1) == '-') && (*(str2 - 2) == '-'))
2118                         *(str2 - 2) = '\0';
2119                 fwrite(str, sizeof(gchar), strlen(str), fp);
2120                 g_free(str);
2121                 break;
2122
2123         default:
2124                 break;
2125         }
2126
2127         childnode = mimeinfo->node->children;
2128         firstboundary = TRUE;
2129         while (childnode != NULL) {
2130                 MimeInfo *child = childnode->data;
2131
2132                 if (firstboundary)
2133                         firstboundary = FALSE;
2134                 else
2135                         fprintf(fp, "\n");
2136                 fprintf(fp, "--%s\n", boundary);
2137
2138                 procmime_write_mime_header(child, fp);
2139                 if (procmime_write_mimeinfo(child, fp) < 0)
2140                         return -1;
2141
2142                 childnode = g_node_next_sibling(childnode);
2143         }       
2144         fprintf(fp, "\n--%s--\n", boundary);
2145
2146         return 0;
2147 }
2148
2149 gint procmime_write_mimeinfo(MimeInfo *mimeinfo, FILE *fp)
2150 {
2151         FILE *infp;
2152
2153         debug_print("procmime_write_mimeinfo\n");
2154
2155         if (G_NODE_IS_LEAF(mimeinfo->node)) {
2156                 switch (mimeinfo->content) {
2157                 case MIMECONTENT_FILE:
2158                         if ((infp = g_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2159                                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2160                                 return -1;
2161                         }
2162                         copy_file_part_to_fp(infp, mimeinfo->offset, mimeinfo->length, fp);
2163                         fclose(infp);
2164                         return 0;
2165
2166                 case MIMECONTENT_MEM:
2167                         fwrite(mimeinfo->data.mem, 
2168                                         sizeof(gchar), 
2169                                         strlen(mimeinfo->data.mem), 
2170                                         fp);
2171                         return 0;
2172
2173                 default:
2174                         return 0;
2175                 }
2176         } else {
2177                 /* Call writer for mime type */
2178                 switch (mimeinfo->type) {
2179                 case MIMETYPE_MESSAGE:
2180                         if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
2181                                 return procmime_write_message_rfc822(mimeinfo, fp);
2182                         }
2183                         break;
2184                         
2185                 case MIMETYPE_MULTIPART:
2186                         return procmime_write_multipart(mimeinfo, fp);
2187                         
2188                 default:
2189                         break;
2190                 }
2191
2192                 return -1;
2193         }
2194
2195         return 0;
2196 }
2197
2198 gchar *procmime_get_part_file_name(MimeInfo *mimeinfo)
2199 {
2200         gchar *base;
2201
2202         if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
2203                 base = g_strdup("mimetmp.html");
2204         else {
2205                 const gchar *basetmp;
2206                 gchar *basename;
2207
2208                 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
2209                 if (basetmp == NULL)
2210                         basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
2211                 if (basetmp == NULL)
2212                         basetmp = "mimetmp";
2213                 basename = g_path_get_basename(basetmp);
2214                 if (*basename == '\0') {
2215                         g_free(basename);
2216                         basename = g_strdup("mimetmp");
2217                 }
2218                 base = conv_filename_from_utf8(basename);
2219                 g_free(basename);
2220                 subst_for_shellsafe_filename(base);
2221         }
2222         
2223         return base;
2224 }
2225