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