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