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