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