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