2006-08-08 [colin] 2.4.0cvs33
[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 #include "alertpanel.h"
52
53 static GHashTable *procmime_get_mime_type_table (void);
54
55 MimeInfo *procmime_mimeinfo_new(void)
56 {
57         MimeInfo *mimeinfo;
58
59         mimeinfo = g_new0(MimeInfo, 1);
60         mimeinfo->content        = MIMECONTENT_EMPTY;
61         mimeinfo->data.filename  = NULL;
62
63         mimeinfo->type           = MIMETYPE_UNKNOWN;
64         mimeinfo->encoding_type  = ENC_UNKNOWN;
65         mimeinfo->typeparameters = g_hash_table_new(g_str_hash, g_str_equal);
66
67         mimeinfo->disposition    = DISPOSITIONTYPE_UNKNOWN;
68         mimeinfo->dispositionparameters 
69                                  = g_hash_table_new(g_str_hash, g_str_equal);
70
71         mimeinfo->node           = g_node_new(mimeinfo);
72         
73         return mimeinfo;
74 }
75
76 static gboolean procmime_mimeinfo_parameters_destroy(gpointer key, gpointer value, gpointer user_data)
77 {
78         g_free(key);
79         g_free(value);
80         
81         return TRUE;
82 }
83
84 static gchar *forced_charset = NULL;
85
86 void procmime_force_charset(const gchar *str)
87 {
88         g_free(forced_charset);
89         forced_charset = NULL;
90         if (str)
91                 forced_charset = g_strdup(str);
92 }
93
94 static EncodingType forced_encoding = 0;
95
96 void procmime_force_encoding(EncodingType encoding)
97 {
98         forced_encoding = encoding;
99 }
100
101 static gboolean free_func(GNode *node, gpointer data)
102 {
103         MimeInfo *mimeinfo = (MimeInfo *) node->data;
104
105         switch (mimeinfo->content) {
106         case MIMECONTENT_FILE:
107                 if (mimeinfo->tmp)
108                         g_unlink(mimeinfo->data.filename);
109                 g_free(mimeinfo->data.filename);
110                 break;
111
112         case MIMECONTENT_MEM:
113                 if (mimeinfo->tmp)
114                         g_free(mimeinfo->data.mem);
115         default:
116                 break;
117         }
118
119         g_free(mimeinfo->subtype);
120         g_free(mimeinfo->description);
121         g_free(mimeinfo->id);
122         g_free(mimeinfo->location);
123
124         g_hash_table_foreach_remove(mimeinfo->typeparameters,
125                 procmime_mimeinfo_parameters_destroy, NULL);
126         g_hash_table_destroy(mimeinfo->typeparameters);
127         g_hash_table_foreach_remove(mimeinfo->dispositionparameters,
128                 procmime_mimeinfo_parameters_destroy, NULL);
129         g_hash_table_destroy(mimeinfo->dispositionparameters);
130
131         if (mimeinfo->privacy)
132                 privacy_free_privacydata(mimeinfo->privacy);
133
134         g_free(mimeinfo);
135
136         return FALSE;
137 }
138
139 void procmime_mimeinfo_free_all(MimeInfo *mimeinfo)
140 {
141         GNode *node;
142
143         if (!mimeinfo)
144                 return;
145
146         node = mimeinfo->node;
147         g_node_traverse(node, G_IN_ORDER, G_TRAVERSE_ALL, -1, free_func, NULL);
148
149         g_node_destroy(node);
150 }
151
152 MimeInfo *procmime_mimeinfo_parent(MimeInfo *mimeinfo)
153 {
154         g_return_val_if_fail(mimeinfo != NULL, NULL);
155         g_return_val_if_fail(mimeinfo->node != NULL, NULL);
156
157         if (mimeinfo->node->parent == NULL)
158                 return NULL;
159         return (MimeInfo *) mimeinfo->node->parent->data;
160 }
161
162 MimeInfo *procmime_mimeinfo_next(MimeInfo *mimeinfo)
163 {
164         g_return_val_if_fail(mimeinfo != NULL, NULL);
165         g_return_val_if_fail(mimeinfo->node != NULL, NULL);
166
167         if (mimeinfo->node->children)
168                 return (MimeInfo *) mimeinfo->node->children->data;
169         if (mimeinfo->node->next)
170                 return (MimeInfo *) mimeinfo->node->next->data;
171
172         if (mimeinfo->node->parent == NULL)
173                 return NULL;
174
175         while (mimeinfo->node->parent != NULL) {
176                 mimeinfo = (MimeInfo *) mimeinfo->node->parent->data;
177                 if (mimeinfo->node->next)
178                         return (MimeInfo *) mimeinfo->node->next->data;
179         }
180
181         return NULL;
182 }
183
184 MimeInfo *procmime_scan_message(MsgInfo *msginfo)
185 {
186         gchar *filename;
187         MimeInfo *mimeinfo;
188
189         filename = procmsg_get_message_file_path(msginfo);
190         if (!filename || !is_file_exist(filename)) {
191                 g_free(filename);
192                 filename = procmsg_get_message_file(msginfo);
193         }
194         if (!filename || !is_file_exist(filename)) 
195                 return NULL;
196
197         if (!folder_has_parent_of_type(msginfo->folder, F_QUEUE) &&
198             !folder_has_parent_of_type(msginfo->folder, F_DRAFT))
199                 mimeinfo = procmime_scan_file(filename);
200         else
201                 mimeinfo = procmime_scan_queue_file(filename);
202         g_free(filename);
203
204         return mimeinfo;
205 }
206
207 enum
208 {
209         H_CONTENT_TRANSFER_ENCODING = 0,
210         H_CONTENT_TYPE              = 1,
211         H_CONTENT_DISPOSITION       = 2,
212         H_CONTENT_DESCRIPTION       = 3,
213         H_SUBJECT                   = 4
214 };
215
216 const gchar *procmime_mimeinfo_get_parameter(MimeInfo *mimeinfo, const gchar *name)
217 {
218         const gchar *value;
219
220         g_return_val_if_fail(mimeinfo != NULL, NULL);
221         g_return_val_if_fail(name != NULL, NULL);
222
223         value = g_hash_table_lookup(mimeinfo->dispositionparameters, name);
224         if (value == NULL)
225                 value = g_hash_table_lookup(mimeinfo->typeparameters, name);
226         
227         return value;
228 }
229
230 gboolean procmime_decode_content(MimeInfo *mimeinfo)
231 {
232         gchar buf[BUFFSIZE];
233         gint readend;
234         gchar *tmpfilename;
235         FILE *outfp, *infp;
236         struct stat statbuf;
237         gboolean tmp_file = FALSE;
238
239         EncodingType encoding = forced_encoding 
240                                 ? forced_encoding
241                                 : mimeinfo->encoding_type;
242                    
243         g_return_val_if_fail(mimeinfo != NULL, FALSE);
244
245         if (encoding == ENC_UNKNOWN ||
246             encoding == ENC_BINARY)
247                 return TRUE;
248
249         infp = g_fopen(mimeinfo->data.filename, "rb");
250         if (!infp) {
251                 perror("fopen");
252                 return FALSE;
253         }
254         fseek(infp, mimeinfo->offset, SEEK_SET);
255
256         outfp = get_tmpfile_in_dir(get_mime_tmp_dir(), &tmpfilename);
257         if (!outfp) {
258                 perror("tmpfile");
259                 fclose(infp);
260                 return FALSE;
261         }
262         tmp_file = TRUE;
263         readend = mimeinfo->offset + mimeinfo->length;
264
265         if (encoding == ENC_QUOTED_PRINTABLE) {
266                 while ((ftell(infp) < readend) && (fgets(buf, sizeof(buf), infp) != NULL)) {
267                         gint len;
268                         len = qp_decode_line(buf);
269                         fwrite(buf, 1, len, outfp);
270                 }
271         } else if (encoding == ENC_BASE64) {
272                 gchar outbuf[BUFFSIZE];
273                 gint len;
274                 Base64Decoder *decoder;
275                 gboolean got_error = FALSE;
276                 gboolean uncanonicalize = FALSE;
277                 FILE *tmpfp = outfp;
278
279                 if (mimeinfo->type == MIMETYPE_TEXT ||
280                     mimeinfo->type == MIMETYPE_MESSAGE) {
281                         uncanonicalize = TRUE;
282                         tmpfp = my_tmpfile();
283                         if (!tmpfp) {
284                                 perror("tmpfile");
285                                 if (tmp_file) fclose(outfp);
286                                 fclose(infp);
287                                 return FALSE;
288                         }
289                 }
290
291                 decoder = base64_decoder_new();
292                 while ((ftell(infp) < readend) && (fgets(buf, sizeof(buf), infp) != NULL)) {
293                         len = base64_decoder_decode(decoder, buf, outbuf);
294                         if (len < 0 && !got_error) {
295                                 g_warning("Bad BASE64 content.\n");
296                                 fwrite(_("[Error decoding BASE64]\n"),
297                                         sizeof(gchar),
298                                         strlen(_("[Error decoding BASE64]\n")),
299                                         tmpfp);
300                                 got_error = TRUE;
301                                 continue;
302                         } else if (len >= 0) {
303                                 /* print out the error message only once 
304                                  * per block */
305                                 fwrite(outbuf, sizeof(gchar), len, tmpfp);
306                                 got_error = FALSE;
307                         }
308                 }
309                 base64_decoder_free(decoder);
310
311                 if (uncanonicalize) {
312                         rewind(tmpfp);
313                         while (fgets(buf, sizeof(buf), tmpfp) != NULL) {
314                                 strcrchomp(buf);
315                                 fputs(buf, outfp);
316                         }
317                         fclose(tmpfp);
318                 }
319         } else if (encoding == ENC_X_UUENCODE) {
320                 gchar outbuf[BUFFSIZE];
321                 gint len;
322                 gboolean flag = FALSE;
323
324                 while ((ftell(infp) < readend) && (fgets(buf, sizeof(buf), infp) != NULL)) {
325                         if (!flag && strncmp(buf,"begin ", 6)) continue;
326
327                         if (flag) {
328                                 len = fromuutobits(outbuf, buf);
329                                 if (len <= 0) {
330                                         if (len < 0) 
331                                                 g_warning("Bad UUENCODE content(%d)\n", len);
332                                         break;
333                                 }
334                                 fwrite(outbuf, sizeof(gchar), len, outfp);
335                         } else
336                                 flag = TRUE;
337                 }
338         } else {
339                 while ((ftell(infp) < readend) && (fgets(buf, sizeof(buf), infp) != NULL)) {
340                         fputs(buf, outfp);
341                 }
342         }
343
344         fclose(outfp);
345         fclose(infp);
346
347         stat(tmpfilename, &statbuf);
348         if (mimeinfo->tmp && (mimeinfo->data.filename != NULL))
349                 g_unlink(mimeinfo->data.filename);
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                         alertpanel_error(_("Couldn't decrypt: %s"),
824                                 privacy_get_error());
825                         return NULL;
826                 }
827         }
828         partinfo = mimeinfo;
829         while (partinfo && partinfo->type != MIMETYPE_TEXT) {
830                 partinfo = procmime_mimeinfo_next(partinfo);
831         }
832
833         if (partinfo)
834                 outfp = procmime_get_text_content(partinfo);
835
836         procmime_mimeinfo_free_all(mimeinfo);
837
838         return outfp;
839 }
840
841 gboolean procmime_msginfo_is_encrypted(MsgInfo *msginfo)
842 {
843         MimeInfo *mimeinfo, *partinfo;
844         gboolean result = FALSE;
845
846         g_return_val_if_fail(msginfo != NULL, FALSE);
847
848         mimeinfo = procmime_scan_message(msginfo);
849         if (!mimeinfo) {
850                 return FALSE;
851         }
852
853         partinfo = mimeinfo;
854         result = (find_encrypted_part(partinfo) != NULL);
855         procmime_mimeinfo_free_all(mimeinfo);
856
857         return result;
858 }
859
860 gboolean procmime_find_string_part(MimeInfo *mimeinfo, const gchar *filename,
861                                    const gchar *str, StrFindFunc find_func)
862 {
863         FILE *outfp;
864         gchar buf[BUFFSIZE];
865
866         g_return_val_if_fail(mimeinfo != NULL, FALSE);
867         g_return_val_if_fail(mimeinfo->type == MIMETYPE_TEXT, FALSE);
868         g_return_val_if_fail(str != NULL, FALSE);
869         g_return_val_if_fail(find_func != NULL, FALSE);
870
871         outfp = procmime_get_text_content(mimeinfo);
872
873         if (!outfp)
874                 return FALSE;
875
876         while (fgets(buf, sizeof(buf), outfp) != NULL) {
877                 strretchomp(buf);
878                 if (find_func(buf, str)) {
879                         fclose(outfp);
880                         return TRUE;
881                 }
882         }
883
884         fclose(outfp);
885
886         return FALSE;
887 }
888
889 gboolean procmime_find_string(MsgInfo *msginfo, const gchar *str,
890                               StrFindFunc find_func)
891 {
892         MimeInfo *mimeinfo;
893         MimeInfo *partinfo;
894         gchar *filename;
895         gboolean found = FALSE;
896
897         g_return_val_if_fail(msginfo != NULL, FALSE);
898         g_return_val_if_fail(str != NULL, FALSE);
899         g_return_val_if_fail(find_func != NULL, FALSE);
900
901         filename = procmsg_get_message_file(msginfo);
902         if (!filename) return FALSE;
903         mimeinfo = procmime_scan_message(msginfo);
904
905         for (partinfo = mimeinfo; partinfo != NULL;
906              partinfo = procmime_mimeinfo_next(partinfo)) {
907                 if (partinfo->type == MIMETYPE_TEXT) {
908                         if (procmime_find_string_part
909                                 (partinfo, filename, str, find_func) == TRUE) {
910                                 found = TRUE;
911                                 break;
912                         }
913                 }
914         }
915
916         procmime_mimeinfo_free_all(mimeinfo);
917         g_free(filename);
918
919         return found;
920 }
921
922 gchar *procmime_get_tmp_file_name(MimeInfo *mimeinfo)
923 {
924         static guint32 id = 0;
925         gchar *base;
926         gchar *filename;
927         gchar f_prefix[10];
928
929         g_return_val_if_fail(mimeinfo != NULL, NULL);
930
931         g_snprintf(f_prefix, sizeof(f_prefix), "%08x.", id++);
932
933         if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
934                 base = g_strdup("mimetmp.html");
935         else {
936                 const gchar *basetmp;
937
938                 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
939                 if (basetmp == NULL)
940                         basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
941                 if (basetmp == NULL)
942                         basetmp = "mimetmp";
943                 basetmp = g_path_get_basename(basetmp);
944                 if (*basetmp == '\0') 
945                         basetmp = g_strdup("mimetmp");
946                 base = conv_filename_from_utf8(basetmp);
947                 g_free((gchar*)basetmp);
948                 subst_for_shellsafe_filename(base);
949         }
950
951         filename = g_strconcat(get_mime_tmp_dir(), G_DIR_SEPARATOR_S,
952                                f_prefix, base, NULL);
953
954         g_free(base);
955         
956         return filename;
957 }
958
959 static GList *mime_type_list = NULL;
960
961 gchar *procmime_get_mime_type(const gchar *filename)
962 {
963         static GHashTable *mime_type_table = NULL;
964         MimeType *mime_type;
965         const gchar *p;
966         gchar *ext = NULL;
967         gchar *base;
968
969         if (!mime_type_table) {
970                 mime_type_table = procmime_get_mime_type_table();
971                 if (!mime_type_table) return NULL;
972         }
973
974         base = g_path_get_basename(filename);
975         if ((p = strrchr(base, '.')) != NULL)
976                 Xstrdup_a(ext, p + 1, p = NULL );
977         g_free(base);
978         if (!p) return NULL;
979
980         g_strdown(ext);
981         mime_type = g_hash_table_lookup(mime_type_table, ext);
982         if (mime_type) {
983                 gchar *str;
984
985                 str = g_strconcat(mime_type->type, "/", mime_type->sub_type,
986                                   NULL);
987                 return str;
988         }
989
990         return NULL;
991 }
992
993 static guint procmime_str_hash(gconstpointer gptr)
994 {
995         guint hash_result = 0;
996         const char *str;
997
998         for (str = gptr; str && *str; str++) {
999                 if (isupper(*str)) hash_result += (*str + ' ');
1000                 else hash_result += *str;
1001         }
1002
1003         return hash_result;
1004 }
1005
1006 static gint procmime_str_equal(gconstpointer gptr1, gconstpointer gptr2)
1007 {
1008         const char *str1 = gptr1;
1009         const char *str2 = gptr2;
1010
1011         return !g_utf8_collate(str1, str2);
1012 }
1013
1014 static GHashTable *procmime_get_mime_type_table(void)
1015 {
1016         GHashTable *table = NULL;
1017         GList *cur;
1018         MimeType *mime_type;
1019         gchar **exts;
1020
1021         if (!mime_type_list) {
1022                 mime_type_list = procmime_get_mime_type_list();
1023                 if (!mime_type_list) return NULL;
1024         }
1025
1026         table = g_hash_table_new(procmime_str_hash, procmime_str_equal);
1027
1028         for (cur = mime_type_list; cur != NULL; cur = cur->next) {
1029                 gint i;
1030                 gchar *key;
1031
1032                 mime_type = (MimeType *)cur->data;
1033
1034                 if (!mime_type->extension) continue;
1035
1036                 exts = g_strsplit(mime_type->extension, " ", 16);
1037                 for (i = 0; exts[i] != NULL; i++) {
1038                         /* make the key case insensitive */
1039                         g_strdown(exts[i]);
1040                         /* use previously dup'd key on overwriting */
1041                         if (g_hash_table_lookup(table, exts[i]))
1042                                 key = exts[i];
1043                         else
1044                                 key = g_strdup(exts[i]);
1045                         g_hash_table_insert(table, key, mime_type);
1046                 }
1047                 g_strfreev(exts);
1048         }
1049
1050         return table;
1051 }
1052
1053 GList *procmime_get_mime_type_list(void)
1054 {
1055         GList *list = NULL;
1056         FILE *fp;
1057         gchar buf[BUFFSIZE];
1058         gchar *p;
1059         gchar *delim;
1060         MimeType *mime_type;
1061         gboolean fp_is_glob_file = TRUE;
1062
1063         if (mime_type_list) 
1064                 return mime_type_list;
1065         
1066         if ((fp = g_fopen("/usr/share/mime/globs", "rb")) == NULL) {
1067                 fp_is_glob_file = FALSE;
1068                 if ((fp = g_fopen("/etc/mime.types", "rb")) == NULL) {
1069                         if ((fp = g_fopen(SYSCONFDIR "/mime.types", "rb")) 
1070                                 == NULL) {
1071                                 FILE_OP_ERROR(SYSCONFDIR "/mime.types", 
1072                                         "fopen");
1073                                 return NULL;
1074                         }
1075                 }
1076         }
1077
1078         while (fgets(buf, sizeof(buf), fp) != NULL) {
1079                 p = strchr(buf, '#');
1080                 if (p) *p = '\0';
1081                 g_strstrip(buf);
1082
1083                 p = buf;
1084                 
1085                 if (fp_is_glob_file) {
1086                         while (*p && !g_ascii_isspace(*p) && (*p!=':')) p++;
1087                 } else {
1088                         while (*p && !g_ascii_isspace(*p)) p++;
1089                 }
1090
1091                 if (*p) {
1092                         *p = '\0';
1093                         p++;
1094                 }
1095                 delim = strchr(buf, '/');
1096                 if (delim == NULL) continue;
1097                 *delim = '\0';
1098
1099                 mime_type = g_new(MimeType, 1);
1100                 mime_type->type = g_strdup(buf);
1101                 mime_type->sub_type = g_strdup(delim + 1);
1102
1103                 if (fp_is_glob_file) {
1104                         while (*p && (g_ascii_isspace(*p)||(*p=='*')||(*p=='.'))) p++;
1105                 } else {
1106                         while (*p && g_ascii_isspace(*p)) p++;
1107                 }
1108
1109                 if (*p)
1110                         mime_type->extension = g_strdup(p);
1111                 else
1112                         mime_type->extension = NULL;
1113
1114                 list = g_list_append(list, mime_type);
1115         }
1116
1117         fclose(fp);
1118
1119         if (!list)
1120                 g_warning("Can't read mime.types\n");
1121
1122         return list;
1123 }
1124
1125 EncodingType procmime_get_encoding_for_charset(const gchar *charset)
1126 {
1127         if (!charset)
1128                 return ENC_8BIT;
1129         else if (!g_ascii_strncasecmp(charset, "ISO-2022-", 9) ||
1130                  !g_ascii_strcasecmp(charset, "US-ASCII"))
1131                 return ENC_7BIT;
1132         else if (!g_ascii_strcasecmp(charset, "ISO-8859-5") ||
1133                  !g_ascii_strncasecmp(charset, "KOI8-", 5) ||
1134                  !g_ascii_strcasecmp(charset, "Windows-1251"))
1135                 return ENC_8BIT;
1136         else if (!g_ascii_strncasecmp(charset, "ISO-8859-", 9))
1137                 return ENC_QUOTED_PRINTABLE;
1138         else
1139                 return ENC_8BIT;
1140 }
1141
1142 EncodingType procmime_get_encoding_for_text_file(const gchar *file, gboolean *has_binary)
1143 {
1144         FILE *fp;
1145         guchar buf[BUFFSIZE];
1146         size_t len;
1147         size_t octet_chars = 0;
1148         size_t total_len = 0;
1149         gfloat octet_percentage;
1150         gboolean force_b64 = FALSE;
1151
1152         if ((fp = g_fopen(file, "rb")) == NULL) {
1153                 FILE_OP_ERROR(file, "fopen");
1154                 return ENC_UNKNOWN;
1155         }
1156
1157         while ((len = fread(buf, sizeof(guchar), sizeof(buf), fp)) > 0) {
1158                 guchar *p;
1159                 gint i;
1160
1161                 for (p = buf, i = 0; i < len; ++p, ++i) {
1162                         if (*p & 0x80)
1163                                 ++octet_chars;
1164                         if (*p == '\0') {
1165                                 force_b64 = TRUE;
1166                                 *has_binary = TRUE;
1167                         }
1168                 }
1169                 total_len += len;
1170         }
1171
1172         fclose(fp);
1173         
1174         if (total_len > 0)
1175                 octet_percentage = (gfloat)octet_chars / (gfloat)total_len;
1176         else
1177                 octet_percentage = 0.0;
1178
1179         debug_print("procmime_get_encoding_for_text_file(): "
1180                     "8bit chars: %d / %d (%f%%)\n", octet_chars, total_len,
1181                     100.0 * octet_percentage);
1182
1183         if (octet_percentage > 0.20 || force_b64) {
1184                 debug_print("using BASE64\n");
1185                 return ENC_BASE64;
1186         } else if (octet_chars > 0) {
1187                 debug_print("using quoted-printable\n");
1188                 return ENC_QUOTED_PRINTABLE;
1189         } else {
1190                 debug_print("using 7bit\n");
1191                 return ENC_7BIT;
1192         }
1193 }
1194
1195 struct EncodingTable 
1196 {
1197         gchar *str;
1198         EncodingType enc_type;
1199 };
1200
1201 struct EncodingTable encoding_table[] = {
1202         {"7bit", ENC_7BIT},
1203         {"8bit", ENC_8BIT},
1204         {"binary", ENC_BINARY},
1205         {"quoted-printable", ENC_QUOTED_PRINTABLE},
1206         {"base64", ENC_BASE64},
1207         {"x-uuencode", ENC_UNKNOWN},
1208         {NULL, ENC_UNKNOWN},
1209 };
1210
1211 const gchar *procmime_get_encoding_str(EncodingType encoding)
1212 {
1213         struct EncodingTable *enc_table;
1214         
1215         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1216                 if (enc_table->enc_type == encoding)
1217                         return enc_table->str;
1218         }
1219         return NULL;
1220 }
1221
1222 /* --- NEW MIME STUFF --- */
1223 struct TypeTable
1224 {
1225         gchar *str;
1226         MimeMediaType type;
1227 };
1228
1229 static struct TypeTable mime_type_table[] = {
1230         {"text", MIMETYPE_TEXT},
1231         {"image", MIMETYPE_IMAGE},
1232         {"audio", MIMETYPE_AUDIO},
1233         {"video", MIMETYPE_VIDEO},
1234         {"application", MIMETYPE_APPLICATION},
1235         {"message", MIMETYPE_MESSAGE},
1236         {"multipart", MIMETYPE_MULTIPART},
1237         {NULL, 0},
1238 };
1239
1240 const gchar *procmime_get_media_type_str(MimeMediaType type)
1241 {
1242         struct TypeTable *type_table;
1243         
1244         for (type_table = mime_type_table; type_table->str != NULL; type_table++) {
1245                 if (type_table->type == type)
1246                         return type_table->str;
1247         }
1248         return NULL;
1249 }
1250
1251 MimeMediaType procmime_get_media_type(const gchar *str)
1252 {
1253         struct TypeTable *typetablearray;
1254
1255         for (typetablearray = mime_type_table; typetablearray->str != NULL; typetablearray++)
1256                 if (g_ascii_strncasecmp(str, typetablearray->str, strlen(typetablearray->str)) == 0)
1257                         return typetablearray->type;
1258
1259         return MIMETYPE_UNKNOWN;
1260 }
1261
1262 /*!
1263  *\brief        Safe wrapper for content type string.
1264  *
1265  *\return       const gchar * Pointer to content type string. 
1266  */
1267 gchar *procmime_get_content_type_str(MimeMediaType type,
1268                                            const char *subtype)
1269 {
1270         const gchar *type_str = NULL;
1271
1272         if (subtype == NULL || !(type_str = procmime_get_media_type_str(type)))
1273                 return g_strdup("unknown");
1274         return g_strdup_printf("%s/%s", type_str, subtype);
1275 }
1276
1277 static int procmime_parse_mimepart(MimeInfo *parent,
1278                              gchar *content_type,
1279                              gchar *content_encoding,
1280                              gchar *content_description,
1281                              gchar *content_id,
1282                              gchar *content_disposition,
1283                              gchar *content_location,
1284                              const gchar *filename,
1285                              guint offset,
1286                              guint length);
1287
1288 void procmime_parse_message_rfc822(MimeInfo *mimeinfo)
1289 {
1290         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1291                                 {"Content-Transfer-Encoding:",
1292                                                    NULL, FALSE},
1293                                 {"Content-Description:",
1294                                                    NULL, TRUE},
1295                                 {"Content-ID:",
1296                                                    NULL, TRUE},
1297                                 {"Content-Disposition:",
1298                                                    NULL, TRUE},
1299                                 {"Content-Location:",
1300                                                    NULL, TRUE},
1301                                 {"MIME-Version:",
1302                                                    NULL, TRUE},
1303                                 {NULL,             NULL, FALSE}};
1304         guint content_start, i;
1305         FILE *fp;
1306         gchar *tmp;
1307
1308         procmime_decode_content(mimeinfo);
1309
1310         fp = g_fopen(mimeinfo->data.filename, "rb");
1311         if (fp == NULL) {
1312                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1313                 return;
1314         }
1315         fseek(fp, mimeinfo->offset, SEEK_SET);
1316         procheader_get_header_fields(fp, hentry);
1317         if (hentry[0].body != NULL) {
1318                 tmp = conv_unmime_header(hentry[0].body, NULL);
1319                 g_free(hentry[0].body);
1320                 hentry[0].body = tmp;
1321         }                
1322         if (hentry[2].body != NULL) {
1323                 tmp = conv_unmime_header(hentry[2].body, NULL);
1324                 g_free(hentry[2].body);
1325                 hentry[2].body = tmp;
1326         }                
1327         if (hentry[4].body != NULL) {
1328                 tmp = conv_unmime_header(hentry[4].body, NULL);
1329                 g_free(hentry[4].body);
1330                 hentry[4].body = tmp;
1331         }                
1332         if (hentry[5].body != NULL) {
1333                 tmp = conv_unmime_header(hentry[5].body, NULL);
1334                 g_free(hentry[5].body);
1335                 hentry[5].body = tmp;
1336         }                
1337         content_start = ftell(fp);
1338         fclose(fp);
1339         
1340         procmime_parse_mimepart(mimeinfo,
1341                                 hentry[0].body, hentry[1].body,
1342                                 hentry[2].body, hentry[3].body,
1343                                 hentry[4].body, hentry[5].body,
1344                                 mimeinfo->data.filename, content_start,
1345                                 mimeinfo->length - (content_start - mimeinfo->offset));
1346         
1347         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1348                 g_free(hentry[i].body);
1349                 hentry[i].body = NULL;
1350         }
1351 }
1352
1353 void procmime_parse_multipart(MimeInfo *mimeinfo)
1354 {
1355         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1356                                 {"Content-Transfer-Encoding:",
1357                                                    NULL, FALSE},
1358                                 {"Content-Description:",
1359                                                    NULL, TRUE},
1360                                 {"Content-ID:",
1361                                                    NULL, TRUE},
1362                                 {"Content-Disposition:",
1363                                                    NULL, TRUE},
1364                                 {"Content-Location:",
1365                                                    NULL, TRUE},
1366                                 {NULL,             NULL, FALSE}};
1367         gchar *p, *tmp;
1368         gchar *boundary;
1369         gint boundary_len = 0, lastoffset = -1, i;
1370         gchar buf[BUFFSIZE];
1371         FILE *fp;
1372         int result = 0;
1373
1374         boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
1375         if (!boundary)
1376                 return;
1377         boundary_len = strlen(boundary);
1378
1379         procmime_decode_content(mimeinfo);
1380
1381         fp = g_fopen(mimeinfo->data.filename, "rb");
1382         if (fp == NULL) {
1383                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1384                 return;
1385         }
1386         fseek(fp, mimeinfo->offset, SEEK_SET);
1387         while ((p = fgets(buf, sizeof(buf), fp)) != NULL && result == 0) {
1388                 if (ftell(fp) - 1 > (mimeinfo->offset + mimeinfo->length))
1389                         break;
1390
1391                 if (IS_BOUNDARY(buf, boundary, boundary_len)) {
1392                         if (lastoffset != -1) {
1393                                 result = procmime_parse_mimepart(mimeinfo,
1394                                                         hentry[0].body, hentry[1].body,
1395                                                         hentry[2].body, hentry[3].body, 
1396                                                         hentry[4].body, hentry[5].body,
1397                                                         mimeinfo->data.filename, lastoffset,
1398                                                         (ftell(fp) - strlen(buf)) - lastoffset - 1);
1399                         }
1400                         
1401                         if (buf[2 + boundary_len]     == '-' &&
1402                             buf[2 + boundary_len + 1] == '-')
1403                                 break;
1404
1405                         for (i = 0; i < (sizeof hentry / sizeof hentry[0]) ; i++) {
1406                                 g_free(hentry[i].body);
1407                                 hentry[i].body = NULL;
1408                         }
1409                         procheader_get_header_fields(fp, hentry);
1410                         if (hentry[0].body != NULL) {
1411                                 tmp = conv_unmime_header(hentry[0].body, NULL);
1412                                 g_free(hentry[0].body);
1413                                 hentry[0].body = tmp;
1414                         }                
1415                         if (hentry[2].body != NULL) {
1416                                 tmp = conv_unmime_header(hentry[2].body, NULL);
1417                                 g_free(hentry[2].body);
1418                                 hentry[2].body = tmp;
1419                         }                
1420                         if (hentry[4].body != NULL) {
1421                                 tmp = conv_unmime_header(hentry[4].body, NULL);
1422                                 g_free(hentry[4].body);
1423                                 hentry[4].body = tmp;
1424                         }                
1425                         if (hentry[5].body != NULL) {
1426                                 tmp = conv_unmime_header(hentry[5].body, NULL);
1427                                 g_free(hentry[5].body);
1428                                 hentry[5].body = tmp;
1429                         }                
1430                         lastoffset = ftell(fp);
1431                 }
1432         }
1433         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1434                 g_free(hentry[i].body);
1435                 hentry[i].body = NULL;
1436         }
1437         fclose(fp);
1438 }
1439
1440 static void parse_parameters(const gchar *parameters, GHashTable *table)
1441 {
1442         gchar *params, *param, *next;
1443         GSList *convlist = NULL, *concatlist = NULL, *cur;
1444
1445         params = g_strdup(parameters);
1446         param = params;
1447         next = params;
1448         for (; next != NULL; param = next) {
1449                 gchar *attribute, *value, *tmp;
1450                 gint len;
1451                 gboolean convert = FALSE;
1452
1453                 next = strchr_with_skip_quote(param, '"', ';');
1454                 if (next != NULL) {
1455                         next[0] = '\0';
1456                         next++;
1457                 }
1458
1459                 g_strstrip(param);
1460
1461                 attribute = param;
1462                 value = strchr(attribute, '=');
1463                 if (value == NULL)
1464                         continue;
1465
1466                 value[0] = '\0';
1467                 value++;
1468                 while (value[0] == ' ')
1469                         value++;
1470
1471                 g_strdown(attribute);
1472
1473                 len = strlen(attribute);
1474                 if (attribute[len - 1] == '*') {
1475                         gchar *srcpos, *dstpos, *endpos;
1476
1477                         convert = TRUE;
1478                         attribute[len - 1] = '\0';
1479
1480                         srcpos = value;
1481                         dstpos = value;
1482                         endpos = value + strlen(value);
1483                         while (srcpos < endpos) {
1484                                 if (*srcpos != '%')
1485                                         *dstpos = *srcpos;
1486                                 else {
1487                                         guchar dstvalue;
1488
1489                                         if (!get_hex_value(&dstvalue, srcpos[1], srcpos[2]))
1490                                                 *dstpos = '?';
1491                                         else
1492                                                 *dstpos = dstvalue;
1493                                         srcpos += 2;
1494                                 }
1495                                 srcpos++;
1496                                 dstpos++;
1497                         }
1498                         *dstpos = '\0';
1499                 } else {
1500                         if (value[0] == '"')
1501                                 extract_quote(value, '"');
1502                         else if ((tmp = strchr(value, ' ')) != NULL)
1503                                 *tmp = '\0';
1504                 }
1505
1506                 if (attribute) {
1507                         while (attribute[0] == ' ')
1508                                 attribute++;
1509                         while (attribute[strlen(attribute)-1] == ' ') 
1510                                 attribute[strlen(attribute)-1] = '\0';
1511                 } 
1512                 if (value) {
1513                         while (value[0] == ' ')
1514                                 value++;
1515                         while (value[strlen(value)-1] == ' ') 
1516                                 value[strlen(value)-1] = '\0';
1517                 }               
1518                 if (strrchr(attribute, '*') != NULL) {
1519                         gchar *tmpattr;
1520
1521                         tmpattr = g_strdup(attribute);
1522                         tmp = strrchr(tmpattr, '*');
1523                         tmp[0] = '\0';
1524
1525                         if ((tmp[1] == '0') && (tmp[2] == '\0') && 
1526                             (g_slist_find_custom(concatlist, attribute, g_str_equal) == NULL))
1527                                 concatlist = g_slist_prepend(concatlist, g_strdup(tmpattr));
1528
1529                         if (convert && (g_slist_find_custom(convlist, attribute, g_str_equal) == NULL))
1530                                 convlist = g_slist_prepend(convlist, g_strdup(tmpattr));
1531
1532                         g_free(tmpattr);
1533                 } else if (convert) {
1534                         if (g_slist_find_custom(convlist, attribute, g_str_equal) == NULL)
1535                                 convlist = g_slist_prepend(convlist, g_strdup(attribute));
1536                 }
1537
1538                 if (g_hash_table_lookup(table, attribute) == NULL)
1539                         g_hash_table_insert(table, g_strdup(attribute), g_strdup(value));
1540         }
1541
1542         for (cur = concatlist; cur != NULL; cur = g_slist_next(cur)) {
1543                 gchar *attribute, *attrwnum, *partvalue;
1544                 gint n = 0;
1545                 GString *value;
1546
1547                 attribute = (gchar *) cur->data;
1548                 value = g_string_sized_new(64);
1549
1550                 attrwnum = g_strdup_printf("%s*%d", attribute, n);
1551                 while ((partvalue = g_hash_table_lookup(table, attrwnum)) != NULL) {
1552                         g_string_append(value, partvalue);
1553
1554                         g_free(attrwnum);
1555                         n++;
1556                         attrwnum = g_strdup_printf("%s*%d", attribute, n);
1557                 }
1558                 g_free(attrwnum);
1559
1560                 g_hash_table_insert(table, g_strdup(attribute), g_strdup(value->str));
1561                 g_string_free(value, TRUE);
1562         }
1563         slist_free_strings(concatlist);
1564         g_slist_free(concatlist);
1565
1566         for (cur = convlist; cur != NULL; cur = g_slist_next(cur)) {
1567                 gchar *attribute, *key, *value;
1568                 gchar *charset, *lang, *oldvalue, *newvalue;
1569
1570                 attribute = (gchar *) cur->data;
1571                 if (!g_hash_table_lookup_extended(
1572                         table, attribute, (gpointer *)(gchar *) &key, (gpointer *)(gchar *) &value))
1573                         continue;
1574
1575                 charset = value;
1576                 lang = strchr(charset, '\'');
1577                 if (lang == NULL)
1578                         continue;
1579                 lang[0] = '\0';
1580                 lang++;
1581                 oldvalue = strchr(lang, '\'');
1582                 if (oldvalue == NULL)
1583                         continue;
1584                 oldvalue[0] = '\0';
1585                 oldvalue++;
1586
1587                 newvalue = conv_codeset_strdup(oldvalue, charset, CS_UTF_8);
1588
1589                 g_hash_table_remove(table, attribute);
1590                 g_free(key);
1591                 g_free(value);
1592
1593                 g_hash_table_insert(table, g_strdup(attribute), newvalue);
1594         }
1595         slist_free_strings(convlist);
1596         g_slist_free(convlist);
1597
1598         g_free(params);
1599 }       
1600
1601 static void procmime_parse_content_type(const gchar *content_type, MimeInfo *mimeinfo)
1602 {
1603         g_return_if_fail(content_type != NULL);
1604         g_return_if_fail(mimeinfo != NULL);
1605
1606         /* RFC 2045, page 13 says that the mime subtype is MANDATORY;
1607          * if it's not available we use the default Content-Type */
1608         if ((content_type[0] == '\0') || (strchr(content_type, '/') == NULL)) {
1609                 mimeinfo->type = MIMETYPE_TEXT;
1610                 mimeinfo->subtype = g_strdup("plain");
1611                 if (g_hash_table_lookup(mimeinfo->typeparameters,
1612                                        "charset") == NULL) {
1613                         g_hash_table_insert(mimeinfo->typeparameters,
1614                                     g_strdup("charset"),
1615                                     g_strdup(
1616                                         conv_get_locale_charset_str_no_utf8()));
1617                 }
1618         } else {
1619                 gchar *type, *subtype, *params;
1620
1621                 type = g_strdup(content_type);
1622                 subtype = strchr(type, '/') + 1;
1623                 *(subtype - 1) = '\0';
1624                 if ((params = strchr(subtype, ';')) != NULL) {
1625                         params[0] = '\0';
1626                         params++;
1627                 }
1628
1629                 mimeinfo->type = procmime_get_media_type(type);
1630                 mimeinfo->subtype = g_strdup(subtype);
1631
1632                 /* Get mimeinfo->typeparameters */
1633                 if (params != NULL)
1634                         parse_parameters(params, mimeinfo->typeparameters);
1635
1636                 g_free(type);
1637         }
1638 }
1639
1640 static void procmime_parse_content_disposition(const gchar *content_disposition, MimeInfo *mimeinfo)
1641 {
1642         gchar *tmp, *params;
1643
1644         g_return_if_fail(content_disposition != NULL);
1645         g_return_if_fail(mimeinfo != NULL);
1646
1647         tmp = g_strdup(content_disposition);
1648         if ((params = strchr(tmp, ';')) != NULL) {
1649                 params[0] = '\0';
1650                 params++;
1651         }       
1652         g_strstrip(tmp);
1653
1654         if (!g_ascii_strcasecmp(tmp, "inline")) 
1655                 mimeinfo->disposition = DISPOSITIONTYPE_INLINE;
1656         else if (!g_ascii_strcasecmp(tmp, "attachment"))
1657                 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1658         else
1659                 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1660         
1661         if (params != NULL)
1662                 parse_parameters(params, mimeinfo->dispositionparameters);
1663
1664         g_free(tmp);
1665 }
1666
1667
1668 static void procmime_parse_content_encoding(const gchar *content_encoding, MimeInfo *mimeinfo)
1669 {
1670         struct EncodingTable *enc_table;
1671         
1672         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1673                 if (g_ascii_strcasecmp(enc_table->str, content_encoding) == 0) {
1674                         mimeinfo->encoding_type = enc_table->enc_type;
1675                         return;
1676                 }
1677         }
1678         mimeinfo->encoding_type = ENC_UNKNOWN;
1679         return;
1680 }
1681
1682 static int procmime_parse_mimepart(MimeInfo *parent,
1683                              gchar *content_type,
1684                              gchar *content_encoding,
1685                              gchar *content_description,
1686                              gchar *content_id,
1687                              gchar *content_disposition,
1688                              gchar *content_location,
1689                              const gchar *filename,
1690                              guint offset,
1691                              guint length)
1692 {
1693         MimeInfo *mimeinfo;
1694
1695         /* Create MimeInfo */
1696         mimeinfo = procmime_mimeinfo_new();
1697         mimeinfo->content = MIMECONTENT_FILE;
1698         if (parent != NULL) {
1699                 if (g_node_depth(parent->node) > 32) {
1700                         /* 32 is an arbitrary value
1701                          * this avoids DOSsing ourselves 
1702                          * with enormous messages
1703                          */
1704                         procmime_mimeinfo_free_all(mimeinfo);
1705                         return -1;                      
1706                 }
1707                 g_node_append(parent->node, mimeinfo->node);
1708         }
1709         mimeinfo->data.filename = g_strdup(filename);
1710         mimeinfo->offset = offset;
1711         mimeinfo->length = length;
1712
1713         if (content_type != NULL) {
1714                 procmime_parse_content_type(content_type, mimeinfo);
1715         } else {
1716                 mimeinfo->type = MIMETYPE_TEXT;
1717                 mimeinfo->subtype = g_strdup("plain");
1718                 if (g_hash_table_lookup(mimeinfo->typeparameters,
1719                                        "charset") == NULL) {
1720                         g_hash_table_insert(mimeinfo->typeparameters,
1721                                     g_strdup("charset"),
1722                                     g_strdup(
1723                                         conv_get_locale_charset_str_no_utf8()));
1724                 }
1725         }
1726
1727         if (content_encoding != NULL) {
1728                 procmime_parse_content_encoding(content_encoding, mimeinfo);
1729         } else {
1730                 mimeinfo->encoding_type = ENC_UNKNOWN;
1731         }
1732
1733         if (content_description != NULL)
1734                 mimeinfo->description = g_strdup(content_description);
1735         else
1736                 mimeinfo->description = NULL;
1737
1738         if (content_id != NULL)
1739                 mimeinfo->id = g_strdup(content_id);
1740         else
1741                 mimeinfo->id = NULL;
1742
1743         if (content_location != NULL)
1744                 mimeinfo->location = g_strdup(content_location);
1745         else
1746                 mimeinfo->location = NULL;
1747
1748         if (content_disposition != NULL) 
1749                 procmime_parse_content_disposition(content_disposition, mimeinfo);
1750         else
1751                 mimeinfo->disposition = DISPOSITIONTYPE_UNKNOWN;
1752
1753         /* Call parser for mime type */
1754         switch (mimeinfo->type) {
1755                 case MIMETYPE_MESSAGE:
1756                         if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
1757                                 procmime_parse_message_rfc822(mimeinfo);
1758                         }
1759                         break;
1760                         
1761                 case MIMETYPE_MULTIPART:
1762                         procmime_parse_multipart(mimeinfo);
1763                         break;
1764                         
1765                 default:
1766                         break;
1767         }
1768
1769         return 0;
1770 }
1771
1772 static gchar *typenames[] = {
1773     "text",
1774     "image",
1775     "audio",
1776     "video",
1777     "application",
1778     "message",
1779     "multipart",
1780     "unknown",
1781 };
1782
1783 static gboolean output_func(GNode *node, gpointer data)
1784 {
1785         guint i, depth;
1786         MimeInfo *mimeinfo = (MimeInfo *) node->data;
1787
1788         depth = g_node_depth(node);
1789         for (i = 0; i < depth; i++)
1790                 printf("    ");
1791         printf("%s/%s (offset:%d length:%d encoding: %d)\n", typenames[mimeinfo->type], mimeinfo->subtype, mimeinfo->offset, mimeinfo->length, mimeinfo->encoding_type);
1792
1793         return FALSE;
1794 }
1795
1796 static void output_mime_structure(MimeInfo *mimeinfo, int indent)
1797 {
1798         g_node_traverse(mimeinfo->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1, output_func, NULL);
1799 }
1800
1801 MimeInfo *procmime_scan_file_with_offset(const gchar *filename, int offset)
1802 {
1803         MimeInfo *mimeinfo;
1804         struct stat buf;
1805
1806         stat(filename, &buf);
1807
1808         mimeinfo = procmime_mimeinfo_new();
1809         mimeinfo->content = MIMECONTENT_FILE;
1810         mimeinfo->encoding_type = ENC_UNKNOWN;
1811         mimeinfo->type = MIMETYPE_MESSAGE;
1812         mimeinfo->subtype = g_strdup("rfc822");
1813         mimeinfo->data.filename = g_strdup(filename);
1814         mimeinfo->offset = offset;
1815         mimeinfo->length = buf.st_size - offset;
1816
1817         procmime_parse_message_rfc822(mimeinfo);
1818         if (debug_get_mode())
1819                 output_mime_structure(mimeinfo, 0);
1820
1821         return mimeinfo;
1822 }
1823
1824 MimeInfo *procmime_scan_file(const gchar *filename)
1825 {
1826         MimeInfo *mimeinfo;
1827
1828         g_return_val_if_fail(filename != NULL, NULL);
1829
1830         mimeinfo = procmime_scan_file_with_offset(filename, 0);
1831
1832         return mimeinfo;
1833 }
1834
1835 MimeInfo *procmime_scan_queue_file(const gchar *filename)
1836 {
1837         FILE *fp;
1838         MimeInfo *mimeinfo;
1839         gchar buf[BUFFSIZE];
1840         gint offset = 0;
1841
1842         g_return_val_if_fail(filename != NULL, NULL);
1843
1844         /* Open file */
1845         if ((fp = g_fopen(filename, "rb")) == NULL)
1846                 return NULL;
1847         /* Skip queue header */
1848         while (fgets(buf, sizeof(buf), fp) != NULL) {
1849                 /* new way */
1850                 if (!strncmp(buf, "X-Sylpheed-End-Special-Headers: 1",
1851                         strlen("X-Sylpheed-End-Special-Headers:")))
1852                         break;
1853                 /* old way */
1854                 if (buf[0] == '\r' || buf[0] == '\n') break;
1855                 /* from other mailers */
1856                 if (!strncmp(buf, "Date: ", 6)
1857                 ||  !strncmp(buf, "To: ", 4)
1858                 ||  !strncmp(buf, "From: ", 6)
1859                 ||  !strncmp(buf, "Subject: ", 9)) {
1860                         rewind(fp);
1861                         break;
1862                 }
1863         }
1864         offset = ftell(fp);
1865         fclose(fp);
1866
1867         mimeinfo = procmime_scan_file_with_offset(filename, offset);
1868
1869         return mimeinfo;
1870 }
1871
1872 typedef enum {
1873     ENC_AS_TOKEN,
1874     ENC_AS_QUOTED_STRING,
1875     ENC_AS_EXTENDED,
1876     ENC_TO_ASCII,
1877 } EncodeAs;
1878
1879 typedef struct _ParametersData {
1880         FILE *fp;
1881         guint len;
1882         guint ascii_only;
1883 } ParametersData;
1884
1885 static void write_parameters(gpointer key, gpointer value, gpointer user_data)
1886 {
1887         gchar *param = key;
1888         gchar *val = value, *valpos, *tmp;
1889         ParametersData *pdata = (ParametersData *)user_data;
1890         GString *buf = g_string_new("");
1891
1892         EncodeAs encas = ENC_AS_TOKEN;
1893
1894         for (valpos = val; *valpos != 0; valpos++) {
1895                 if (!IS_ASCII(*valpos) || *valpos == '"') {
1896                         encas = ENC_AS_EXTENDED;
1897                         break;
1898                 }
1899             
1900                 /* CTLs */
1901                 if (((*valpos >= 0) && (*valpos < 037)) || (*valpos == 0177)) {
1902                         encas = ENC_AS_QUOTED_STRING;
1903                         continue;
1904                 }
1905
1906                 /* tspecials + SPACE */
1907                 switch (*valpos) {
1908                 case ' ':
1909                 case '(': 
1910                 case ')':
1911                 case '<':
1912                 case '>':
1913                 case '@':
1914                 case ',':
1915                 case ';':
1916                 case ':':
1917                 case '\\':
1918                 case '\'':
1919                 case '/':
1920                 case '[':
1921                 case ']':
1922                 case '?':
1923                 case '=':
1924                         encas = ENC_AS_QUOTED_STRING;
1925                         continue;
1926                 }
1927         }
1928         
1929         if (encas == ENC_AS_EXTENDED && pdata->ascii_only == TRUE) 
1930                 encas = ENC_TO_ASCII;
1931
1932         switch (encas) {
1933         case ENC_AS_TOKEN:
1934                 g_string_append_printf(buf, "%s=%s", param, val);
1935                 break;
1936
1937         case ENC_TO_ASCII:
1938                 tmp = g_strdup(val);
1939                 g_strcanon(tmp, 
1940                         " ()<>@,';:\\/[]?=.0123456789"
1941                         "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1942                         "abcdefghijklmnopqrstuvwxyz",
1943                         '_');
1944                 g_string_append_printf(buf, "%s=\"%s\"", param, tmp);
1945                 g_free(tmp);
1946                 break;
1947
1948         case ENC_AS_QUOTED_STRING:
1949                 g_string_append_printf(buf, "%s=\"%s\"", param, val);
1950                 break;
1951
1952         case ENC_AS_EXTENDED:
1953                 if (!g_utf8_validate(val, -1, NULL))
1954                         g_string_append_printf(buf, "%s*=%s''", param,
1955                                 conv_get_locale_charset_str());
1956                 else
1957                         g_string_append_printf(buf, "%s*=%s''", param,
1958                                 CS_INTERNAL);
1959                 for (valpos = val; *valpos != '\0'; valpos++) {
1960                         if (IS_ASCII(*valpos) && isalnum(*valpos)) {
1961                                 g_string_append_printf(buf, "%c", *valpos);
1962                         } else {
1963                                 gchar hexstr[3] = "XX";
1964                                 get_hex_str(hexstr, *valpos);
1965                                 g_string_append_printf(buf, "%%%s", hexstr);
1966                         }
1967                 }
1968                 break;          
1969         }
1970         
1971         if (buf->str && strlen(buf->str)) {
1972                 if (pdata->len + strlen(buf->str) + 2 > 76) {
1973                         fprintf(pdata->fp, ";\n %s", buf->str);
1974                         pdata->len = strlen(buf->str) + 1;
1975                 } else {
1976                         fprintf(pdata->fp, "; %s", buf->str);
1977                         pdata->len += strlen(buf->str) + 2;
1978                 }
1979         }
1980         g_string_free(buf, TRUE);
1981 }
1982
1983 void procmime_write_mime_header(MimeInfo *mimeinfo, FILE *fp)
1984 {
1985         struct TypeTable *type_table;
1986         ParametersData *pdata = g_new0(ParametersData, 1);
1987         debug_print("procmime_write_mime_header\n");
1988         
1989         pdata->fp = fp;
1990         pdata->ascii_only = FALSE;
1991
1992         for (type_table = mime_type_table; type_table->str != NULL; type_table++)
1993                 if (mimeinfo->type == type_table->type) {
1994                         gchar *buf = g_strdup_printf(
1995                                 "Content-Type: %s/%s", type_table->str, mimeinfo->subtype);
1996                         fprintf(fp, "%s", buf);
1997                         pdata->len = strlen(buf);
1998                         pdata->ascii_only = TRUE;
1999                         g_free(buf);
2000                         break;
2001                 }
2002         g_hash_table_foreach(mimeinfo->typeparameters, write_parameters, pdata);
2003         g_free(pdata);
2004
2005         fprintf(fp, "\n");
2006
2007         if (mimeinfo->encoding_type != ENC_UNKNOWN)
2008                 fprintf(fp, "Content-Transfer-Encoding: %s\n", procmime_get_encoding_str(mimeinfo->encoding_type));
2009
2010         if (mimeinfo->description != NULL)
2011                 fprintf(fp, "Content-Description: %s\n", mimeinfo->description);
2012
2013         if (mimeinfo->id != NULL)
2014                 fprintf(fp, "Content-ID: %s\n", mimeinfo->id);
2015
2016         if (mimeinfo->location != NULL)
2017                 fprintf(fp, "Content-Location: %s\n", mimeinfo->location);
2018
2019         if (mimeinfo->disposition != DISPOSITIONTYPE_UNKNOWN) {
2020                 ParametersData *pdata = g_new0(ParametersData, 1);
2021                 gchar *buf = NULL;
2022                 if (mimeinfo->disposition == DISPOSITIONTYPE_INLINE)
2023                         buf = g_strdup("Content-Disposition: inline");
2024                 else if (mimeinfo->disposition == DISPOSITIONTYPE_ATTACHMENT)
2025                         buf = g_strdup("Content-Disposition: attachment");
2026                 else
2027                         buf = g_strdup("Content-Disposition: unknown");
2028
2029                 fprintf(fp, "%s", buf);
2030                 pdata->len = strlen(buf);
2031                 g_free(buf);
2032
2033                 pdata->fp = fp;
2034                 pdata->ascii_only = FALSE;
2035
2036                 g_hash_table_foreach(mimeinfo->dispositionparameters, write_parameters, pdata);
2037                 g_free(pdata);
2038                 fprintf(fp, "\n");
2039         }
2040
2041         fprintf(fp, "\n");
2042 }
2043
2044 gint procmime_write_message_rfc822(MimeInfo *mimeinfo, FILE *fp)
2045 {
2046         FILE *infp;
2047         GNode *childnode;
2048         MimeInfo *child;
2049         gchar buf[BUFFSIZE];
2050         gboolean skip = FALSE;;
2051
2052         debug_print("procmime_write_message_rfc822\n");
2053
2054         /* write header */
2055         switch (mimeinfo->content) {
2056         case MIMECONTENT_FILE:
2057                 if ((infp = g_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2058                         FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2059                         return -1;
2060                 }
2061                 fseek(infp, mimeinfo->offset, SEEK_SET);
2062                 while (fgets(buf, sizeof(buf), infp) == buf) {
2063                         if (buf[0] == '\n' && buf[1] == '\0')
2064                                 break;
2065                         if (skip && (buf[0] == ' ' || buf[0] == '\t'))
2066                                 continue;
2067                         if (g_ascii_strncasecmp(buf, "Mime-Version:", 13) == 0 ||
2068                             g_ascii_strncasecmp(buf, "Content-Type:", 13) == 0 ||
2069                             g_ascii_strncasecmp(buf, "Content-Transfer-Encoding:", 26) == 0 ||
2070                             g_ascii_strncasecmp(buf, "Content-Description:", 20) == 0 ||
2071                             g_ascii_strncasecmp(buf, "Content-ID:", 11) == 0 ||
2072                             g_ascii_strncasecmp(buf, "Content-Location:", 17) == 0 ||
2073                             g_ascii_strncasecmp(buf, "Content-Disposition:", 20) == 0) {
2074                                 skip = TRUE;
2075                                 continue;
2076                         }
2077                         fwrite(buf, sizeof(gchar), strlen(buf), fp);
2078                         skip = FALSE;
2079                 }
2080                 fclose(infp);
2081                 break;
2082
2083         case MIMECONTENT_MEM:
2084                 fwrite(mimeinfo->data.mem, 
2085                                 sizeof(gchar), 
2086                                 strlen(mimeinfo->data.mem), 
2087                                 fp);
2088                 break;
2089
2090         default:
2091                 break;
2092         }
2093
2094         childnode = mimeinfo->node->children;
2095         if (childnode == NULL)
2096                 return -1;
2097
2098         child = (MimeInfo *) childnode->data;
2099         fprintf(fp, "Mime-Version: 1.0\n");
2100         procmime_write_mime_header(child, fp);
2101         return procmime_write_mimeinfo(child, fp);
2102 }
2103
2104 gint procmime_write_multipart(MimeInfo *mimeinfo, FILE *fp)
2105 {
2106         FILE *infp;
2107         GNode *childnode;
2108         gchar *boundary, *str, *str2;
2109         gchar buf[BUFFSIZE];
2110         gboolean firstboundary;
2111
2112         debug_print("procmime_write_multipart\n");
2113
2114         boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
2115
2116         switch (mimeinfo->content) {
2117         case MIMECONTENT_FILE:
2118                 if ((infp = g_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2119                         FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2120                         return -1;
2121                 }
2122                 fseek(infp, mimeinfo->offset, SEEK_SET);
2123                 while (fgets(buf, sizeof(buf), infp) == buf) {
2124                         if (IS_BOUNDARY(buf, boundary, strlen(boundary)))
2125                                 break;
2126                         fwrite(buf, sizeof(gchar), strlen(buf), fp);
2127                 }
2128                 fclose(infp);
2129                 break;
2130
2131         case MIMECONTENT_MEM:
2132                 str = g_strdup(mimeinfo->data.mem);
2133                 if (((str2 = strstr(str, boundary)) != NULL) && ((str2 - str) >= 2) &&
2134                     (*(str2 - 1) == '-') && (*(str2 - 2) == '-'))
2135                         *(str2 - 2) = '\0';
2136                 fwrite(str, sizeof(gchar), strlen(str), fp);
2137                 g_free(str);
2138                 break;
2139
2140         default:
2141                 break;
2142         }
2143
2144         childnode = mimeinfo->node->children;
2145         firstboundary = TRUE;
2146         while (childnode != NULL) {
2147                 MimeInfo *child = childnode->data;
2148
2149                 if (firstboundary)
2150                         firstboundary = FALSE;
2151                 else
2152                         fprintf(fp, "\n");
2153                 fprintf(fp, "--%s\n", boundary);
2154
2155                 procmime_write_mime_header(child, fp);
2156                 if (procmime_write_mimeinfo(child, fp) < 0)
2157                         return -1;
2158
2159                 childnode = g_node_next_sibling(childnode);
2160         }       
2161         fprintf(fp, "\n--%s--\n", boundary);
2162
2163         return 0;
2164 }
2165
2166 gint procmime_write_mimeinfo(MimeInfo *mimeinfo, FILE *fp)
2167 {
2168         FILE *infp;
2169
2170         debug_print("procmime_write_mimeinfo\n");
2171
2172         if (G_NODE_IS_LEAF(mimeinfo->node)) {
2173                 switch (mimeinfo->content) {
2174                 case MIMECONTENT_FILE:
2175                         if ((infp = g_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2176                                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2177                                 return -1;
2178                         }
2179                         copy_file_part_to_fp(infp, mimeinfo->offset, mimeinfo->length, fp);
2180                         fclose(infp);
2181                         return 0;
2182
2183                 case MIMECONTENT_MEM:
2184                         fwrite(mimeinfo->data.mem, 
2185                                         sizeof(gchar), 
2186                                         strlen(mimeinfo->data.mem), 
2187                                         fp);
2188                         return 0;
2189
2190                 default:
2191                         return 0;
2192                 }
2193         } else {
2194                 /* Call writer for mime type */
2195                 switch (mimeinfo->type) {
2196                 case MIMETYPE_MESSAGE:
2197                         if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
2198                                 return procmime_write_message_rfc822(mimeinfo, fp);
2199                         }
2200                         break;
2201                         
2202                 case MIMETYPE_MULTIPART:
2203                         return procmime_write_multipart(mimeinfo, fp);
2204                         
2205                 default:
2206                         break;
2207                 }
2208
2209                 return -1;
2210         }
2211
2212         return 0;
2213 }
2214
2215 gchar *procmime_get_part_file_name(MimeInfo *mimeinfo)
2216 {
2217         gchar *base;
2218
2219         if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
2220                 base = g_strdup("mimetmp.html");
2221         else {
2222                 const gchar *basetmp;
2223                 gchar *basename;
2224
2225                 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
2226                 if (basetmp == NULL)
2227                         basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
2228                 if (basetmp == NULL)
2229                         basetmp = "mimetmp";
2230                 basename = g_path_get_basename(basetmp);
2231                 if (*basename == '\0') {
2232                         g_free(basename);
2233                         basename = g_strdup("mimetmp");
2234                 }
2235                 base = conv_filename_from_utf8(basename);
2236                 g_free(basename);
2237                 subst_for_shellsafe_filename(base);
2238         }
2239         
2240         return base;
2241 }
2242