2005-06-08 [colin] 1.9.11cvs49
[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+1], 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         gboolean fp_is_glob_file = TRUE;
1019
1020         if (mime_type_list) 
1021                 return mime_type_list;
1022         
1023         if ((fp = fopen("/usr/share/mime/globs", "rb")) == NULL) {
1024                 fp_is_glob_file = FALSE;
1025                 if ((fp = fopen("/etc/mime.types", "rb")) == NULL) {
1026                         if ((fp = fopen(SYSCONFDIR "/mime.types", "rb")) 
1027                                 == NULL) {
1028                                 FILE_OP_ERROR(SYSCONFDIR "/mime.types", 
1029                                         "fopen");
1030                                 return NULL;
1031                         }
1032                 }
1033         }
1034
1035         while (fgets(buf, sizeof(buf), fp) != NULL) {
1036                 p = strchr(buf, '#');
1037                 if (p) *p = '\0';
1038                 g_strstrip(buf);
1039
1040                 p = buf;
1041                 
1042                 if (fp_is_glob_file) {
1043                         while (*p && !isspace(*p) && (*p!=':')) p++;
1044                 } else {
1045                         while (*p && !isspace(*p)) p++;
1046                 }
1047
1048                 if (*p) {
1049                         *p = '\0';
1050                         p++;
1051                 }
1052                 delim = strchr(buf, '/');
1053                 if (delim == NULL) continue;
1054                 *delim = '\0';
1055
1056                 mime_type = g_new(MimeType, 1);
1057                 mime_type->type = g_strdup(buf);
1058                 mime_type->sub_type = g_strdup(delim + 1);
1059
1060                 if (fp_is_glob_file) {
1061                         while (*p && (isspace(*p)||(*p=='*')||(*p=='.'))) p++;
1062                 } else {
1063                         while (*p && isspace(*p)) p++;
1064                 }
1065
1066                 if (*p)
1067                         mime_type->extension = g_strdup(p);
1068                 else
1069                         mime_type->extension = NULL;
1070
1071                 list = g_list_append(list, mime_type);
1072         }
1073
1074         fclose(fp);
1075
1076         if (!list)
1077                 g_warning("Can't read mime.types\n");
1078
1079         return list;
1080 }
1081
1082 EncodingType procmime_get_encoding_for_charset(const gchar *charset)
1083 {
1084         if (!charset)
1085                 return ENC_8BIT;
1086         else if (!g_ascii_strncasecmp(charset, "ISO-2022-", 9) ||
1087                  !g_ascii_strcasecmp(charset, "US-ASCII"))
1088                 return ENC_7BIT;
1089         else if (!g_ascii_strcasecmp(charset, "ISO-8859-5") ||
1090                  !g_ascii_strncasecmp(charset, "KOI8-", 5) ||
1091                  !g_ascii_strcasecmp(charset, "Windows-1251"))
1092                 return ENC_8BIT;
1093         else if (!g_ascii_strncasecmp(charset, "ISO-8859-", 9))
1094                 return ENC_QUOTED_PRINTABLE;
1095         else
1096                 return ENC_8BIT;
1097 }
1098
1099 EncodingType procmime_get_encoding_for_text_file(const gchar *file)
1100 {
1101         FILE *fp;
1102         guchar buf[BUFFSIZE];
1103         size_t len;
1104         size_t octet_chars = 0;
1105         size_t total_len = 0;
1106         gfloat octet_percentage;
1107
1108         if ((fp = fopen(file, "rb")) == NULL) {
1109                 FILE_OP_ERROR(file, "fopen");
1110                 return ENC_UNKNOWN;
1111         }
1112
1113         while ((len = fread(buf, sizeof(guchar), sizeof(buf), fp)) > 0) {
1114                 guchar *p;
1115                 gint i;
1116
1117                 for (p = buf, i = 0; i < len; ++p, ++i) {
1118                         if (*p & 0x80)
1119                                 ++octet_chars;
1120                 }
1121                 total_len += len;
1122         }
1123
1124         fclose(fp);
1125         
1126         if (total_len > 0)
1127                 octet_percentage = (gfloat)octet_chars / (gfloat)total_len;
1128         else
1129                 octet_percentage = 0.0;
1130
1131         debug_print("procmime_get_encoding_for_text_file(): "
1132                     "8bit chars: %d / %d (%f%%)\n", octet_chars, total_len,
1133                     100.0 * octet_percentage);
1134
1135         if (octet_percentage > 0.20) {
1136                 debug_print("using BASE64\n");
1137                 return ENC_BASE64;
1138         } else if (octet_chars > 0) {
1139                 debug_print("using quoted-printable\n");
1140                 return ENC_QUOTED_PRINTABLE;
1141         } else {
1142                 debug_print("using 7bit\n");
1143                 return ENC_7BIT;
1144         }
1145 }
1146
1147 struct EncodingTable 
1148 {
1149         gchar *str;
1150         EncodingType enc_type;
1151 };
1152
1153 struct EncodingTable encoding_table[] = {
1154         {"7bit", ENC_7BIT},
1155         {"8bit", ENC_8BIT},
1156         {"binary", ENC_BINARY},
1157         {"quoted-printable", ENC_QUOTED_PRINTABLE},
1158         {"base64", ENC_BASE64},
1159         {"x-uuencode", ENC_UNKNOWN},
1160         {NULL, ENC_UNKNOWN},
1161 };
1162
1163 const gchar *procmime_get_encoding_str(EncodingType encoding)
1164 {
1165         struct EncodingTable *enc_table;
1166         
1167         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1168                 if (enc_table->enc_type == encoding)
1169                         return enc_table->str;
1170         }
1171         return NULL;
1172 }
1173
1174 /* --- NEW MIME STUFF --- */
1175 struct TypeTable
1176 {
1177         gchar *str;
1178         MimeMediaType type;
1179 };
1180
1181 static struct TypeTable mime_type_table[] = {
1182         {"text", MIMETYPE_TEXT},
1183         {"image", MIMETYPE_IMAGE},
1184         {"audio", MIMETYPE_AUDIO},
1185         {"video", MIMETYPE_VIDEO},
1186         {"application", MIMETYPE_APPLICATION},
1187         {"message", MIMETYPE_MESSAGE},
1188         {"multipart", MIMETYPE_MULTIPART},
1189         {NULL, 0},
1190 };
1191
1192 const gchar *procmime_get_media_type_str(MimeMediaType type)
1193 {
1194         struct TypeTable *type_table;
1195         
1196         for (type_table = mime_type_table; type_table->str != NULL; type_table++) {
1197                 if (type_table->type == type)
1198                         return type_table->str;
1199         }
1200         return NULL;
1201 }
1202
1203 MimeMediaType procmime_get_media_type(const gchar *str)
1204 {
1205         struct TypeTable *typetablearray;
1206
1207         for (typetablearray = mime_type_table; typetablearray->str != NULL; typetablearray++)
1208                 if (g_ascii_strncasecmp(str, typetablearray->str, strlen(typetablearray->str)) == 0)
1209                         return typetablearray->type;
1210
1211         return MIMETYPE_UNKNOWN;
1212 }
1213
1214 /*!
1215  *\brief        Safe wrapper for content type string.
1216  *
1217  *\return       const gchar * Pointer to content type string. 
1218  */
1219 gchar *procmime_get_content_type_str(MimeMediaType type,
1220                                            const char *subtype)
1221 {
1222         const gchar *type_str = NULL;
1223
1224         if (subtype == NULL || !(type_str = procmime_get_media_type_str(type)))
1225                 return g_strdup("unknown");
1226         return g_strdup_printf("%s/%s", type_str, subtype);
1227 }
1228
1229 int procmime_parse_mimepart(MimeInfo *parent,
1230                              gchar *content_type,
1231                              gchar *content_encoding,
1232                              gchar *content_description,
1233                              gchar *content_id,
1234                              gchar *content_disposition,
1235                              const gchar *filename,
1236                              guint offset,
1237                              guint length);
1238
1239 void procmime_parse_message_rfc822(MimeInfo *mimeinfo)
1240 {
1241         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1242                                 {"Content-Transfer-Encoding:",
1243                                                    NULL, FALSE},
1244                                 {"Content-Description:",
1245                                                    NULL, TRUE},
1246                                 {"Content-ID:",
1247                                                    NULL, TRUE},
1248                                 {"Content-Disposition:",
1249                                                    NULL, TRUE},
1250                                 {"MIME-Version:",
1251                                                    NULL, TRUE},
1252                                 {NULL,             NULL, FALSE}};
1253         guint content_start, i;
1254         FILE *fp;
1255         gint mime_major, mime_minor;
1256         gchar *tmp;
1257
1258         procmime_decode_content(mimeinfo);
1259
1260         fp = fopen(mimeinfo->data.filename, "rb");
1261         if (fp == NULL) {
1262                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1263                 return;
1264         }
1265         fseek(fp, mimeinfo->offset, SEEK_SET);
1266         procheader_get_header_fields(fp, hentry);
1267         if (hentry[0].body != NULL) {
1268                 tmp = conv_unmime_header(hentry[0].body, NULL);
1269                 g_free(hentry[0].body);
1270                 hentry[0].body = tmp;
1271         }                
1272         if (hentry[2].body != NULL) {
1273                 tmp = conv_unmime_header(hentry[2].body, NULL);
1274                 g_free(hentry[2].body);
1275                 hentry[2].body = tmp;
1276         }                
1277         if (hentry[4].body != NULL) {
1278                 tmp = conv_unmime_header(hentry[4].body, NULL);
1279                 g_free(hentry[4].body);
1280                 hentry[4].body = tmp;
1281         }                
1282         content_start = ftell(fp);
1283         fclose(fp);
1284
1285         if ((hentry[5].body != NULL) &&
1286             (sscanf(hentry[5].body, "%d.%d", &mime_major, &mime_minor) == 2) &&
1287             (mime_major == 1) && (mime_minor == 0)) {
1288                 procmime_parse_mimepart(mimeinfo,
1289                                         hentry[0].body, hentry[1].body,
1290                                         hentry[2].body, hentry[3].body, 
1291                                         hentry[4].body, 
1292                                         mimeinfo->data.filename, content_start,
1293                                         mimeinfo->length - (content_start - mimeinfo->offset));
1294         } else {
1295                 MimeInfo *subinfo;
1296
1297                 subinfo = procmime_mimeinfo_new();
1298                 subinfo->content = MIMECONTENT_FILE;
1299                 subinfo->encoding_type = ENC_UNKNOWN;
1300                 subinfo->type = MIMETYPE_TEXT;
1301                 subinfo->subtype = g_strdup("plain");
1302                 subinfo->data.filename = g_strdup(mimeinfo->data.filename);
1303                 subinfo->offset = content_start;
1304                 subinfo->length = mimeinfo->length - (content_start - mimeinfo->offset);
1305
1306                 g_node_append(mimeinfo->node, subinfo->node);
1307         }
1308         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1309                 g_free(hentry[i].body);
1310                 hentry[i].body = NULL;
1311         }
1312 }
1313
1314 void procmime_parse_multipart(MimeInfo *mimeinfo)
1315 {
1316         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1317                                 {"Content-Transfer-Encoding:",
1318                                                    NULL, FALSE},
1319                                 {"Content-Description:",
1320                                                    NULL, TRUE},
1321                                 {"Content-ID:",
1322                                                    NULL, TRUE},
1323                                 {"Content-Disposition:",
1324                                                    NULL, TRUE},
1325                                 {NULL,             NULL, FALSE}};
1326         gchar *p, *tmp;
1327         gchar *boundary;
1328         gint boundary_len = 0, lastoffset = -1, i;
1329         gchar buf[BUFFSIZE];
1330         FILE *fp;
1331         int result = 0;
1332
1333         boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
1334         if (!boundary)
1335                 return;
1336         boundary_len = strlen(boundary);
1337
1338         procmime_decode_content(mimeinfo);
1339
1340         fp = fopen(mimeinfo->data.filename, "rb");
1341         if (fp == NULL) {
1342                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1343                 return;
1344         }
1345         fseek(fp, mimeinfo->offset, SEEK_SET);
1346         while ((p = fgets(buf, sizeof(buf), fp)) != NULL && result == 0) {
1347                 if (ftell(fp) > (mimeinfo->offset + mimeinfo->length))
1348                         break;
1349
1350                 if (IS_BOUNDARY(buf, boundary, boundary_len)) {
1351                         if (lastoffset != -1) {
1352                                 result = procmime_parse_mimepart(mimeinfo,
1353                                                         hentry[0].body, hentry[1].body,
1354                                                         hentry[2].body, hentry[3].body, 
1355                                                         hentry[4].body, 
1356                                                         mimeinfo->data.filename, lastoffset,
1357                                                         (ftell(fp) - strlen(buf)) - lastoffset - 1);
1358                         }
1359                         
1360                         if (buf[2 + boundary_len]     == '-' &&
1361                             buf[2 + boundary_len + 1] == '-')
1362                                 break;
1363
1364                         for (i = 0; i < (sizeof hentry / sizeof hentry[0]) ; i++) {
1365                                 g_free(hentry[i].body);
1366                                 hentry[i].body = NULL;
1367                         }
1368                         procheader_get_header_fields(fp, hentry);
1369                         if (hentry[0].body != NULL) {
1370                                 tmp = conv_unmime_header(hentry[0].body, NULL);
1371                                 g_free(hentry[0].body);
1372                                 hentry[0].body = tmp;
1373                         }                
1374                         if (hentry[2].body != NULL) {
1375                                 tmp = conv_unmime_header(hentry[2].body, NULL);
1376                                 g_free(hentry[2].body);
1377                                 hentry[2].body = tmp;
1378                         }                
1379                         if (hentry[4].body != NULL) {
1380                                 tmp = conv_unmime_header(hentry[4].body, NULL);
1381                                 g_free(hentry[4].body);
1382                                 hentry[4].body = tmp;
1383                         }                
1384                         lastoffset = ftell(fp);
1385                 }
1386         }
1387         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1388                 g_free(hentry[i].body);
1389                 hentry[i].body = NULL;
1390         }
1391         fclose(fp);
1392 }
1393
1394 static void parse_parameters(const gchar *parameters, GHashTable *table)
1395 {
1396         gchar *params, *param, *next;
1397         GSList *convlist = NULL, *concatlist = NULL, *cur;
1398
1399         params = g_strdup(parameters);
1400         param = params;
1401         next = params;
1402         for (; next != NULL; param = next) {
1403                 gchar *attribute, *value, *tmp;
1404                 gint len;
1405                 gboolean convert = FALSE;
1406
1407                 next = strchr_with_skip_quote(param, '"', ';');
1408                 if (next != NULL) {
1409                         next[0] = '\0';
1410                         next++;
1411                 }
1412
1413                 g_strstrip(param);
1414
1415                 attribute = param;
1416                 value = strchr(attribute, '=');
1417                 if (value == NULL)
1418                         continue;
1419
1420                 value[0] = '\0';
1421                 value++;
1422
1423                 g_strdown(attribute);
1424
1425                 len = strlen(attribute);
1426                 if (attribute[len - 1] == '*') {
1427                         gchar *srcpos, *dstpos, *endpos;
1428
1429                         convert = TRUE;
1430                         attribute[len - 1] = '\0';
1431
1432                         srcpos = value;
1433                         dstpos = value;
1434                         endpos = value + strlen(value);
1435                         while (srcpos < endpos) {
1436                                 if (*srcpos != '%')
1437                                         *dstpos = *srcpos;
1438                                 else {
1439                                         guchar dstvalue;
1440
1441                                         if (!get_hex_value(&dstvalue, srcpos[1], srcpos[2]))
1442                                                 *dstpos = '?';
1443                                         else
1444                                                 *dstpos = dstvalue;
1445                                         srcpos += 2;
1446                                 }
1447                                 srcpos++;
1448                                 dstpos++;
1449                         }
1450                         *dstpos = '\0';
1451                 } else {
1452                         if (value[0] == '"')
1453                                 extract_quote(value, '"');
1454                         else if ((tmp = strchr(value, ' ')) != NULL)
1455                                 *tmp = '\0';
1456                 }
1457
1458                 if (strrchr(attribute, '*') != NULL) {
1459                         gchar *tmpattr;
1460
1461                         tmpattr = g_strdup(attribute);
1462                         tmp = strrchr(tmpattr, '*');
1463                         tmp[0] = '\0';
1464
1465                         if ((tmp[1] == '0') && (tmp[2] == '\0') && 
1466                             (g_slist_find_custom(concatlist, attribute, g_str_equal) == NULL))
1467                                 concatlist = g_slist_prepend(concatlist, g_strdup(tmpattr));
1468
1469                         if (convert && (g_slist_find_custom(convlist, attribute, g_str_equal) == NULL))
1470                                 convlist = g_slist_prepend(convlist, g_strdup(tmpattr));
1471
1472                         g_free(tmpattr);
1473                 } else if (convert) {
1474                         if (g_slist_find_custom(convlist, attribute, g_str_equal) == NULL)
1475                                 convlist = g_slist_prepend(convlist, g_strdup(attribute));
1476                 }
1477
1478                 if (g_hash_table_lookup(table, attribute) == NULL)
1479                         g_hash_table_insert(table, g_strdup(attribute), g_strdup(value));
1480         }
1481
1482         for (cur = concatlist; cur != NULL; cur = g_slist_next(cur)) {
1483                 gchar *attribute, *attrwnum, *partvalue;
1484                 gint n = 0;
1485                 GString *value;
1486
1487                 attribute = (gchar *) cur->data;
1488                 value = g_string_sized_new(64);
1489
1490                 attrwnum = g_strdup_printf("%s*%d", attribute, n);
1491                 while ((partvalue = g_hash_table_lookup(table, attrwnum)) != NULL) {
1492                         g_string_append(value, partvalue);
1493
1494                         g_free(attrwnum);
1495                         n++;
1496                         attrwnum = g_strdup_printf("%s*%d", attribute, n);
1497                 }
1498                 g_free(attrwnum);
1499
1500                 g_hash_table_insert(table, g_strdup(attribute), g_strdup(value->str));
1501                 g_string_free(value, TRUE);
1502         }
1503         slist_free_strings(concatlist);
1504         g_slist_free(concatlist);
1505
1506         for (cur = convlist; cur != NULL; cur = g_slist_next(cur)) {
1507                 gchar *attribute, *key, *value;
1508                 gchar *charset, *lang, *oldvalue, *newvalue;
1509
1510                 attribute = (gchar *) cur->data;
1511                 if (!g_hash_table_lookup_extended(table, attribute, (gpointer *) &key, (gpointer *) &value))
1512                         continue;
1513
1514                 charset = value;
1515                 lang = strchr(charset, '\'');
1516                 if (lang == NULL)
1517                         continue;
1518                 lang[0] = '\0';
1519                 lang++;
1520                 oldvalue = strchr(lang, '\'');
1521                 if (oldvalue == NULL)
1522                         continue;
1523                 oldvalue[0] = '\0';
1524                 oldvalue++;
1525
1526                 newvalue = conv_codeset_strdup(oldvalue, charset, CS_UTF_8);
1527
1528                 g_hash_table_remove(table, attribute);
1529                 g_free(key);
1530                 g_free(value);
1531
1532                 g_hash_table_insert(table, g_strdup(attribute), newvalue);
1533         }
1534         slist_free_strings(convlist);
1535         g_slist_free(convlist);
1536
1537         g_free(params);
1538 }       
1539
1540 static void procmime_parse_content_type(const gchar *content_type, MimeInfo *mimeinfo)
1541 {
1542         g_return_if_fail(content_type != NULL);
1543         g_return_if_fail(mimeinfo != NULL);
1544
1545         /* RFC 2045, page 13 says that the mime subtype is MANDATORY;
1546          * if it's not available we use the default Content-Type */
1547         if ((content_type[0] == '\0') || (strchr(content_type, '/') == NULL)) {
1548                 mimeinfo->type = MIMETYPE_TEXT;
1549                 mimeinfo->subtype = g_strdup("plain");
1550                 if (g_hash_table_lookup(mimeinfo->typeparameters,
1551                                        "charset") == NULL)
1552                         g_hash_table_insert(mimeinfo->typeparameters,
1553                                             g_strdup("charset"),
1554                                             g_strdup("us-ascii"));
1555         } else {
1556                 gchar *type, *subtype, *params;
1557
1558                 type = g_strdup(content_type);
1559                 subtype = strchr(type, '/') + 1;
1560                 *(subtype - 1) = '\0';
1561                 if ((params = strchr(subtype, ';')) != NULL) {
1562                         params[0] = '\0';
1563                         params++;
1564                 }
1565
1566                 mimeinfo->type = procmime_get_media_type(type);
1567                 mimeinfo->subtype = g_strdup(subtype);
1568
1569                 /* Get mimeinfo->typeparameters */
1570                 if (params != NULL)
1571                         parse_parameters(params, mimeinfo->typeparameters);
1572
1573                 g_free(type);
1574         }
1575 }
1576
1577 static void procmime_parse_content_disposition(const gchar *content_disposition, MimeInfo *mimeinfo)
1578 {
1579         gchar *tmp, *params;
1580
1581         g_return_if_fail(content_disposition != NULL);
1582         g_return_if_fail(mimeinfo != NULL);
1583
1584         tmp = g_strdup(content_disposition);
1585         if ((params = strchr(tmp, ';')) != NULL) {
1586                 params[0] = '\0';
1587                 params++;
1588         }       
1589         g_strstrip(tmp);
1590
1591         if (!g_ascii_strcasecmp(tmp, "inline")) 
1592                 mimeinfo->disposition = DISPOSITIONTYPE_INLINE;
1593         else if (!g_ascii_strcasecmp(tmp, "attachment"))
1594                 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1595         else
1596                 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1597         
1598         if (params != NULL)
1599                 parse_parameters(params, mimeinfo->dispositionparameters);
1600
1601         g_free(tmp);
1602 }
1603
1604
1605 static void procmime_parse_content_encoding(const gchar *content_encoding, MimeInfo *mimeinfo)
1606 {
1607         struct EncodingTable *enc_table;
1608         
1609         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1610                 if (g_ascii_strcasecmp(enc_table->str, content_encoding) == 0) {
1611                         mimeinfo->encoding_type = enc_table->enc_type;
1612                         return;
1613                 }
1614         }
1615         mimeinfo->encoding_type = ENC_UNKNOWN;
1616         return;
1617 }
1618
1619 int procmime_parse_mimepart(MimeInfo *parent,
1620                              gchar *content_type,
1621                              gchar *content_encoding,
1622                              gchar *content_description,
1623                              gchar *content_id,
1624                              gchar *content_disposition,
1625                              const gchar *filename,
1626                              guint offset,
1627                              guint length)
1628 {
1629         MimeInfo *mimeinfo;
1630
1631         /* Create MimeInfo */
1632         mimeinfo = procmime_mimeinfo_new();
1633         mimeinfo->content = MIMECONTENT_FILE;
1634         if (parent != NULL) {
1635                 if (g_node_depth(parent->node) > 32) {
1636                         /* 32 is an arbitrary value
1637                          * this avoids DOSsing ourselves 
1638                          * with enormous messages
1639                          */
1640                         procmime_mimeinfo_free_all(mimeinfo);
1641                         return -1;                      
1642                 }
1643                 g_node_append(parent->node, mimeinfo->node);
1644         }
1645         mimeinfo->data.filename = g_strdup(filename);
1646         mimeinfo->offset = offset;
1647         mimeinfo->length = length;
1648
1649         if (content_type != NULL) {
1650                 procmime_parse_content_type(content_type, mimeinfo);
1651         } else {
1652                 mimeinfo->type = MIMETYPE_TEXT;
1653                 mimeinfo->subtype = g_strdup("plain");
1654                 if (g_hash_table_lookup(mimeinfo->typeparameters,
1655                                        "charset") == NULL)
1656                         g_hash_table_insert(mimeinfo->typeparameters, g_strdup("charset"), g_strdup("us-ascii"));
1657         }
1658
1659         if (content_encoding != NULL) {
1660                 procmime_parse_content_encoding(content_encoding, mimeinfo);
1661         } else {
1662                 mimeinfo->encoding_type = ENC_UNKNOWN;
1663         }
1664
1665         if (content_description != NULL)
1666                 mimeinfo->description = g_strdup(content_description);
1667         else
1668                 mimeinfo->description = NULL;
1669
1670         if (content_id != NULL)
1671                 mimeinfo->id = g_strdup(content_id);
1672         else
1673                 mimeinfo->id = NULL;
1674
1675         if (content_disposition != NULL) 
1676                 procmime_parse_content_disposition(content_disposition, mimeinfo);
1677         else
1678                 mimeinfo->disposition = DISPOSITIONTYPE_UNKNOWN;
1679
1680         /* Call parser for mime type */
1681         switch (mimeinfo->type) {
1682                 case MIMETYPE_MESSAGE:
1683                         if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
1684                                 procmime_parse_message_rfc822(mimeinfo);
1685                         }
1686                         break;
1687                         
1688                 case MIMETYPE_MULTIPART:
1689                         procmime_parse_multipart(mimeinfo);
1690                         break;
1691                         
1692                 default:
1693                         break;
1694         }
1695
1696         return 0;
1697 }
1698
1699 static gchar *typenames[] = {
1700     "text",
1701     "image",
1702     "audio",
1703     "video",
1704     "application",
1705     "message",
1706     "multipart",
1707     "unknown",
1708 };
1709
1710 static gboolean output_func(GNode *node, gpointer data)
1711 {
1712         guint i, depth;
1713         MimeInfo *mimeinfo = (MimeInfo *) node->data;
1714
1715         depth = g_node_depth(node);
1716         for (i = 0; i < depth; i++)
1717                 printf("    ");
1718         printf("%s/%s (offset:%d length:%d encoding: %d)\n", typenames[mimeinfo->type], mimeinfo->subtype, mimeinfo->offset, mimeinfo->length, mimeinfo->encoding_type);
1719
1720         return FALSE;
1721 }
1722
1723 static void output_mime_structure(MimeInfo *mimeinfo, int indent)
1724 {
1725         g_node_traverse(mimeinfo->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1, output_func, NULL);
1726 }
1727
1728 MimeInfo *procmime_scan_file_with_offset(const gchar *filename, int offset)
1729 {
1730         MimeInfo *mimeinfo;
1731         struct stat buf;
1732
1733         stat(filename, &buf);
1734
1735         mimeinfo = procmime_mimeinfo_new();
1736         mimeinfo->content = MIMECONTENT_FILE;
1737         mimeinfo->encoding_type = ENC_UNKNOWN;
1738         mimeinfo->type = MIMETYPE_MESSAGE;
1739         mimeinfo->subtype = g_strdup("rfc822");
1740         mimeinfo->data.filename = g_strdup(filename);
1741         mimeinfo->offset = offset;
1742         mimeinfo->length = buf.st_size - offset;
1743
1744         procmime_parse_message_rfc822(mimeinfo);
1745         if (debug_get_mode())
1746                 output_mime_structure(mimeinfo, 0);
1747
1748         return mimeinfo;
1749 }
1750
1751 MimeInfo *procmime_scan_file(const gchar *filename)
1752 {
1753         MimeInfo *mimeinfo;
1754
1755         g_return_val_if_fail(filename != NULL, NULL);
1756
1757         mimeinfo = procmime_scan_file_with_offset(filename, 0);
1758
1759         return mimeinfo;
1760 }
1761
1762 MimeInfo *procmime_scan_queue_file(const gchar *filename)
1763 {
1764         FILE *fp;
1765         MimeInfo *mimeinfo;
1766         gchar buf[BUFFSIZE];
1767         gint offset = 0;
1768
1769         g_return_val_if_fail(filename != NULL, NULL);
1770
1771         /* Open file */
1772         if ((fp = fopen(filename, "rb")) == NULL)
1773                 return NULL;
1774         /* Skip queue header */
1775         while (fgets(buf, sizeof(buf), fp) != NULL)
1776                 if (buf[0] == '\r' || buf[0] == '\n') break;
1777         offset = ftell(fp);
1778         fclose(fp);
1779
1780         mimeinfo = procmime_scan_file_with_offset(filename, offset);
1781
1782         return mimeinfo;
1783 }
1784
1785 typedef enum {
1786     ENC_AS_TOKEN,
1787     ENC_AS_QUOTED_STRING,
1788     ENC_AS_EXTENDED,
1789 } EncodeAs;
1790
1791 typedef struct _ParametersData {
1792         FILE *fp;
1793         guint len;
1794 } ParametersData;
1795
1796 static void write_parameters(gpointer key, gpointer value, gpointer user_data)
1797 {
1798         gchar *param = key;
1799         gchar *val = value, *valpos;
1800         ParametersData *pdata = (ParametersData *)user_data;
1801         GString *buf = g_string_new("");
1802
1803         EncodeAs encas = ENC_AS_TOKEN;
1804
1805         for (valpos = val; *valpos != 0; valpos++) {
1806                 if (!IS_ASCII(*valpos)) {
1807                         encas = ENC_AS_EXTENDED;
1808                         break;
1809                 }
1810             
1811                 /* CTLs */
1812                 if (((*valpos >= 0) && (*valpos < 037)) || (*valpos == 0177)) {
1813                         encas = ENC_AS_QUOTED_STRING;
1814                         continue;
1815                 }
1816
1817                 /* tspecials + SPACE */
1818                 switch (*valpos) {
1819                 case ' ':
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                         encas = ENC_AS_QUOTED_STRING;
1836                         continue;
1837                 }
1838         }
1839
1840         switch (encas) {
1841         case ENC_AS_TOKEN:
1842                 g_string_append_printf(buf, "%s=%s", param, val);
1843                 break;
1844
1845         case ENC_AS_QUOTED_STRING:
1846                 g_string_append_printf(buf, "%s=\"%s\"", param, val);
1847                 break;
1848
1849         case ENC_AS_EXTENDED:
1850                 if (!g_utf8_validate(val, -1, NULL))
1851                         g_string_append_printf(buf, "%s*=%s''", param,
1852                                 conv_get_locale_charset_str());
1853                 else
1854                         g_string_append_printf(buf, "%s*=%s''", param,
1855                                 CS_INTERNAL);
1856                 for (valpos = val; *valpos != '\0'; valpos++) {
1857                         if (IS_ASCII(*valpos) && isalnum(*valpos)) {
1858                                 g_string_append_printf(buf, "%c", *valpos);
1859                         } else {
1860                                 gchar hexstr[3] = "XX";
1861                                 get_hex_str(hexstr, *valpos);
1862                                 g_string_append_printf(buf, "%%%s", hexstr);
1863                         }
1864                 }
1865                 break;
1866         }
1867         
1868         if (buf->str && strlen(buf->str)) {
1869                 if (pdata->len + strlen(buf->str) + 2 > 76) {
1870                         fprintf(pdata->fp, ";\n %s", buf->str);
1871                         pdata->len = strlen(buf->str) + 1;
1872                 } else {
1873                         fprintf(pdata->fp, "; %s", buf->str);
1874                         pdata->len += strlen(buf->str) + 2;
1875                 }
1876         }
1877         g_string_free(buf, TRUE);
1878 }
1879
1880 void procmime_write_mime_header(MimeInfo *mimeinfo, FILE *fp)
1881 {
1882         struct TypeTable *type_table;
1883         ParametersData *pdata = g_new0(ParametersData, 1);
1884         debug_print("procmime_write_mime_header\n");
1885         
1886         pdata->fp = fp;
1887
1888         for (type_table = mime_type_table; type_table->str != NULL; type_table++)
1889                 if (mimeinfo->type == type_table->type) {
1890                         gchar *buf = g_strdup_printf(
1891                                 "Content-Type: %s/%s", type_table->str, mimeinfo->subtype);
1892                         fprintf(fp, "%s", buf);
1893                         pdata->len = strlen(buf);
1894                         g_free(buf);
1895                         break;
1896                 }
1897         g_hash_table_foreach(mimeinfo->typeparameters, write_parameters, pdata);
1898         g_free(pdata);
1899
1900         fprintf(fp, "\n");
1901
1902         if (mimeinfo->encoding_type != ENC_UNKNOWN)
1903                 fprintf(fp, "Content-Transfer-Encoding: %s\n", procmime_get_encoding_str(mimeinfo->encoding_type));
1904
1905         if (mimeinfo->description != NULL)
1906                 fprintf(fp, "Content-Description: %s\n", mimeinfo->description);
1907
1908         if (mimeinfo->id != NULL)
1909                 fprintf(fp, "Content-ID: %s\n", mimeinfo->id);
1910
1911         if (mimeinfo->disposition != DISPOSITIONTYPE_UNKNOWN) {
1912                 ParametersData *pdata = g_new0(ParametersData, 1);
1913                 gchar *buf = NULL;
1914                 if (mimeinfo->disposition == DISPOSITIONTYPE_INLINE)
1915                         buf = g_strdup("Content-Disposition: inline");
1916                 else if (mimeinfo->disposition == DISPOSITIONTYPE_ATTACHMENT)
1917                         buf = g_strdup("Content-Disposition: attachment");
1918                 else
1919                         buf = g_strdup("Content-Disposition: unknown");
1920
1921                 fprintf(fp, "%s", buf);
1922                 pdata->len = strlen(buf);
1923                 g_free(buf);
1924
1925                 pdata->fp = fp;
1926                 g_hash_table_foreach(mimeinfo->dispositionparameters, write_parameters, pdata);
1927                 g_free(pdata);
1928                 fprintf(fp, "\n");
1929         }
1930
1931         fprintf(fp, "\n");
1932 }
1933
1934 gint procmime_write_message_rfc822(MimeInfo *mimeinfo, FILE *fp)
1935 {
1936         FILE *infp;
1937         GNode *childnode;
1938         MimeInfo *child;
1939         gchar buf[BUFFSIZE];
1940         gboolean skip = FALSE;;
1941
1942         debug_print("procmime_write_message_rfc822\n");
1943
1944         /* write header */
1945         switch (mimeinfo->content) {
1946         case MIMECONTENT_FILE:
1947                 if ((infp = fopen(mimeinfo->data.filename, "rb")) == NULL) {
1948                         FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1949                         return -1;
1950                 }
1951                 fseek(infp, mimeinfo->offset, SEEK_SET);
1952                 while (fgets(buf, sizeof(buf), infp) == buf) {
1953                         if (buf[0] == '\n' && buf[1] == '\0')
1954                                 break;
1955                         if (skip && (buf[0] == ' ' || buf[0] == '\t'))
1956                                 continue;
1957                         if (g_ascii_strncasecmp(buf, "Mime-Version:", 13) == 0 ||
1958                             g_ascii_strncasecmp(buf, "Content-Type:", 13) == 0 ||
1959                             g_ascii_strncasecmp(buf, "Content-Transfer-Encoding:", 26) == 0 ||
1960                             g_ascii_strncasecmp(buf, "Content-Description:", 20) == 0 ||
1961                             g_ascii_strncasecmp(buf, "Content-ID:", 11) == 0 ||
1962                             g_ascii_strncasecmp(buf, "Content-Disposition:", 20) == 0) {
1963                                 skip = TRUE;
1964                                 continue;
1965                         }
1966                         fwrite(buf, sizeof(gchar), strlen(buf), fp);
1967                         skip = FALSE;
1968                 }
1969                 fclose(infp);
1970                 break;
1971
1972         case MIMECONTENT_MEM:
1973                 fwrite(mimeinfo->data.mem, strlen(mimeinfo->data.mem), sizeof(gchar), fp);
1974                 break;
1975
1976         default:
1977                 break;
1978         }
1979
1980         childnode = mimeinfo->node->children;
1981         if (childnode == NULL)
1982                 return -1;
1983
1984         child = (MimeInfo *) childnode->data;
1985         fprintf(fp, "Mime-Version: 1.0\n");
1986         procmime_write_mime_header(child, fp);
1987         return procmime_write_mimeinfo(child, fp);
1988 }
1989
1990 gint procmime_write_multipart(MimeInfo *mimeinfo, FILE *fp)
1991 {
1992         FILE *infp;
1993         GNode *childnode;
1994         gchar *boundary, *str, *str2;
1995         gchar buf[BUFFSIZE];
1996         gboolean firstboundary;
1997
1998         debug_print("procmime_write_multipart\n");
1999
2000         boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
2001
2002         switch (mimeinfo->content) {
2003         case MIMECONTENT_FILE:
2004                 if ((infp = fopen(mimeinfo->data.filename, "rb")) == NULL) {
2005                         FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2006                         return -1;
2007                 }
2008                 fseek(infp, mimeinfo->offset, SEEK_SET);
2009                 while (fgets(buf, sizeof(buf), infp) == buf) {
2010                         if (IS_BOUNDARY(buf, boundary, strlen(boundary)))
2011                                 break;
2012                         fwrite(buf, sizeof(gchar), strlen(buf), fp);
2013                 }
2014                 fclose(infp);
2015                 break;
2016
2017         case MIMECONTENT_MEM:
2018                 str = g_strdup(mimeinfo->data.mem);
2019                 if (((str2 = strstr(str, boundary)) != NULL) && ((str2 - str) >= 2) &&
2020                     (*(str2 - 1) == '-') && (*(str2 - 2) == '-'))
2021                         *(str2 - 2) = '\0';
2022                 fwrite(str, strlen(str), sizeof(gchar), fp);
2023                 g_free(str);
2024                 break;
2025
2026         default:
2027                 break;
2028         }
2029
2030         childnode = mimeinfo->node->children;
2031         firstboundary = TRUE;
2032         while (childnode != NULL) {
2033                 MimeInfo *child = childnode->data;
2034
2035                 if (firstboundary)
2036                         firstboundary = FALSE;
2037                 else
2038                         fprintf(fp, "\n");
2039                 fprintf(fp, "--%s\n", boundary);
2040
2041                 procmime_write_mime_header(child, fp);
2042                 if (procmime_write_mimeinfo(child, fp) < 0)
2043                         return -1;
2044
2045                 childnode = g_node_next_sibling(childnode);
2046         }       
2047         fprintf(fp, "\n--%s--\n", boundary);
2048
2049         return 0;
2050 }
2051
2052 gint procmime_write_mimeinfo(MimeInfo *mimeinfo, FILE *fp)
2053 {
2054         FILE *infp;
2055
2056         debug_print("procmime_write_mimeinfo\n");
2057
2058         if (G_NODE_IS_LEAF(mimeinfo->node)) {
2059                 switch (mimeinfo->content) {
2060                 case MIMECONTENT_FILE:
2061                         if ((infp = fopen(mimeinfo->data.filename, "rb")) == NULL) {
2062                                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2063                                 return -1;
2064                         }
2065                         copy_file_part_to_fp(infp, mimeinfo->offset, mimeinfo->length, fp);
2066                         fclose(infp);
2067                         return 0;
2068
2069                 case MIMECONTENT_MEM:
2070                         fwrite(mimeinfo->data.mem, strlen(mimeinfo->data.mem), sizeof(gchar), fp);
2071                         return 0;
2072
2073                 default:
2074                         return 0;
2075                 }
2076         } else {
2077                 /* Call writer for mime type */
2078                 switch (mimeinfo->type) {
2079                 case MIMETYPE_MESSAGE:
2080                         if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0)
2081                                 return procmime_write_message_rfc822(mimeinfo, fp);
2082                         break;
2083                         
2084                 case MIMETYPE_MULTIPART:
2085                         return procmime_write_multipart(mimeinfo, fp);
2086                         
2087                 default:
2088                         break;
2089                 }
2090
2091                 return -1;
2092         }
2093
2094         return 0;
2095 }
2096
2097 gchar *procmime_get_part_file_name(MimeInfo *mimeinfo)
2098 {
2099         gchar *base;
2100
2101         if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
2102                 base = g_strdup("mimetmp.html");
2103         else {
2104                 const gchar *basetmp;
2105                 gchar *basename;
2106
2107                 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
2108                 if (basetmp == NULL)
2109                         basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
2110                 if (basetmp == NULL)
2111                         basetmp = "mimetmp";
2112                 basename = g_path_get_basename(basetmp);
2113                 if (*basename == '\0') {
2114                         g_free(basename);
2115                         basename = g_strdup("mimetmp");
2116                 }
2117                 base = conv_filename_from_utf8(basename);
2118                 g_free(basename);
2119                 subst_for_shellsafe_filename(base);
2120         }
2121         
2122         return base;
2123 }
2124