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