bb84330071d2e20403d883b92655ea92c51aea6f
[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                                 tmp_fp = infp;
462                                 g_free(out);
463                                 if (infp == NULL)
464                                         return FALSE;
465                         }
466                 }
467
468                 while ((len = fread(inbuf, sizeof(gchar),
469                                     B64_LINE_SIZE, tmp_fp))
470                        == B64_LINE_SIZE) {
471                         base64_encode(outbuf, inbuf, B64_LINE_SIZE);
472                         fputs(outbuf, outfp);
473                         fputc('\n', outfp);
474                 }
475                 if (len > 0 && feof(tmp_fp)) {
476                         base64_encode(outbuf, inbuf, len);
477                         fputs(outbuf, outfp);
478                         fputc('\n', outfp);
479                 }
480
481                 if (tmp_file) {
482                         fclose(tmp_fp);
483                         unlink(tmp_file);
484                         g_free(tmp_file);
485                 }
486         } else if (encoding == ENC_QUOTED_PRINTABLE) {
487                 gchar inbuf[BUFFSIZE], outbuf[BUFFSIZE * 4];
488
489                 while (fgets(inbuf, sizeof(inbuf), infp) != NULL) {
490                         qp_encode_line(outbuf, inbuf);
491
492                         if (!strncmp("From ", outbuf, sizeof("From ")-1)) {
493                                 gchar *tmpbuf = outbuf;
494                                 
495                                 tmpbuf += sizeof("From ")-1;
496                                 
497                                 fputs("=46rom ", outfp);
498                                 fputs(tmpbuf, outfp);
499                         } else 
500                                 fputs(outbuf, outfp);
501                 }
502         } else {
503                 gchar buf[BUFFSIZE];
504
505                 while (fgets(buf, sizeof(buf), infp) != NULL) {
506                         strcrchomp(buf);
507                         fputs(buf, outfp);
508                 }
509         }
510
511         fclose(outfp);
512         fclose(infp);
513
514         if (mimeinfo->content == MIMECONTENT_FILE) {
515                 if (mimeinfo->tmp && (mimeinfo->data.filename != NULL))
516                         unlink(mimeinfo->data.filename);
517                 g_free(mimeinfo->data.filename);
518         } else if (mimeinfo->content == MIMECONTENT_MEM) {
519                 if (mimeinfo->tmp && (mimeinfo->data.mem != NULL))
520                         g_free(mimeinfo->data.mem);
521         }
522
523         stat(tmpfilename, &statbuf);
524         mimeinfo->content = MIMECONTENT_FILE;
525         mimeinfo->data.filename = tmpfilename;
526         mimeinfo->tmp = TRUE;
527         mimeinfo->offset = 0;
528         mimeinfo->length = statbuf.st_size;
529         mimeinfo->encoding_type = encoding;
530
531         return TRUE;
532 }
533
534 gint procmime_get_part(const gchar *outfile, MimeInfo *mimeinfo)
535 {
536         FILE *infp, *outfp;
537         gchar buf[BUFFSIZE];
538         gint restlength, readlength;
539
540         g_return_val_if_fail(outfile != NULL, -1);
541         g_return_val_if_fail(mimeinfo != NULL, -1);
542
543         if (mimeinfo->encoding_type != ENC_BINARY && !procmime_decode_content(mimeinfo))
544                 return -1;
545
546         if ((infp = fopen(mimeinfo->data.filename, "rb")) == NULL) {
547                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
548                 return -1;
549         }
550         if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
551                 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
552                 fclose(infp);
553                 return -1;
554         }
555         if ((outfp = fopen(outfile, "wb")) == NULL) {
556                 FILE_OP_ERROR(outfile, "fopen");
557                 fclose(infp);
558                 return -1;
559         }
560
561         restlength = mimeinfo->length;
562
563         while ((restlength > 0) && ((readlength = fread(buf, 1, restlength > BUFFSIZE ? BUFFSIZE : restlength, infp)) > 0)) {
564                 fwrite(buf, 1, readlength, outfp);
565                 restlength -= readlength;
566         }
567
568         fclose(infp);
569         if (fclose(outfp) == EOF) {
570                 FILE_OP_ERROR(outfile, "fclose");
571                 unlink(outfile);
572                 return -1;
573         }
574
575         return 0;
576 }
577
578 struct ContentRenderer {
579         char * content_type;
580         char * renderer;
581 };
582
583 static GList * renderer_list = NULL;
584
585 static struct ContentRenderer *
586 content_renderer_new(char * content_type, char * renderer)
587 {
588         struct ContentRenderer * cr;
589
590         cr = g_new(struct ContentRenderer, 1);
591         if (cr == NULL)
592                 return NULL;
593
594         cr->content_type = g_strdup(content_type);
595         cr->renderer = g_strdup(renderer);
596
597         return cr;
598 }
599
600 static void content_renderer_free(struct ContentRenderer * cr)
601 {
602         g_free(cr->content_type);
603         g_free(cr->renderer);
604         g_free(cr);
605 }
606
607 void renderer_read_config(void)
608 {
609         gchar buf[BUFFSIZE];
610         FILE * f;
611         gchar * rcpath;
612
613         g_list_foreach(renderer_list, (GFunc) content_renderer_free, NULL);
614         renderer_list = NULL;
615
616         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, RENDERER_RC, NULL);
617         f = fopen(rcpath, "rb");
618         g_free(rcpath);
619         
620         if (f == NULL)
621                 return;
622
623         while (fgets(buf, BUFFSIZE, f)) {
624                 char * p;
625                 struct ContentRenderer * cr;
626
627                 strretchomp(buf);
628                 p = strchr(buf, ' ');
629                 if (p == NULL)
630                         continue;
631                 * p = 0;
632
633                 cr = content_renderer_new(buf, p + 1);
634                 if (cr == NULL)
635                         continue;
636
637                 renderer_list = g_list_append(renderer_list, cr);
638         }
639
640         fclose(f);
641 }
642
643 void renderer_write_config(void)
644 {
645         gchar * rcpath;
646         PrefFile *pfile;
647         GList * cur;
648
649         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, RENDERER_RC, NULL);
650         
651         if ((pfile = prefs_write_open(rcpath)) == NULL) {
652                 g_warning("failed to write configuration to file\n");
653                 g_free(rcpath);
654                 return;
655         }
656
657         g_free(rcpath);
658
659         for (cur = renderer_list ; cur != NULL ; cur = cur->next) {
660                 struct ContentRenderer * renderer;
661                 renderer = cur->data;
662                 fprintf(pfile->fp, "%s %s\n", renderer->content_type,
663                         renderer->renderer);
664         }
665
666         if (prefs_file_close(pfile) < 0) {
667                 g_warning("failed to write configuration to file\n");
668                 return;
669         }
670 }
671
672 FILE *procmime_get_text_content(MimeInfo *mimeinfo)
673 {
674         FILE *tmpfp, *outfp;
675         const gchar *src_codeset;
676         gboolean conv_fail = FALSE;
677         gchar buf[BUFFSIZE];
678         gchar *str;
679         struct ContentRenderer * renderer;
680         GList * cur;
681         gchar *tmpfile, *content_type;
682     
683         g_return_val_if_fail(mimeinfo != NULL, NULL);
684
685         if (!procmime_decode_content(mimeinfo))
686                 return NULL;
687
688         tmpfile = procmime_get_tmp_file_name(mimeinfo);
689         if (tmpfile == NULL)
690                 return NULL;
691
692         if (procmime_get_part(tmpfile, mimeinfo) < 0) {
693                 g_free(tmpfile);
694                 return NULL;
695         }
696
697         tmpfp = fopen(tmpfile, "rb");
698         if (tmpfp == NULL) {
699                 g_free(tmpfile);
700                 return NULL;
701         }
702
703         if ((outfp = my_tmpfile()) == NULL) {
704                 perror("tmpfile");
705                 fclose(tmpfp);
706                 g_free(tmpfile);
707                 return NULL;
708         }
709
710         src_codeset = forced_charset
711                       ? forced_charset : 
712                       procmime_mimeinfo_get_parameter(mimeinfo, "charset");
713
714         renderer = NULL;
715
716         content_type = procmime_get_content_type_str(mimeinfo->type,
717                                                      mimeinfo->subtype);
718         for (cur = renderer_list ; cur != NULL ; cur = cur->next) {
719                 struct ContentRenderer * cr;
720
721                 cr = cur->data;
722                 if (g_ascii_strcasecmp(cr->content_type, content_type) == 0) {
723                         renderer = cr;
724                         break;
725                 }
726         }
727         g_free(content_type);
728
729         if (renderer != NULL) {
730                 FILE * p;
731                 int oldout;
732                 
733                 oldout = dup(1);
734                 
735                 dup2(fileno(outfp), 1);
736                 
737                 p = popen(renderer->renderer, "w");
738                 if (p != NULL) {
739                         size_t count;
740                         
741                         while ((count =
742                                 fread(buf, sizeof(char), sizeof(buf),
743                                       tmpfp)) > 0)
744                                 fwrite(buf, sizeof(char), count, p);
745                         pclose(p);
746                 }
747                 
748                 dup2(oldout, 1);
749 /* CodeConverter seems to have no effect here */
750         } else if (mimeinfo->type == MIMETYPE_TEXT && !g_ascii_strcasecmp(mimeinfo->subtype, "html")) {
751                 HTMLParser *parser;
752                 CodeConverter *conv;
753
754                 conv = conv_code_converter_new(src_codeset);
755                 parser = html_parser_new(tmpfp, conv);
756                 while ((str = html_parse(parser)) != NULL) {
757                         fputs(str, outfp);
758                 }
759                 html_parser_destroy(parser);
760                 conv_code_converter_destroy(conv);
761         } else if (mimeinfo->type == MIMETYPE_TEXT && !g_ascii_strcasecmp(mimeinfo->subtype, "enriched")) {
762                 ERTFParser *parser;
763                 CodeConverter *conv;
764
765                 conv = conv_code_converter_new(src_codeset);
766                 parser = ertf_parser_new(tmpfp, conv);
767                 while ((str = ertf_parse(parser)) != NULL) {
768                         fputs(str, outfp);
769                 }
770                 ertf_parser_destroy(parser);
771                 conv_code_converter_destroy(conv);
772         } else if (mimeinfo->type == MIMETYPE_TEXT) {
773                 while (fgets(buf, sizeof(buf), tmpfp) != NULL) {
774                         str = conv_codeset_strdup(buf, src_codeset, CS_UTF_8);
775                         if (str) {
776                                 fputs(str, outfp);
777                                 g_free(str);
778                         } else {
779                                 conv_fail = TRUE;
780                                 fputs(buf, outfp);
781                         }
782                 }
783         }
784
785         if (conv_fail)
786                 g_warning("procmime_get_text_content(): Code conversion failed.\n");
787
788         fclose(tmpfp);
789         rewind(outfp);
790         unlink(tmpfile);
791         g_free(tmpfile);
792
793         return outfp;
794 }
795
796 /* search the first text part of (multipart) MIME message,
797    decode, convert it and output to outfp. */
798 FILE *procmime_get_first_text_content(MsgInfo *msginfo)
799 {
800         FILE *outfp = NULL;
801         MimeInfo *mimeinfo, *partinfo;
802
803         g_return_val_if_fail(msginfo != NULL, NULL);
804
805         mimeinfo = procmime_scan_message(msginfo);
806         if (!mimeinfo) return NULL;
807
808         partinfo = mimeinfo;
809         while (partinfo && partinfo->type != MIMETYPE_TEXT)
810                 partinfo = procmime_mimeinfo_next(partinfo);
811
812         if (partinfo)
813                 outfp = procmime_get_text_content(partinfo);
814
815         procmime_mimeinfo_free_all(mimeinfo);
816
817         return outfp;
818 }
819
820 gboolean procmime_find_string_part(MimeInfo *mimeinfo, const gchar *filename,
821                                    const gchar *str, StrFindFunc find_func)
822 {
823         FILE *outfp;
824         gchar buf[BUFFSIZE];
825
826         g_return_val_if_fail(mimeinfo != NULL, FALSE);
827         g_return_val_if_fail(mimeinfo->type == MIMETYPE_TEXT, FALSE);
828         g_return_val_if_fail(str != NULL, FALSE);
829         g_return_val_if_fail(find_func != NULL, FALSE);
830
831         outfp = procmime_get_text_content(mimeinfo);
832
833         if (!outfp)
834                 return FALSE;
835
836         while (fgets(buf, sizeof(buf), outfp) != NULL) {
837                 strretchomp(buf);
838                 if (find_func(buf, str)) {
839                         fclose(outfp);
840                         return TRUE;
841                 }
842         }
843
844         fclose(outfp);
845
846         return FALSE;
847 }
848
849 gboolean procmime_find_string(MsgInfo *msginfo, const gchar *str,
850                               StrFindFunc find_func)
851 {
852         MimeInfo *mimeinfo;
853         MimeInfo *partinfo;
854         gchar *filename;
855         gboolean found = FALSE;
856
857         g_return_val_if_fail(msginfo != NULL, FALSE);
858         g_return_val_if_fail(str != NULL, FALSE);
859         g_return_val_if_fail(find_func != NULL, FALSE);
860
861         filename = procmsg_get_message_file(msginfo);
862         if (!filename) return FALSE;
863         mimeinfo = procmime_scan_message(msginfo);
864
865         for (partinfo = mimeinfo; partinfo != NULL;
866              partinfo = procmime_mimeinfo_next(partinfo)) {
867                 if (partinfo->type == MIMETYPE_TEXT) {
868                         if (procmime_find_string_part
869                                 (partinfo, filename, str, find_func) == TRUE) {
870                                 found = TRUE;
871                                 break;
872                         }
873                 }
874         }
875
876         procmime_mimeinfo_free_all(mimeinfo);
877         g_free(filename);
878
879         return found;
880 }
881
882 gchar *procmime_get_tmp_file_name(MimeInfo *mimeinfo)
883 {
884         static guint32 id = 0;
885         gchar *base;
886         gchar *filename;
887         gchar f_prefix[10];
888
889         g_return_val_if_fail(mimeinfo != NULL, NULL);
890
891         g_snprintf(f_prefix, sizeof(f_prefix), "%08x.", id++);
892
893         if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
894                 base = g_strdup("mimetmp.html");
895         else {
896                 const gchar *basetmp;
897
898                 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
899                 if (basetmp == NULL)
900                         basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
901                 if (basetmp == NULL)
902                         basetmp = "mimetmp";
903                 basetmp = g_path_get_basename(basetmp);
904                 if (*basetmp == '\0') basetmp = g_strdup("mimetmp");
905                 base = conv_filename_from_utf8(basetmp);
906                 subst_for_shellsafe_filename(base);
907         }
908
909         filename = g_strconcat(get_mime_tmp_dir(), G_DIR_SEPARATOR_S,
910                                f_prefix, base, NULL);
911
912         g_free(base);
913         
914         return filename;
915 }
916
917 static GList *mime_type_list = NULL;
918
919 gchar *procmime_get_mime_type(const gchar *filename)
920 {
921         static GHashTable *mime_type_table = NULL;
922         MimeType *mime_type;
923         const gchar *p;
924         gchar *ext = NULL;
925         gchar *base;
926
927         if (!mime_type_table) {
928                 mime_type_table = procmime_get_mime_type_table();
929                 if (!mime_type_table) return NULL;
930         }
931
932         base = g_path_get_basename(filename);
933         if ((p = strrchr(base, '.')) != NULL)
934                 Xstrdup_a(ext, p + 1, p = NULL );
935         g_free(base);
936         if (!p) return NULL;
937
938         g_strdown(ext);
939         mime_type = g_hash_table_lookup(mime_type_table, ext);
940         if (mime_type) {
941                 gchar *str;
942
943                 str = g_strconcat(mime_type->type, "/", mime_type->sub_type,
944                                   NULL);
945                 return str;
946         }
947
948         return NULL;
949 }
950
951 static guint procmime_str_hash(gconstpointer gptr)
952 {
953         guint hash_result = 0;
954         const char *str;
955
956         for (str = gptr; str && *str; str++) {
957                 if (isupper(*str)) hash_result += (*str + ' ');
958                 else hash_result += *str;
959         }
960
961         return hash_result;
962 }
963
964 static gint procmime_str_equal(gconstpointer gptr1, gconstpointer gptr2)
965 {
966         const char *str1 = gptr1;
967         const char *str2 = gptr2;
968
969         return !g_utf8_collate(str1, str2);
970 }
971
972 static GHashTable *procmime_get_mime_type_table(void)
973 {
974         GHashTable *table = NULL;
975         GList *cur;
976         MimeType *mime_type;
977         gchar **exts;
978
979         if (!mime_type_list) {
980                 mime_type_list = procmime_get_mime_type_list();
981                 if (!mime_type_list) return NULL;
982         }
983
984         table = g_hash_table_new(procmime_str_hash, procmime_str_equal);
985
986         for (cur = mime_type_list; cur != NULL; cur = cur->next) {
987                 gint i;
988                 gchar *key;
989
990                 mime_type = (MimeType *)cur->data;
991
992                 if (!mime_type->extension) continue;
993
994                 exts = g_strsplit(mime_type->extension, " ", 16);
995                 for (i = 0; exts[i] != NULL; i++) {
996                         /* make the key case insensitive */
997                         g_strdown(exts[i]);
998                         /* use previously dup'd key on overwriting */
999                         if (g_hash_table_lookup(table, exts[i]))
1000                                 key = exts[i];
1001                         else
1002                                 key = g_strdup(exts[i]);
1003                         g_hash_table_insert(table, key, mime_type);
1004                 }
1005                 g_strfreev(exts);
1006         }
1007
1008         return table;
1009 }
1010
1011 GList *procmime_get_mime_type_list(void)
1012 {
1013         GList *list = NULL;
1014         FILE *fp;
1015         gchar buf[BUFFSIZE];
1016         guchar *p;
1017         gchar *delim;
1018         MimeType *mime_type;
1019         gboolean fp_is_glob_file = TRUE;
1020
1021         if (mime_type_list) 
1022                 return mime_type_list;
1023         
1024         if ((fp = fopen("/usr/share/mime/globs", "rb")) == NULL) {
1025                 fp_is_glob_file = FALSE;
1026                 if ((fp = fopen("/etc/mime.types", "rb")) == NULL) {
1027                         if ((fp = fopen(SYSCONFDIR "/mime.types", "rb")) 
1028                                 == NULL) {
1029                                 FILE_OP_ERROR(SYSCONFDIR "/mime.types", 
1030                                         "fopen");
1031                                 return NULL;
1032                         }
1033                 }
1034         }
1035
1036         while (fgets(buf, sizeof(buf), fp) != NULL) {
1037                 p = strchr(buf, '#');
1038                 if (p) *p = '\0';
1039                 g_strstrip(buf);
1040
1041                 p = buf;
1042                 
1043                 if (fp_is_glob_file) {
1044                         while (*p && !isspace(*p) && (*p!=':')) p++;
1045                 } else {
1046                         while (*p && !isspace(*p)) p++;
1047                 }
1048
1049                 if (*p) {
1050                         *p = '\0';
1051                         p++;
1052                 }
1053                 delim = strchr(buf, '/');
1054                 if (delim == NULL) continue;
1055                 *delim = '\0';
1056
1057                 mime_type = g_new(MimeType, 1);
1058                 mime_type->type = g_strdup(buf);
1059                 mime_type->sub_type = g_strdup(delim + 1);
1060
1061                 if (fp_is_glob_file) {
1062                         while (*p && (isspace(*p)||(*p=='*')||(*p=='.'))) p++;
1063                 } else {
1064                         while (*p && isspace(*p)) p++;
1065                 }
1066
1067                 if (*p)
1068                         mime_type->extension = g_strdup(p);
1069                 else
1070                         mime_type->extension = NULL;
1071
1072                 list = g_list_append(list, mime_type);
1073         }
1074
1075         fclose(fp);
1076
1077         if (!list)
1078                 g_warning("Can't read mime.types\n");
1079
1080         return list;
1081 }
1082
1083 EncodingType procmime_get_encoding_for_charset(const gchar *charset)
1084 {
1085         if (!charset)
1086                 return ENC_8BIT;
1087         else if (!g_ascii_strncasecmp(charset, "ISO-2022-", 9) ||
1088                  !g_ascii_strcasecmp(charset, "US-ASCII"))
1089                 return ENC_7BIT;
1090         else if (!g_ascii_strcasecmp(charset, "ISO-8859-5") ||
1091                  !g_ascii_strncasecmp(charset, "KOI8-", 5) ||
1092                  !g_ascii_strcasecmp(charset, "Windows-1251"))
1093                 return ENC_8BIT;
1094         else if (!g_ascii_strncasecmp(charset, "ISO-8859-", 9))
1095                 return ENC_QUOTED_PRINTABLE;
1096         else
1097                 return ENC_8BIT;
1098 }
1099
1100 EncodingType procmime_get_encoding_for_text_file(const gchar *file)
1101 {
1102         FILE *fp;
1103         guchar buf[BUFFSIZE];
1104         size_t len;
1105         size_t octet_chars = 0;
1106         size_t total_len = 0;
1107         gfloat octet_percentage;
1108
1109         if ((fp = fopen(file, "rb")) == NULL) {
1110                 FILE_OP_ERROR(file, "fopen");
1111                 return ENC_UNKNOWN;
1112         }
1113
1114         while ((len = fread(buf, sizeof(guchar), sizeof(buf), fp)) > 0) {
1115                 guchar *p;
1116                 gint i;
1117
1118                 for (p = buf, i = 0; i < len; ++p, ++i) {
1119                         if (*p & 0x80)
1120                                 ++octet_chars;
1121                 }
1122                 total_len += len;
1123         }
1124
1125         fclose(fp);
1126         
1127         if (total_len > 0)
1128                 octet_percentage = (gfloat)octet_chars / (gfloat)total_len;
1129         else
1130                 octet_percentage = 0.0;
1131
1132         debug_print("procmime_get_encoding_for_text_file(): "
1133                     "8bit chars: %d / %d (%f%%)\n", octet_chars, total_len,
1134                     100.0 * octet_percentage);
1135
1136         if (octet_percentage > 0.20) {
1137                 debug_print("using BASE64\n");
1138                 return ENC_BASE64;
1139         } else if (octet_chars > 0) {
1140                 debug_print("using quoted-printable\n");
1141                 return ENC_QUOTED_PRINTABLE;
1142         } else {
1143                 debug_print("using 7bit\n");
1144                 return ENC_7BIT;
1145         }
1146 }
1147
1148 struct EncodingTable 
1149 {
1150         gchar *str;
1151         EncodingType enc_type;
1152 };
1153
1154 struct EncodingTable encoding_table[] = {
1155         {"7bit", ENC_7BIT},
1156         {"8bit", ENC_8BIT},
1157         {"binary", ENC_BINARY},
1158         {"quoted-printable", ENC_QUOTED_PRINTABLE},
1159         {"base64", ENC_BASE64},
1160         {"x-uuencode", ENC_UNKNOWN},
1161         {NULL, ENC_UNKNOWN},
1162 };
1163
1164 const gchar *procmime_get_encoding_str(EncodingType encoding)
1165 {
1166         struct EncodingTable *enc_table;
1167         
1168         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1169                 if (enc_table->enc_type == encoding)
1170                         return enc_table->str;
1171         }
1172         return NULL;
1173 }
1174
1175 /* --- NEW MIME STUFF --- */
1176 struct TypeTable
1177 {
1178         gchar *str;
1179         MimeMediaType type;
1180 };
1181
1182 static struct TypeTable mime_type_table[] = {
1183         {"text", MIMETYPE_TEXT},
1184         {"image", MIMETYPE_IMAGE},
1185         {"audio", MIMETYPE_AUDIO},
1186         {"video", MIMETYPE_VIDEO},
1187         {"application", MIMETYPE_APPLICATION},
1188         {"message", MIMETYPE_MESSAGE},
1189         {"multipart", MIMETYPE_MULTIPART},
1190         {NULL, 0},
1191 };
1192
1193 const gchar *procmime_get_media_type_str(MimeMediaType type)
1194 {
1195         struct TypeTable *type_table;
1196         
1197         for (type_table = mime_type_table; type_table->str != NULL; type_table++) {
1198                 if (type_table->type == type)
1199                         return type_table->str;
1200         }
1201         return NULL;
1202 }
1203
1204 MimeMediaType procmime_get_media_type(const gchar *str)
1205 {
1206         struct TypeTable *typetablearray;
1207
1208         for (typetablearray = mime_type_table; typetablearray->str != NULL; typetablearray++)
1209                 if (g_ascii_strncasecmp(str, typetablearray->str, strlen(typetablearray->str)) == 0)
1210                         return typetablearray->type;
1211
1212         return MIMETYPE_UNKNOWN;
1213 }
1214
1215 /*!
1216  *\brief        Safe wrapper for content type string.
1217  *
1218  *\return       const gchar * Pointer to content type string. 
1219  */
1220 gchar *procmime_get_content_type_str(MimeMediaType type,
1221                                            const char *subtype)
1222 {
1223         const gchar *type_str = NULL;
1224
1225         if (subtype == NULL || !(type_str = procmime_get_media_type_str(type)))
1226                 return g_strdup("unknown");
1227         return g_strdup_printf("%s/%s", type_str, subtype);
1228 }
1229
1230 int procmime_parse_mimepart(MimeInfo *parent,
1231                              gchar *content_type,
1232                              gchar *content_encoding,
1233                              gchar *content_description,
1234                              gchar *content_id,
1235                              gchar *content_disposition,
1236                              const gchar *filename,
1237                              guint offset,
1238                              guint length);
1239
1240 void procmime_parse_message_rfc822(MimeInfo *mimeinfo)
1241 {
1242         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1243                                 {"Content-Transfer-Encoding:",
1244                                                    NULL, FALSE},
1245                                 {"Content-Description:",
1246                                                    NULL, TRUE},
1247                                 {"Content-ID:",
1248                                                    NULL, TRUE},
1249                                 {"Content-Disposition:",
1250                                                    NULL, TRUE},
1251                                 {"MIME-Version:",
1252                                                    NULL, TRUE},
1253                                 {NULL,             NULL, FALSE}};
1254         guint content_start, i;
1255         FILE *fp;
1256         gint mime_major, mime_minor;
1257         gchar *tmp;
1258
1259         procmime_decode_content(mimeinfo);
1260
1261         fp = fopen(mimeinfo->data.filename, "rb");
1262         if (fp == NULL) {
1263                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1264                 return;
1265         }
1266         fseek(fp, mimeinfo->offset, SEEK_SET);
1267         procheader_get_header_fields(fp, hentry);
1268         if (hentry[0].body != NULL) {
1269                 tmp = conv_unmime_header(hentry[0].body, NULL);
1270                 g_free(hentry[0].body);
1271                 hentry[0].body = tmp;
1272         }                
1273         if (hentry[2].body != NULL) {
1274                 tmp = conv_unmime_header(hentry[2].body, NULL);
1275                 g_free(hentry[2].body);
1276                 hentry[2].body = tmp;
1277         }                
1278         if (hentry[4].body != NULL) {
1279                 tmp = conv_unmime_header(hentry[4].body, NULL);
1280                 g_free(hentry[4].body);
1281                 hentry[4].body = tmp;
1282         }                
1283         content_start = ftell(fp);
1284         fclose(fp);
1285
1286         if ((hentry[5].body != NULL) &&
1287             (sscanf(hentry[5].body, "%d.%d", &mime_major, &mime_minor) == 2) &&
1288             (mime_major == 1) && (mime_minor == 0)) {
1289                 procmime_parse_mimepart(mimeinfo,
1290                                         hentry[0].body, hentry[1].body,
1291                                         hentry[2].body, hentry[3].body, 
1292                                         hentry[4].body, 
1293                                         mimeinfo->data.filename, content_start,
1294                                         mimeinfo->length - (content_start - mimeinfo->offset));
1295         } else {
1296                 MimeInfo *subinfo;
1297
1298                 subinfo = procmime_mimeinfo_new();
1299                 subinfo->content = MIMECONTENT_FILE;
1300                 subinfo->encoding_type = ENC_UNKNOWN;
1301                 subinfo->type = MIMETYPE_TEXT;
1302                 subinfo->subtype = g_strdup("plain");
1303                 subinfo->data.filename = g_strdup(mimeinfo->data.filename);
1304                 subinfo->offset = content_start;
1305                 subinfo->length = mimeinfo->length - (content_start - mimeinfo->offset);
1306
1307                 g_node_append(mimeinfo->node, subinfo->node);
1308         }
1309         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1310                 g_free(hentry[i].body);
1311                 hentry[i].body = NULL;
1312         }
1313 }
1314
1315 void procmime_parse_multipart(MimeInfo *mimeinfo)
1316 {
1317         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1318                                 {"Content-Transfer-Encoding:",
1319                                                    NULL, FALSE},
1320                                 {"Content-Description:",
1321                                                    NULL, TRUE},
1322                                 {"Content-ID:",
1323                                                    NULL, TRUE},
1324                                 {"Content-Disposition:",
1325                                                    NULL, TRUE},
1326                                 {NULL,             NULL, FALSE}};
1327         gchar *p, *tmp;
1328         gchar *boundary;
1329         gint boundary_len = 0, lastoffset = -1, i;
1330         gchar buf[BUFFSIZE];
1331         FILE *fp;
1332         int result = 0;
1333
1334         boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
1335         if (!boundary)
1336                 return;
1337         boundary_len = strlen(boundary);
1338
1339         procmime_decode_content(mimeinfo);
1340
1341         fp = fopen(mimeinfo->data.filename, "rb");
1342         if (fp == NULL) {
1343                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1344                 return;
1345         }
1346         fseek(fp, mimeinfo->offset, SEEK_SET);
1347         while ((p = fgets(buf, sizeof(buf), fp)) != NULL && result == 0) {
1348                 if (ftell(fp) > (mimeinfo->offset + mimeinfo->length))
1349                         break;
1350
1351                 if (IS_BOUNDARY(buf, boundary, boundary_len)) {
1352                         if (lastoffset != -1) {
1353                                 result = procmime_parse_mimepart(mimeinfo,
1354                                                         hentry[0].body, hentry[1].body,
1355                                                         hentry[2].body, hentry[3].body, 
1356                                                         hentry[4].body, 
1357                                                         mimeinfo->data.filename, lastoffset,
1358                                                         (ftell(fp) - strlen(buf)) - lastoffset - 1);
1359                         }
1360                         
1361                         if (buf[2 + boundary_len]     == '-' &&
1362                             buf[2 + boundary_len + 1] == '-')
1363                                 break;
1364
1365                         for (i = 0; i < (sizeof hentry / sizeof hentry[0]) ; i++) {
1366                                 g_free(hentry[i].body);
1367                                 hentry[i].body = NULL;
1368                         }
1369                         procheader_get_header_fields(fp, hentry);
1370                         if (hentry[0].body != NULL) {
1371                                 tmp = conv_unmime_header(hentry[0].body, NULL);
1372                                 g_free(hentry[0].body);
1373                                 hentry[0].body = tmp;
1374                         }                
1375                         if (hentry[2].body != NULL) {
1376                                 tmp = conv_unmime_header(hentry[2].body, NULL);
1377                                 g_free(hentry[2].body);
1378                                 hentry[2].body = tmp;
1379                         }                
1380                         if (hentry[4].body != NULL) {
1381                                 tmp = conv_unmime_header(hentry[4].body, NULL);
1382                                 g_free(hentry[4].body);
1383                                 hentry[4].body = tmp;
1384                         }                
1385                         lastoffset = ftell(fp);
1386                 }
1387         }
1388         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1389                 g_free(hentry[i].body);
1390                 hentry[i].body = NULL;
1391         }
1392         fclose(fp);
1393 }
1394
1395 static void parse_parameters(const gchar *parameters, GHashTable *table)
1396 {
1397         gchar *params, *param, *next;
1398         GSList *convlist = NULL, *concatlist = NULL, *cur;
1399
1400         params = g_strdup(parameters);
1401         param = params;
1402         next = params;
1403         for (; next != NULL; param = next) {
1404                 gchar *attribute, *value, *tmp;
1405                 gint len;
1406                 gboolean convert = FALSE;
1407
1408                 next = strchr_with_skip_quote(param, '"', ';');
1409                 if (next != NULL) {
1410                         next[0] = '\0';
1411                         next++;
1412                 }
1413
1414                 g_strstrip(param);
1415
1416                 attribute = param;
1417                 value = strchr(attribute, '=');
1418                 if (value == NULL)
1419                         continue;
1420
1421                 value[0] = '\0';
1422                 value++;
1423
1424                 g_strdown(attribute);
1425
1426                 len = strlen(attribute);
1427                 if (attribute[len - 1] == '*') {
1428                         gchar *srcpos, *dstpos, *endpos;
1429
1430                         convert = TRUE;
1431                         attribute[len - 1] = '\0';
1432
1433                         srcpos = value;
1434                         dstpos = value;
1435                         endpos = value + strlen(value);
1436                         while (srcpos < endpos) {
1437                                 if (*srcpos != '%')
1438                                         *dstpos = *srcpos;
1439                                 else {
1440                                         guchar dstvalue;
1441
1442                                         if (!get_hex_value(&dstvalue, srcpos[1], srcpos[2]))
1443                                                 *dstpos = '?';
1444                                         else
1445                                                 *dstpos = dstvalue;
1446                                         srcpos += 2;
1447                                 }
1448                                 srcpos++;
1449                                 dstpos++;
1450                         }
1451                         *dstpos = '\0';
1452                 } else {
1453                         if (value[0] == '"')
1454                                 extract_quote(value, '"');
1455                         else if ((tmp = strchr(value, ' ')) != NULL)
1456                                 *tmp = '\0';
1457                 }
1458
1459                 if (strrchr(attribute, '*') != NULL) {
1460                         gchar *tmpattr;
1461
1462                         tmpattr = g_strdup(attribute);
1463                         tmp = strrchr(tmpattr, '*');
1464                         tmp[0] = '\0';
1465
1466                         if ((tmp[1] == '0') && (tmp[2] == '\0') && 
1467                             (g_slist_find_custom(concatlist, attribute, g_str_equal) == NULL))
1468                                 concatlist = g_slist_prepend(concatlist, g_strdup(tmpattr));
1469
1470                         if (convert && (g_slist_find_custom(convlist, attribute, g_str_equal) == NULL))
1471                                 convlist = g_slist_prepend(convlist, g_strdup(tmpattr));
1472
1473                         g_free(tmpattr);
1474                 } else if (convert) {
1475                         if (g_slist_find_custom(convlist, attribute, g_str_equal) == NULL)
1476                                 convlist = g_slist_prepend(convlist, g_strdup(attribute));
1477                 }
1478
1479                 if (g_hash_table_lookup(table, attribute) == NULL)
1480                         g_hash_table_insert(table, g_strdup(attribute), g_strdup(value));
1481         }
1482
1483         for (cur = concatlist; cur != NULL; cur = g_slist_next(cur)) {
1484                 gchar *attribute, *attrwnum, *partvalue;
1485                 gint n = 0;
1486                 GString *value;
1487
1488                 attribute = (gchar *) cur->data;
1489                 value = g_string_sized_new(64);
1490
1491                 attrwnum = g_strdup_printf("%s*%d", attribute, n);
1492                 while ((partvalue = g_hash_table_lookup(table, attrwnum)) != NULL) {
1493                         g_string_append(value, partvalue);
1494
1495                         g_free(attrwnum);
1496                         n++;
1497                         attrwnum = g_strdup_printf("%s*%d", attribute, n);
1498                 }
1499                 g_free(attrwnum);
1500
1501                 g_hash_table_insert(table, g_strdup(attribute), g_strdup(value->str));
1502                 g_string_free(value, TRUE);
1503         }
1504         slist_free_strings(concatlist);
1505         g_slist_free(concatlist);
1506
1507         for (cur = convlist; cur != NULL; cur = g_slist_next(cur)) {
1508                 gchar *attribute, *key, *value;
1509                 gchar *charset, *lang, *oldvalue, *newvalue;
1510
1511                 attribute = (gchar *) cur->data;
1512                 if (!g_hash_table_lookup_extended(table, attribute, (gpointer *) &key, (gpointer *) &value))
1513                         continue;
1514
1515                 charset = value;
1516                 lang = strchr(charset, '\'');
1517                 if (lang == NULL)
1518                         continue;
1519                 lang[0] = '\0';
1520                 lang++;
1521                 oldvalue = strchr(lang, '\'');
1522                 if (oldvalue == NULL)
1523                         continue;
1524                 oldvalue[0] = '\0';
1525                 oldvalue++;
1526
1527                 newvalue = conv_codeset_strdup(oldvalue, charset, CS_UTF_8);
1528
1529                 g_hash_table_remove(table, attribute);
1530                 g_free(key);
1531                 g_free(value);
1532
1533                 g_hash_table_insert(table, g_strdup(attribute), newvalue);
1534         }
1535         slist_free_strings(convlist);
1536         g_slist_free(convlist);
1537
1538         g_free(params);
1539 }       
1540
1541 static void procmime_parse_content_type(const gchar *content_type, MimeInfo *mimeinfo)
1542 {
1543         g_return_if_fail(content_type != NULL);
1544         g_return_if_fail(mimeinfo != NULL);
1545
1546         /* RFC 2045, page 13 says that the mime subtype is MANDATORY;
1547          * if it's not available we use the default Content-Type */
1548         if ((content_type[0] == '\0') || (strchr(content_type, '/') == NULL)) {
1549                 mimeinfo->type = MIMETYPE_TEXT;
1550                 mimeinfo->subtype = g_strdup("plain");
1551                 if (g_hash_table_lookup(mimeinfo->typeparameters,
1552                                        "charset") == NULL)
1553                         g_hash_table_insert(mimeinfo->typeparameters,
1554                                             g_strdup("charset"),
1555                                             g_strdup("us-ascii"));
1556         } else {
1557                 gchar *type, *subtype, *params;
1558
1559                 type = g_strdup(content_type);
1560                 subtype = strchr(type, '/') + 1;
1561                 *(subtype - 1) = '\0';
1562                 if ((params = strchr(subtype, ';')) != NULL) {
1563                         params[0] = '\0';
1564                         params++;
1565                 }
1566
1567                 mimeinfo->type = procmime_get_media_type(type);
1568                 mimeinfo->subtype = g_strdup(subtype);
1569
1570                 /* Get mimeinfo->typeparameters */
1571                 if (params != NULL)
1572                         parse_parameters(params, mimeinfo->typeparameters);
1573
1574                 g_free(type);
1575         }
1576 }
1577
1578 static void procmime_parse_content_disposition(const gchar *content_disposition, MimeInfo *mimeinfo)
1579 {
1580         gchar *tmp, *params;
1581
1582         g_return_if_fail(content_disposition != NULL);
1583         g_return_if_fail(mimeinfo != NULL);
1584
1585         tmp = g_strdup(content_disposition);
1586         if ((params = strchr(tmp, ';')) != NULL) {
1587                 params[0] = '\0';
1588                 params++;
1589         }       
1590         g_strstrip(tmp);
1591
1592         if (!g_ascii_strcasecmp(tmp, "inline")) 
1593                 mimeinfo->disposition = DISPOSITIONTYPE_INLINE;
1594         else if (!g_ascii_strcasecmp(tmp, "attachment"))
1595                 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1596         else
1597                 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1598         
1599         if (params != NULL)
1600                 parse_parameters(params, mimeinfo->dispositionparameters);
1601
1602         g_free(tmp);
1603 }
1604
1605
1606 static void procmime_parse_content_encoding(const gchar *content_encoding, MimeInfo *mimeinfo)
1607 {
1608         struct EncodingTable *enc_table;
1609         
1610         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1611                 if (g_ascii_strcasecmp(enc_table->str, content_encoding) == 0) {
1612                         mimeinfo->encoding_type = enc_table->enc_type;
1613                         return;
1614                 }
1615         }
1616         mimeinfo->encoding_type = ENC_UNKNOWN;
1617         return;
1618 }
1619
1620 int procmime_parse_mimepart(MimeInfo *parent,
1621                              gchar *content_type,
1622                              gchar *content_encoding,
1623                              gchar *content_description,
1624                              gchar *content_id,
1625                              gchar *content_disposition,
1626                              const gchar *filename,
1627                              guint offset,
1628                              guint length)
1629 {
1630         MimeInfo *mimeinfo;
1631
1632         /* Create MimeInfo */
1633         mimeinfo = procmime_mimeinfo_new();
1634         mimeinfo->content = MIMECONTENT_FILE;
1635         if (parent != NULL) {
1636                 if (g_node_depth(parent->node) > 32) {
1637                         /* 32 is an arbitrary value
1638                          * this avoids DOSsing ourselves 
1639                          * with enormous messages
1640                          */
1641                         procmime_mimeinfo_free_all(mimeinfo);
1642                         return -1;                      
1643                 }
1644                 g_node_append(parent->node, mimeinfo->node);
1645         }
1646         mimeinfo->data.filename = g_strdup(filename);
1647         mimeinfo->offset = offset;
1648         mimeinfo->length = length;
1649
1650         if (content_type != NULL) {
1651                 procmime_parse_content_type(content_type, mimeinfo);
1652         } else {
1653                 mimeinfo->type = MIMETYPE_TEXT;
1654                 mimeinfo->subtype = g_strdup("plain");
1655                 if (g_hash_table_lookup(mimeinfo->typeparameters,
1656                                        "charset") == NULL)
1657                         g_hash_table_insert(mimeinfo->typeparameters, g_strdup("charset"), g_strdup("us-ascii"));
1658         }
1659
1660         if (content_encoding != NULL) {
1661                 procmime_parse_content_encoding(content_encoding, mimeinfo);
1662         } else {
1663                 mimeinfo->encoding_type = ENC_UNKNOWN;
1664         }
1665
1666         if (content_description != NULL)
1667                 mimeinfo->description = g_strdup(content_description);
1668         else
1669                 mimeinfo->description = NULL;
1670
1671         if (content_id != NULL)
1672                 mimeinfo->id = g_strdup(content_id);
1673         else
1674                 mimeinfo->id = NULL;
1675
1676         if (content_disposition != NULL) 
1677                 procmime_parse_content_disposition(content_disposition, mimeinfo);
1678         else
1679                 mimeinfo->disposition = DISPOSITIONTYPE_UNKNOWN;
1680
1681         /* Call parser for mime type */
1682         switch (mimeinfo->type) {
1683                 case MIMETYPE_MESSAGE:
1684                         if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
1685                                 procmime_parse_message_rfc822(mimeinfo);
1686                         }
1687                         break;
1688                         
1689                 case MIMETYPE_MULTIPART:
1690                         procmime_parse_multipart(mimeinfo);
1691                         break;
1692                         
1693                 default:
1694                         break;
1695         }
1696
1697         return 0;
1698 }
1699
1700 static gchar *typenames[] = {
1701     "text",
1702     "image",
1703     "audio",
1704     "video",
1705     "application",
1706     "message",
1707     "multipart",
1708     "unknown",
1709 };
1710
1711 static gboolean output_func(GNode *node, gpointer data)
1712 {
1713         guint i, depth;
1714         MimeInfo *mimeinfo = (MimeInfo *) node->data;
1715
1716         depth = g_node_depth(node);
1717         for (i = 0; i < depth; i++)
1718                 printf("    ");
1719         printf("%s/%s (offset:%d length:%d encoding: %d)\n", typenames[mimeinfo->type], mimeinfo->subtype, mimeinfo->offset, mimeinfo->length, mimeinfo->encoding_type);
1720
1721         return FALSE;
1722 }
1723
1724 static void output_mime_structure(MimeInfo *mimeinfo, int indent)
1725 {
1726         g_node_traverse(mimeinfo->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1, output_func, NULL);
1727 }
1728
1729 MimeInfo *procmime_scan_file_with_offset(const gchar *filename, int offset)
1730 {
1731         MimeInfo *mimeinfo;
1732         struct stat buf;
1733
1734         stat(filename, &buf);
1735
1736         mimeinfo = procmime_mimeinfo_new();
1737         mimeinfo->content = MIMECONTENT_FILE;
1738         mimeinfo->encoding_type = ENC_UNKNOWN;
1739         mimeinfo->type = MIMETYPE_MESSAGE;
1740         mimeinfo->subtype = g_strdup("rfc822");
1741         mimeinfo->data.filename = g_strdup(filename);
1742         mimeinfo->offset = offset;
1743         mimeinfo->length = buf.st_size - offset;
1744
1745         procmime_parse_message_rfc822(mimeinfo);
1746         if (debug_get_mode())
1747                 output_mime_structure(mimeinfo, 0);
1748
1749         return mimeinfo;
1750 }
1751
1752 MimeInfo *procmime_scan_file(const gchar *filename)
1753 {
1754         MimeInfo *mimeinfo;
1755
1756         g_return_val_if_fail(filename != NULL, NULL);
1757
1758         mimeinfo = procmime_scan_file_with_offset(filename, 0);
1759
1760         return mimeinfo;
1761 }
1762
1763 MimeInfo *procmime_scan_queue_file(const gchar *filename)
1764 {
1765         FILE *fp;
1766         MimeInfo *mimeinfo;
1767         gchar buf[BUFFSIZE];
1768         gint offset = 0;
1769
1770         g_return_val_if_fail(filename != NULL, NULL);
1771
1772         /* Open file */
1773         if ((fp = fopen(filename, "rb")) == NULL)
1774                 return NULL;
1775         /* Skip queue header */
1776         while (fgets(buf, sizeof(buf), fp) != NULL)
1777                 if (buf[0] == '\r' || buf[0] == '\n') break;
1778         offset = ftell(fp);
1779         fclose(fp);
1780
1781         mimeinfo = procmime_scan_file_with_offset(filename, offset);
1782
1783         return mimeinfo;
1784 }
1785
1786 typedef enum {
1787     ENC_AS_TOKEN,
1788     ENC_AS_QUOTED_STRING,
1789     ENC_AS_EXTENDED,
1790 } EncodeAs;
1791
1792 typedef struct _ParametersData {
1793         FILE *fp;
1794         guint len;
1795 } ParametersData;
1796
1797 static void write_parameters(gpointer key, gpointer value, gpointer user_data)
1798 {
1799         gchar *param = key;
1800         gchar *val = value, *valpos;
1801         ParametersData *pdata = (ParametersData *)user_data;
1802         GString *buf = g_string_new("");
1803
1804         EncodeAs encas = ENC_AS_TOKEN;
1805
1806         for (valpos = val; *valpos != 0; valpos++) {
1807                 if (!IS_ASCII(*valpos)) {
1808                         encas = ENC_AS_EXTENDED;
1809                         break;
1810                 }
1811             
1812                 /* CTLs */
1813                 if (((*valpos >= 0) && (*valpos < 037)) || (*valpos == 0177)) {
1814                         encas = ENC_AS_QUOTED_STRING;
1815                         continue;
1816                 }
1817
1818                 /* tspecials + SPACE */
1819                 switch (*valpos) {
1820                 case ' ':
1821                 case '(': 
1822                 case ')':
1823                 case '<':
1824                 case '>':
1825                 case '@':
1826                 case ',':
1827                 case ';':
1828                 case ':':
1829                 case '\\':
1830                 case '"':
1831                 case '/':
1832                 case '[':
1833                 case ']':
1834                 case '?':
1835                 case '=':
1836                         encas = ENC_AS_QUOTED_STRING;
1837                         continue;
1838                 }
1839         }
1840
1841         switch (encas) {
1842         case ENC_AS_TOKEN:
1843                 g_string_append_printf(buf, "%s=%s", param, val);
1844                 break;
1845
1846         case ENC_AS_QUOTED_STRING:
1847                 g_string_append_printf(buf, "%s=\"%s\"", param, val);
1848                 break;
1849
1850         case ENC_AS_EXTENDED:
1851                 if (!g_utf8_validate(val, -1, NULL))
1852                         g_string_append_printf(buf, "%s*=%s''", param,
1853                                 conv_get_locale_charset_str());
1854                 else
1855                         g_string_append_printf(buf, "%s*=%s''", param,
1856                                 CS_INTERNAL);
1857                 for (valpos = val; *valpos != '\0'; valpos++) {
1858                         if (IS_ASCII(*valpos) && isalnum(*valpos)) {
1859                                 g_string_append_printf(buf, "%c", *valpos);
1860                         } else {
1861                                 gchar hexstr[3] = "XX";
1862                                 get_hex_str(hexstr, *valpos);
1863                                 g_string_append_printf(buf, "%%%s", hexstr);
1864                         }
1865                 }
1866                 break;
1867         }
1868         
1869         if (buf->str && strlen(buf->str)) {
1870                 if (pdata->len + strlen(buf->str) + 2 > 76) {
1871                         fprintf(pdata->fp, ";\n %s", buf->str);
1872                         pdata->len = strlen(buf->str) + 1;
1873                 } else {
1874                         fprintf(pdata->fp, "; %s", buf->str);
1875                         pdata->len += strlen(buf->str) + 2;
1876                 }
1877         }
1878         g_string_free(buf, TRUE);
1879 }
1880
1881 void procmime_write_mime_header(MimeInfo *mimeinfo, FILE *fp)
1882 {
1883         struct TypeTable *type_table;
1884         ParametersData *pdata = g_new0(ParametersData, 1);
1885         debug_print("procmime_write_mime_header\n");
1886         
1887         pdata->fp = fp;
1888
1889         for (type_table = mime_type_table; type_table->str != NULL; type_table++)
1890                 if (mimeinfo->type == type_table->type) {
1891                         gchar *buf = g_strdup_printf(
1892                                 "Content-Type: %s/%s", type_table->str, mimeinfo->subtype);
1893                         fprintf(fp, "%s", buf);
1894                         pdata->len = strlen(buf);
1895                         g_free(buf);
1896                         break;
1897                 }
1898         g_hash_table_foreach(mimeinfo->typeparameters, write_parameters, pdata);
1899         g_free(pdata);
1900
1901         fprintf(fp, "\n");
1902
1903         if (mimeinfo->encoding_type != ENC_UNKNOWN)
1904                 fprintf(fp, "Content-Transfer-Encoding: %s\n", procmime_get_encoding_str(mimeinfo->encoding_type));
1905
1906         if (mimeinfo->description != NULL)
1907                 fprintf(fp, "Content-Description: %s\n", mimeinfo->description);
1908
1909         if (mimeinfo->id != NULL)
1910                 fprintf(fp, "Content-ID: %s\n", mimeinfo->id);
1911
1912         if (mimeinfo->disposition != DISPOSITIONTYPE_UNKNOWN) {
1913                 ParametersData *pdata = g_new0(ParametersData, 1);
1914                 gchar *buf = NULL;
1915                 if (mimeinfo->disposition == DISPOSITIONTYPE_INLINE)
1916                         buf = g_strdup("Content-Disposition: inline");
1917                 else if (mimeinfo->disposition == DISPOSITIONTYPE_ATTACHMENT)
1918                         buf = g_strdup("Content-Disposition: attachment");
1919                 else
1920                         buf = g_strdup("Content-Disposition: unknown");
1921
1922                 fprintf(fp, "%s", buf);
1923                 pdata->len = strlen(buf);
1924                 g_free(buf);
1925
1926                 pdata->fp = fp;
1927                 g_hash_table_foreach(mimeinfo->dispositionparameters, write_parameters, pdata);
1928                 g_free(pdata);
1929                 fprintf(fp, "\n");
1930         }
1931
1932         fprintf(fp, "\n");
1933 }
1934
1935 gint procmime_write_message_rfc822(MimeInfo *mimeinfo, FILE *fp)
1936 {
1937         FILE *infp;
1938         GNode *childnode;
1939         MimeInfo *child;
1940         gchar buf[BUFFSIZE];
1941         gboolean skip = FALSE;;
1942
1943         debug_print("procmime_write_message_rfc822\n");
1944
1945         /* write header */
1946         switch (mimeinfo->content) {
1947         case MIMECONTENT_FILE:
1948                 if ((infp = fopen(mimeinfo->data.filename, "rb")) == NULL) {
1949                         FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1950                         return -1;
1951                 }
1952                 fseek(infp, mimeinfo->offset, SEEK_SET);
1953                 while (fgets(buf, sizeof(buf), infp) == buf) {
1954                         if (buf[0] == '\n' && buf[1] == '\0')
1955                                 break;
1956                         if (skip && (buf[0] == ' ' || buf[0] == '\t'))
1957                                 continue;
1958                         if (g_ascii_strncasecmp(buf, "Mime-Version:", 13) == 0 ||
1959                             g_ascii_strncasecmp(buf, "Content-Type:", 13) == 0 ||
1960                             g_ascii_strncasecmp(buf, "Content-Transfer-Encoding:", 26) == 0 ||
1961                             g_ascii_strncasecmp(buf, "Content-Description:", 20) == 0 ||
1962                             g_ascii_strncasecmp(buf, "Content-ID:", 11) == 0 ||
1963                             g_ascii_strncasecmp(buf, "Content-Disposition:", 20) == 0) {
1964                                 skip = TRUE;
1965                                 continue;
1966                         }
1967                         fwrite(buf, sizeof(gchar), strlen(buf), fp);
1968                         skip = FALSE;
1969                 }
1970                 fclose(infp);
1971                 break;
1972
1973         case MIMECONTENT_MEM:
1974                 fwrite(mimeinfo->data.mem, strlen(mimeinfo->data.mem), sizeof(gchar), fp);
1975                 break;
1976
1977         default:
1978                 break;
1979         }
1980
1981         childnode = mimeinfo->node->children;
1982         if (childnode == NULL)
1983                 return -1;
1984
1985         child = (MimeInfo *) childnode->data;
1986         fprintf(fp, "Mime-Version: 1.0\n");
1987         procmime_write_mime_header(child, fp);
1988         return procmime_write_mimeinfo(child, fp);
1989 }
1990
1991 gint procmime_write_multipart(MimeInfo *mimeinfo, FILE *fp)
1992 {
1993         FILE *infp;
1994         GNode *childnode;
1995         gchar *boundary, *str, *str2;
1996         gchar buf[BUFFSIZE];
1997         gboolean firstboundary;
1998
1999         debug_print("procmime_write_multipart\n");
2000
2001         boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
2002
2003         switch (mimeinfo->content) {
2004         case MIMECONTENT_FILE:
2005                 if ((infp = fopen(mimeinfo->data.filename, "rb")) == NULL) {
2006                         FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2007                         return -1;
2008                 }
2009                 fseek(infp, mimeinfo->offset, SEEK_SET);
2010                 while (fgets(buf, sizeof(buf), infp) == buf) {
2011                         if (IS_BOUNDARY(buf, boundary, strlen(boundary)))
2012                                 break;
2013                         fwrite(buf, sizeof(gchar), strlen(buf), fp);
2014                 }
2015                 fclose(infp);
2016                 break;
2017
2018         case MIMECONTENT_MEM:
2019                 str = g_strdup(mimeinfo->data.mem);
2020                 if (((str2 = strstr(str, boundary)) != NULL) && ((str2 - str) >= 2) &&
2021                     (*(str2 - 1) == '-') && (*(str2 - 2) == '-'))
2022                         *(str2 - 2) = '\0';
2023                 fwrite(str, strlen(str), sizeof(gchar), fp);
2024                 g_free(str);
2025                 break;
2026
2027         default:
2028                 break;
2029         }
2030
2031         childnode = mimeinfo->node->children;
2032         firstboundary = TRUE;
2033         while (childnode != NULL) {
2034                 MimeInfo *child = childnode->data;
2035
2036                 if (firstboundary)
2037                         firstboundary = FALSE;
2038                 else
2039                         fprintf(fp, "\n");
2040                 fprintf(fp, "--%s\n", boundary);
2041
2042                 procmime_write_mime_header(child, fp);
2043                 if (procmime_write_mimeinfo(child, fp) < 0)
2044                         return -1;
2045
2046                 childnode = g_node_next_sibling(childnode);
2047         }       
2048         fprintf(fp, "\n--%s--\n", boundary);
2049
2050         return 0;
2051 }
2052
2053 gint procmime_write_mimeinfo(MimeInfo *mimeinfo, FILE *fp)
2054 {
2055         FILE *infp;
2056
2057         debug_print("procmime_write_mimeinfo\n");
2058
2059         if (G_NODE_IS_LEAF(mimeinfo->node)) {
2060                 switch (mimeinfo->content) {
2061                 case MIMECONTENT_FILE:
2062                         if ((infp = fopen(mimeinfo->data.filename, "rb")) == NULL) {
2063                                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2064                                 return -1;
2065                         }
2066                         copy_file_part_to_fp(infp, mimeinfo->offset, mimeinfo->length, fp);
2067                         fclose(infp);
2068                         return 0;
2069
2070                 case MIMECONTENT_MEM:
2071                         fwrite(mimeinfo->data.mem, strlen(mimeinfo->data.mem), sizeof(gchar), fp);
2072                         return 0;
2073
2074                 default:
2075                         return 0;
2076                 }
2077         } else {
2078                 /* Call writer for mime type */
2079                 switch (mimeinfo->type) {
2080                 case MIMETYPE_MESSAGE:
2081                         if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0)
2082                                 return procmime_write_message_rfc822(mimeinfo, fp);
2083                         break;
2084                         
2085                 case MIMETYPE_MULTIPART:
2086                         return procmime_write_multipart(mimeinfo, fp);
2087                         
2088                 default:
2089                         break;
2090                 }
2091
2092                 return -1;
2093         }
2094
2095         return 0;
2096 }
2097
2098 gchar *procmime_get_part_file_name(MimeInfo *mimeinfo)
2099 {
2100         gchar *base;
2101
2102         if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
2103                 base = g_strdup("mimetmp.html");
2104         else {
2105                 const gchar *basetmp;
2106                 gchar *basename;
2107
2108                 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
2109                 if (basetmp == NULL)
2110                         basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
2111                 if (basetmp == NULL)
2112                         basetmp = "mimetmp";
2113                 basename = g_path_get_basename(basetmp);
2114                 if (*basename == '\0') {
2115                         g_free(basename);
2116                         basename = g_strdup("mimetmp");
2117                 }
2118                 base = conv_filename_from_utf8(basename);
2119                 g_free(basename);
2120                 subst_for_shellsafe_filename(base);
2121         }
2122         
2123         return base;
2124 }
2125