2005-02-14 [colin] 1.0.1cvs6.1
[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, strlen("From "))) {
482                                 gchar *tmpbuf = outbuf;
483                                 
484                                 tmpbuf += strlen("From ");
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                 base = g_path_get_basename(basetmp);
894                 if (*base == '\0') base = g_strdup("mimetmp");
895                 subst_for_shellsafe_filename(base);
896         }
897
898         filename = g_strconcat(get_mime_tmp_dir(), G_DIR_SEPARATOR_S,
899                                f_prefix, base, NULL);
900
901         g_free(base);
902         return filename;
903 }
904
905 static GList *mime_type_list = NULL;
906
907 gchar *procmime_get_mime_type(const gchar *filename)
908 {
909         static GHashTable *mime_type_table = NULL;
910         MimeType *mime_type;
911         const gchar *p;
912         gchar *ext;
913         gchar *base;
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         base = g_path_get_basename(filename);
921         p = strrchr(base, '.');
922         g_free(base);
923         if (!p) return NULL;
924
925         Xstrdup_a(ext, p + 1, return NULL);
926         g_strdown(ext);
927         mime_type = g_hash_table_lookup(mime_type_table, ext);
928         if (mime_type) {
929                 gchar *str;
930
931                 str = g_strconcat(mime_type->type, "/", mime_type->sub_type,
932                                   NULL);
933                 return str;
934         }
935
936         return NULL;
937 }
938
939 static guint procmime_str_hash(gconstpointer gptr)
940 {
941         guint hash_result = 0;
942         const char *str;
943
944         for (str = gptr; str && *str; str++) {
945                 if (isupper(*str)) hash_result += (*str + ' ');
946                 else hash_result += *str;
947         }
948
949         return hash_result;
950 }
951
952 static gint procmime_str_equal(gconstpointer gptr1, gconstpointer gptr2)
953 {
954         const char *str1 = gptr1;
955         const char *str2 = gptr2;
956
957         return !g_utf8_collate(str1, str2);
958 }
959
960 static GHashTable *procmime_get_mime_type_table(void)
961 {
962         GHashTable *table = NULL;
963         GList *cur;
964         MimeType *mime_type;
965         gchar **exts;
966
967         if (!mime_type_list) {
968                 mime_type_list = procmime_get_mime_type_list();
969                 if (!mime_type_list) return NULL;
970         }
971
972         table = g_hash_table_new(procmime_str_hash, procmime_str_equal);
973
974         for (cur = mime_type_list; cur != NULL; cur = cur->next) {
975                 gint i;
976                 gchar *key;
977
978                 mime_type = (MimeType *)cur->data;
979
980                 if (!mime_type->extension) continue;
981
982                 exts = g_strsplit(mime_type->extension, " ", 16);
983                 for (i = 0; exts[i] != NULL; i++) {
984                         /* make the key case insensitive */
985                         g_strdown(exts[i]);
986                         /* use previously dup'd key on overwriting */
987                         if (g_hash_table_lookup(table, exts[i]))
988                                 key = exts[i];
989                         else
990                                 key = g_strdup(exts[i]);
991                         g_hash_table_insert(table, key, mime_type);
992                 }
993                 g_strfreev(exts);
994         }
995
996         return table;
997 }
998
999 GList *procmime_get_mime_type_list(void)
1000 {
1001         GList *list = NULL;
1002         FILE *fp;
1003         gchar buf[BUFFSIZE];
1004         guchar *p;
1005         gchar *delim;
1006         MimeType *mime_type;
1007
1008         if (mime_type_list) 
1009                 return mime_type_list;
1010
1011         if ((fp = fopen("/etc/mime.types", "rb")) == NULL) {
1012                 if ((fp = fopen(SYSCONFDIR "/mime.types", "rb")) == NULL) {
1013                         FILE_OP_ERROR(SYSCONFDIR "/mime.types", "fopen");
1014                         return NULL;
1015                 }
1016         }
1017
1018         while (fgets(buf, sizeof(buf), fp) != NULL) {
1019                 p = strchr(buf, '#');
1020                 if (p) *p = '\0';
1021                 g_strstrip(buf);
1022
1023                 p = buf;
1024                 while (*p && !isspace(*p)) p++;
1025                 if (*p) {
1026                         *p = '\0';
1027                         p++;
1028                 }
1029                 delim = strchr(buf, '/');
1030                 if (delim == NULL) continue;
1031                 *delim = '\0';
1032
1033                 mime_type = g_new(MimeType, 1);
1034                 mime_type->type = g_strdup(buf);
1035                 mime_type->sub_type = g_strdup(delim + 1);
1036
1037                 while (*p && isspace(*p)) p++;
1038                 if (*p)
1039                         mime_type->extension = g_strdup(p);
1040                 else
1041                         mime_type->extension = NULL;
1042
1043                 list = g_list_append(list, mime_type);
1044         }
1045
1046         fclose(fp);
1047
1048         if (!list)
1049                 g_warning("Can't read mime.types\n");
1050
1051         return list;
1052 }
1053
1054 EncodingType procmime_get_encoding_for_charset(const gchar *charset)
1055 {
1056         if (!charset)
1057                 return ENC_8BIT;
1058         else if (!g_ascii_strncasecmp(charset, "ISO-2022-", 9) ||
1059                  !g_ascii_strcasecmp(charset, "US-ASCII"))
1060                 return ENC_7BIT;
1061         else if (!g_ascii_strcasecmp(charset, "ISO-8859-5") ||
1062                  !g_ascii_strncasecmp(charset, "KOI8-", 5) ||
1063                  !g_ascii_strcasecmp(charset, "Windows-1251"))
1064                 return ENC_8BIT;
1065         else if (!g_ascii_strncasecmp(charset, "ISO-8859-", 9))
1066                 return ENC_QUOTED_PRINTABLE;
1067         else
1068                 return ENC_8BIT;
1069 }
1070
1071 EncodingType procmime_get_encoding_for_text_file(const gchar *file)
1072 {
1073         FILE *fp;
1074         guchar buf[BUFFSIZE];
1075         size_t len;
1076         size_t octet_chars = 0;
1077         size_t total_len = 0;
1078         gfloat octet_percentage;
1079
1080         if ((fp = fopen(file, "rb")) == NULL) {
1081                 FILE_OP_ERROR(file, "fopen");
1082                 return ENC_UNKNOWN;
1083         }
1084
1085         while ((len = fread(buf, sizeof(guchar), sizeof(buf), fp)) > 0) {
1086                 guchar *p;
1087                 gint i;
1088
1089                 for (p = buf, i = 0; i < len; ++p, ++i) {
1090                         if (*p & 0x80)
1091                                 ++octet_chars;
1092                 }
1093                 total_len += len;
1094         }
1095
1096         fclose(fp);
1097         
1098         if (total_len > 0)
1099                 octet_percentage = (gfloat)octet_chars / (gfloat)total_len;
1100         else
1101                 octet_percentage = 0.0;
1102
1103         debug_print("procmime_get_encoding_for_text_file(): "
1104                     "8bit chars: %d / %d (%f%%)\n", octet_chars, total_len,
1105                     100.0 * octet_percentage);
1106
1107         if (octet_percentage > 0.20) {
1108                 debug_print("using BASE64\n");
1109                 return ENC_BASE64;
1110         } else if (octet_chars > 0) {
1111                 debug_print("using quoted-printable\n");
1112                 return ENC_QUOTED_PRINTABLE;
1113         } else {
1114                 debug_print("using 7bit\n");
1115                 return ENC_7BIT;
1116         }
1117 }
1118
1119 struct EncodingTable 
1120 {
1121         gchar *str;
1122         EncodingType enc_type;
1123 };
1124
1125 struct EncodingTable encoding_table[] = {
1126         {"7bit", ENC_7BIT},
1127         {"8bit", ENC_8BIT},
1128         {"binary", ENC_BINARY},
1129         {"quoted-printable", ENC_QUOTED_PRINTABLE},
1130         {"base64", ENC_BASE64},
1131         {"x-uuencode", ENC_UNKNOWN},
1132         {NULL, ENC_UNKNOWN},
1133 };
1134
1135 const gchar *procmime_get_encoding_str(EncodingType encoding)
1136 {
1137         struct EncodingTable *enc_table;
1138         
1139         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1140                 if (enc_table->enc_type == encoding)
1141                         return enc_table->str;
1142         }
1143         return NULL;
1144 }
1145
1146 /* --- NEW MIME STUFF --- */
1147 struct TypeTable
1148 {
1149         gchar *str;
1150         MimeMediaType type;
1151 };
1152
1153 static struct TypeTable mime_type_table[] = {
1154         {"text", MIMETYPE_TEXT},
1155         {"image", MIMETYPE_IMAGE},
1156         {"audio", MIMETYPE_AUDIO},
1157         {"video", MIMETYPE_VIDEO},
1158         {"application", MIMETYPE_APPLICATION},
1159         {"message", MIMETYPE_MESSAGE},
1160         {"multipart", MIMETYPE_MULTIPART},
1161         {NULL, 0},
1162 };
1163
1164 const gchar *procmime_get_media_type_str(MimeMediaType type)
1165 {
1166         struct TypeTable *type_table;
1167         
1168         for (type_table = mime_type_table; type_table->str != NULL; type_table++) {
1169                 if (type_table->type == type)
1170                         return type_table->str;
1171         }
1172         return NULL;
1173 }
1174
1175 MimeMediaType procmime_get_media_type(const gchar *str)
1176 {
1177         struct TypeTable *typetablearray;
1178
1179         for (typetablearray = mime_type_table; typetablearray->str != NULL; typetablearray++)
1180                 if (g_ascii_strncasecmp(str, typetablearray->str, strlen(typetablearray->str)) == 0)
1181                         return typetablearray->type;
1182
1183         return MIMETYPE_UNKNOWN;
1184 }
1185
1186 /*!
1187  *\brief        Safe wrapper for content type string.
1188  *
1189  *\return       const gchar * Pointer to content type string. 
1190  */
1191 gchar *procmime_get_content_type_str(MimeMediaType type,
1192                                            const char *subtype)
1193 {
1194         const gchar *type_str = NULL;
1195
1196         if (subtype == NULL || !(type_str = procmime_get_media_type_str(type)))
1197                 return g_strdup("unknown");
1198         return g_strdup_printf("%s/%s", type_str, subtype);
1199 }
1200
1201 void procmime_parse_mimepart(MimeInfo *parent,
1202                              gchar *content_type,
1203                              gchar *content_encoding,
1204                              gchar *content_description,
1205                              gchar *content_id,
1206                              gchar *content_disposition,
1207                              const gchar *filename,
1208                              guint offset,
1209                              guint length);
1210
1211 void procmime_parse_message_rfc822(MimeInfo *mimeinfo)
1212 {
1213         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1214                                 {"Content-Transfer-Encoding:",
1215                                                    NULL, FALSE},
1216                                 {"Content-Description:",
1217                                                    NULL, TRUE},
1218                                 {"Content-ID:",
1219                                                    NULL, TRUE},
1220                                 {"Content-Disposition:",
1221                                                    NULL, TRUE},
1222                                 {"MIME-Version:",
1223                                                    NULL, TRUE},
1224                                 {NULL,             NULL, FALSE}};
1225         guint content_start, i;
1226         FILE *fp;
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_overwrite(hentry[0].body);
1240         if (hentry[2].body != NULL)
1241                 conv_unmime_header_overwrite(hentry[2].body);
1242         if (hentry[4].body != NULL)
1243                 conv_unmime_header_overwrite(hentry[4].body);
1244         content_start = ftell(fp);
1245         fclose(fp);
1246
1247         if ((hentry[5].body != NULL) &&
1248             (sscanf(hentry[5].body, "%d.%d", &mime_major, &mime_minor) == 2) &&
1249             (mime_major == 1) && (mime_minor == 0)) {
1250                 procmime_parse_mimepart(mimeinfo,
1251                                         hentry[0].body, hentry[1].body,
1252                                         hentry[2].body, hentry[3].body, 
1253                                         hentry[4].body, 
1254                                         mimeinfo->data.filename, content_start,
1255                                         mimeinfo->length - (content_start - mimeinfo->offset));
1256         } else {
1257                 MimeInfo *subinfo;
1258
1259                 subinfo = procmime_mimeinfo_new();
1260                 subinfo->content = MIMECONTENT_FILE;
1261                 subinfo->encoding_type = ENC_UNKNOWN;
1262                 subinfo->type = MIMETYPE_TEXT;
1263                 subinfo->subtype = g_strdup("plain");
1264                 subinfo->data.filename = g_strdup(mimeinfo->data.filename);
1265                 subinfo->offset = content_start;
1266                 subinfo->length = mimeinfo->length - (content_start - mimeinfo->offset);
1267
1268                 g_node_append(mimeinfo->node, subinfo->node);
1269         }
1270         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1271                 g_free(hentry[i].body);
1272                 hentry[i].body = NULL;
1273         }
1274 }
1275
1276 void procmime_parse_multipart(MimeInfo *mimeinfo)
1277 {
1278         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1279                                 {"Content-Transfer-Encoding:",
1280                                                    NULL, FALSE},
1281                                 {"Content-Description:",
1282                                                    NULL, TRUE},
1283                                 {"Content-ID:",
1284                                                    NULL, TRUE},
1285                                 {"Content-Disposition:",
1286                                                    NULL, TRUE},
1287                                 {NULL,             NULL, FALSE}};
1288         gchar *p;
1289         gchar *boundary;
1290         gint boundary_len = 0, lastoffset = -1, i;
1291         gchar buf[BUFFSIZE];
1292         FILE *fp;
1293
1294         boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
1295         if (!boundary)
1296                 return;
1297         boundary_len = strlen(boundary);
1298
1299         procmime_decode_content(mimeinfo);
1300
1301         fp = fopen(mimeinfo->data.filename, "rb");
1302         if (fp == NULL) {
1303                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1304                 return;
1305         }
1306         fseek(fp, mimeinfo->offset, SEEK_SET);
1307         while ((p = fgets(buf, sizeof(buf), fp)) != NULL) {
1308                 if (ftell(fp) > (mimeinfo->offset + mimeinfo->length))
1309                         break;
1310
1311                 if (IS_BOUNDARY(buf, boundary, boundary_len)) {
1312                         if (lastoffset != -1) {
1313                                 procmime_parse_mimepart(mimeinfo,
1314                                                         hentry[0].body, hentry[1].body,
1315                                                         hentry[2].body, hentry[3].body, 
1316                                                         hentry[4].body, 
1317                                                         mimeinfo->data.filename, lastoffset,
1318                                                         (ftell(fp) - strlen(buf)) - lastoffset - 1);
1319                         }
1320                         
1321                         if (buf[2 + boundary_len]     == '-' &&
1322                             buf[2 + boundary_len + 1] == '-')
1323                                 break;
1324
1325                         for (i = 0; i < (sizeof hentry / sizeof hentry[0]) ; i++) {
1326                                 g_free(hentry[i].body);
1327                                 hentry[i].body = NULL;
1328                         }
1329                         procheader_get_header_fields(fp, hentry);
1330                         if (hentry[0].body != NULL)
1331                                 conv_unmime_header_overwrite(hentry[0].body);
1332                         if (hentry[2].body != NULL)
1333                                 conv_unmime_header_overwrite(hentry[2].body);
1334                         if (hentry[4].body != NULL)
1335                                 conv_unmime_header_overwrite(hentry[4].body);
1336                         lastoffset = ftell(fp);
1337                 }
1338         }
1339         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1340                 g_free(hentry[i].body);
1341                 hentry[i].body = NULL;
1342         }
1343         fclose(fp);
1344 }
1345
1346 static void parse_parameters(const gchar *parameters, GHashTable *table)
1347 {
1348         gchar *params, *param, *next;
1349         GSList *convlist = NULL, *concatlist = NULL, *cur;
1350
1351         params = g_strdup(parameters);
1352         param = params;
1353         next = params;
1354         for (; next != NULL; param = next) {
1355                 gchar *attribute, *value, *tmp;
1356                 gint len;
1357                 gboolean convert = FALSE;
1358
1359                 next = strchr_with_skip_quote(param, '"', ';');
1360                 if (next != NULL) {
1361                         next[0] = '\0';
1362                         next++;
1363                 }
1364
1365                 g_strstrip(param);
1366
1367                 attribute = param;
1368                 value = strchr(attribute, '=');
1369                 if (value == NULL)
1370                         continue;
1371
1372                 value[0] = '\0';
1373                 value++;
1374
1375                 g_strdown(attribute);
1376
1377                 len = strlen(attribute);
1378                 if (attribute[len - 1] == '*') {
1379                         gchar *srcpos, *dstpos, *endpos;
1380
1381                         convert = TRUE;
1382                         attribute[len - 1] = '\0';
1383
1384                         srcpos = value;
1385                         dstpos = value;
1386                         endpos = value + strlen(value);
1387                         while (srcpos < endpos) {
1388                                 if (*srcpos != '%')
1389                                         *dstpos = *srcpos;
1390                                 else {
1391                                         guchar dstvalue;
1392
1393                                         if (!get_hex_value(&dstvalue, srcpos[1], srcpos[2]))
1394                                                 *dstpos = '?';
1395                                         else
1396                                                 *dstpos = dstvalue;
1397                                         srcpos += 2;
1398                                 }
1399                                 srcpos++;
1400                                 dstpos++;
1401                         }
1402                         *dstpos = '\0';
1403                 } else {
1404                         if (value[0] == '"')
1405                                 extract_quote(value, '"');
1406                         else if ((tmp = strchr(value, ' ')) != NULL)
1407                                 *tmp = '\0';
1408                 }
1409
1410                 if (strrchr(attribute, '*') != NULL) {
1411                         gchar *tmpattr;
1412
1413                         tmpattr = g_strdup(attribute);
1414                         tmp = strrchr(tmpattr, '*');
1415                         tmp[0] = '\0';
1416
1417                         if ((tmp[1] == '0') && (tmp[2] == '\0') && 
1418                             (g_slist_find_custom(concatlist, attribute, g_str_equal) == NULL))
1419                                 concatlist = g_slist_prepend(concatlist, g_strdup(tmpattr));
1420
1421                         if (convert && (g_slist_find_custom(convlist, attribute, g_str_equal) == NULL))
1422                                 convlist = g_slist_prepend(convlist, g_strdup(tmpattr));
1423
1424                         g_free(tmpattr);
1425                 } else if (convert) {
1426                         if (g_slist_find_custom(convlist, attribute, g_str_equal) == NULL)
1427                                 convlist = g_slist_prepend(convlist, g_strdup(attribute));
1428                 }
1429
1430                 if (g_hash_table_lookup(table, attribute) == NULL)
1431                         g_hash_table_insert(table, g_strdup(attribute), g_strdup(value));
1432         }
1433
1434         for (cur = concatlist; cur != NULL; cur = g_slist_next(cur)) {
1435                 gchar *attribute, *attrwnum, *partvalue;
1436                 gint n = 0;
1437                 GString *value;
1438
1439                 attribute = (gchar *) cur->data;
1440                 value = g_string_sized_new(64);
1441
1442                 attrwnum = g_strdup_printf("%s*%d", attribute, n);
1443                 while ((partvalue = g_hash_table_lookup(table, attrwnum)) != NULL) {
1444                         g_string_append(value, partvalue);
1445
1446                         g_free(attrwnum);
1447                         n++;
1448                         attrwnum = g_strdup_printf("%s*%d", attribute, n);
1449                 }
1450                 g_free(attrwnum);
1451
1452                 g_hash_table_insert(table, g_strdup(attribute), g_strdup(value->str));
1453                 g_string_free(value, TRUE);
1454         }
1455         slist_free_strings(concatlist);
1456         g_slist_free(concatlist);
1457
1458         for (cur = convlist; cur != NULL; cur = g_slist_next(cur)) {
1459                 gchar *attribute, *key, *value;
1460                 gchar *charset, *lang, *oldvalue, *newvalue;
1461
1462                 attribute = (gchar *) cur->data;
1463                 if (!g_hash_table_lookup_extended(table, attribute, (gpointer *) &key, (gpointer *) &value))
1464                         continue;
1465
1466                 charset = value;
1467                 lang = strchr(charset, '\'');
1468                 if (lang == NULL)
1469                         continue;
1470                 lang[0] = '\0';
1471                 lang++;
1472                 oldvalue = strchr(lang, '\'');
1473                 if (oldvalue == NULL)
1474                         continue;
1475                 oldvalue[0] = '\0';
1476                 oldvalue++;
1477
1478                 newvalue = conv_codeset_strdup(oldvalue, charset, CS_UTF_8);
1479
1480                 g_hash_table_remove(table, attribute);
1481                 g_free(key);
1482                 g_free(value);
1483
1484                 g_hash_table_insert(table, g_strdup(attribute), newvalue);
1485         }
1486         slist_free_strings(convlist);
1487         g_slist_free(convlist);
1488
1489         g_free(params);
1490 }       
1491
1492 static void procmime_parse_content_type(const gchar *content_type, MimeInfo *mimeinfo)
1493 {
1494         g_return_if_fail(content_type != NULL);
1495         g_return_if_fail(mimeinfo != NULL);
1496
1497         /* RFC 2045, page 13 says that the mime subtype is MANDATORY;
1498          * if it's not available we use the default Content-Type */
1499         if ((content_type[0] == '\0') || (strchr(content_type, '/') == NULL)) {
1500                 mimeinfo->type = MIMETYPE_TEXT;
1501                 mimeinfo->subtype = g_strdup("plain");
1502                 if (g_hash_table_lookup(mimeinfo->typeparameters,
1503                                        "charset") == NULL)
1504                         g_hash_table_insert(mimeinfo->typeparameters,
1505                                             g_strdup("charset"),
1506                                             g_strdup("us-ascii"));
1507         } else {
1508                 gchar *type, *subtype, *params;
1509
1510                 type = g_strdup(content_type);
1511                 subtype = strchr(type, '/') + 1;
1512                 *(subtype - 1) = '\0';
1513                 if ((params = strchr(subtype, ';')) != NULL) {
1514                         params[0] = '\0';
1515                         params++;
1516                 }
1517
1518                 mimeinfo->type = procmime_get_media_type(type);
1519                 mimeinfo->subtype = g_strdup(subtype);
1520
1521                 /* Get mimeinfo->typeparameters */
1522                 if (params != NULL)
1523                         parse_parameters(params, mimeinfo->typeparameters);
1524
1525                 g_free(type);
1526         }
1527 }
1528
1529 static void procmime_parse_content_disposition(const gchar *content_disposition, MimeInfo *mimeinfo)
1530 {
1531         gchar *tmp, *params;
1532
1533         g_return_if_fail(content_disposition != NULL);
1534         g_return_if_fail(mimeinfo != NULL);
1535
1536         tmp = g_strdup(content_disposition);
1537         if ((params = strchr(tmp, ';')) != NULL) {
1538                 params[0] = '\0';
1539                 params++;
1540         }       
1541         g_strstrip(tmp);
1542
1543         if (!g_ascii_strcasecmp(tmp, "inline")) 
1544                 mimeinfo->disposition = DISPOSITIONTYPE_INLINE;
1545         else if (!g_ascii_strcasecmp(tmp, "attachment"))
1546                 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1547         else
1548                 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1549         
1550         if (params != NULL)
1551                 parse_parameters(params, mimeinfo->dispositionparameters);
1552
1553         g_free(tmp);
1554 }
1555
1556
1557 static void procmime_parse_content_encoding(const gchar *content_encoding, MimeInfo *mimeinfo)
1558 {
1559         struct EncodingTable *enc_table;
1560         
1561         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1562                 if (g_ascii_strcasecmp(enc_table->str, content_encoding) == 0) {
1563                         mimeinfo->encoding_type = enc_table->enc_type;
1564                         return;
1565                 }
1566         }
1567         mimeinfo->encoding_type = ENC_UNKNOWN;
1568         return;
1569 }
1570
1571 void procmime_parse_mimepart(MimeInfo *parent,
1572                              gchar *content_type,
1573                              gchar *content_encoding,
1574                              gchar *content_description,
1575                              gchar *content_id,
1576                              gchar *content_disposition,
1577                              const gchar *filename,
1578                              guint offset,
1579                              guint length)
1580 {
1581         MimeInfo *mimeinfo;
1582
1583         /* Create MimeInfo */
1584         mimeinfo = procmime_mimeinfo_new();
1585         mimeinfo->content = MIMECONTENT_FILE;
1586         if (parent != NULL)
1587                 g_node_append(parent->node, mimeinfo->node);
1588         mimeinfo->data.filename = g_strdup(filename);
1589         mimeinfo->offset = offset;
1590         mimeinfo->length = length;
1591
1592         if (content_type != NULL) {
1593                 procmime_parse_content_type(content_type, mimeinfo);
1594         } else {
1595                 mimeinfo->type = MIMETYPE_TEXT;
1596                 mimeinfo->subtype = g_strdup("plain");
1597                 if (g_hash_table_lookup(mimeinfo->typeparameters,
1598                                        "charset") == NULL)
1599                         g_hash_table_insert(mimeinfo->typeparameters, g_strdup("charset"), g_strdup("us-ascii"));
1600         }
1601
1602         if (content_encoding != NULL) {
1603                 procmime_parse_content_encoding(content_encoding, mimeinfo);
1604         } else {
1605                 mimeinfo->encoding_type = ENC_UNKNOWN;
1606         }
1607
1608         if (content_description != NULL)
1609                 mimeinfo->description = g_strdup(content_description);
1610         else
1611                 mimeinfo->description = NULL;
1612
1613         if (content_id != NULL)
1614                 mimeinfo->id = g_strdup(content_id);
1615         else
1616                 mimeinfo->id = NULL;
1617
1618         if (content_disposition != NULL) 
1619                 procmime_parse_content_disposition(content_disposition, mimeinfo);
1620         else
1621                 mimeinfo->disposition = DISPOSITIONTYPE_UNKNOWN;
1622
1623         /* Call parser for mime type */
1624         switch (mimeinfo->type) {
1625                 case MIMETYPE_MESSAGE:
1626                         if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
1627                                 procmime_parse_message_rfc822(mimeinfo);
1628                         }
1629                         break;
1630                         
1631                 case MIMETYPE_MULTIPART:
1632                         procmime_parse_multipart(mimeinfo);
1633                         break;
1634                         
1635                 default:
1636                         break;
1637         }
1638 }
1639
1640 static gchar *typenames[] = {
1641     "text",
1642     "image",
1643     "audio",
1644     "video",
1645     "application",
1646     "message",
1647     "multipart",
1648     "unknown",
1649 };
1650
1651 static gboolean output_func(GNode *node, gpointer data)
1652 {
1653         guint i, depth;
1654         MimeInfo *mimeinfo = (MimeInfo *) node->data;
1655
1656         depth = g_node_depth(node);
1657         for (i = 0; i < depth; i++)
1658                 printf("    ");
1659         printf("%s/%s (offset:%d length:%d encoding: %d)\n", typenames[mimeinfo->type], mimeinfo->subtype, mimeinfo->offset, mimeinfo->length, mimeinfo->encoding_type);
1660
1661         return FALSE;
1662 }
1663
1664 static void output_mime_structure(MimeInfo *mimeinfo, int indent)
1665 {
1666         g_node_traverse(mimeinfo->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1, output_func, NULL);
1667 }
1668
1669 MimeInfo *procmime_scan_file_with_offset(const gchar *filename, int offset)
1670 {
1671         MimeInfo *mimeinfo;
1672         struct stat buf;
1673
1674         stat(filename, &buf);
1675
1676         mimeinfo = procmime_mimeinfo_new();
1677         mimeinfo->content = MIMECONTENT_FILE;
1678         mimeinfo->encoding_type = ENC_UNKNOWN;
1679         mimeinfo->type = MIMETYPE_MESSAGE;
1680         mimeinfo->subtype = g_strdup("rfc822");
1681         mimeinfo->data.filename = g_strdup(filename);
1682         mimeinfo->offset = offset;
1683         mimeinfo->length = buf.st_size - offset;
1684
1685         procmime_parse_message_rfc822(mimeinfo);
1686         if (debug_get_mode())
1687                 output_mime_structure(mimeinfo, 0);
1688
1689         return mimeinfo;
1690 }
1691
1692 MimeInfo *procmime_scan_file(const gchar *filename)
1693 {
1694         MimeInfo *mimeinfo;
1695
1696         g_return_val_if_fail(filename != NULL, NULL);
1697
1698         mimeinfo = procmime_scan_file_with_offset(filename, 0);
1699
1700         return mimeinfo;
1701 }
1702
1703 MimeInfo *procmime_scan_queue_file(const gchar *filename)
1704 {
1705         FILE *fp;
1706         MimeInfo *mimeinfo;
1707         gchar buf[BUFFSIZE];
1708         gint offset = 0;
1709
1710         g_return_val_if_fail(filename != NULL, NULL);
1711
1712         /* Open file */
1713         if ((fp = fopen(filename, "rb")) == NULL)
1714                 return NULL;
1715         /* Skip queue header */
1716         while (fgets(buf, sizeof(buf), fp) != NULL)
1717                 if (buf[0] == '\r' || buf[0] == '\n') break;
1718         offset = ftell(fp);
1719         fclose(fp);
1720
1721         mimeinfo = procmime_scan_file_with_offset(filename, offset);
1722
1723         return mimeinfo;
1724 }
1725
1726 typedef enum {
1727     ENC_AS_TOKEN,
1728     ENC_AS_QUOTED_STRING,
1729     ENC_AS_EXTENDED,
1730 } EncodeAs;
1731
1732 typedef struct _ParametersData {
1733         FILE *fp;
1734         guint len;
1735 } ParametersData;
1736
1737 static void write_parameters(gpointer key, gpointer value, gpointer user_data)
1738 {
1739         gchar *param = key;
1740         gchar *val = value, *valpos;
1741         ParametersData *pdata = (ParametersData *)user_data;
1742         GString *buf = g_string_new("");
1743
1744         EncodeAs encas = ENC_AS_TOKEN;
1745
1746         for (valpos = val; *valpos != 0; valpos++) {
1747                 if (!IS_ASCII(*valpos)) {
1748                         encas = ENC_AS_EXTENDED;
1749                         break;
1750                 }
1751             
1752                 /* CTLs */
1753                 if (((*valpos >= 0) && (*valpos < 037)) || (*valpos == 0177)) {
1754                         encas = ENC_AS_QUOTED_STRING;
1755                         continue;
1756                 }
1757
1758                 /* tspecials + SPACE */
1759                 switch (*valpos) {
1760                 case ' ':
1761                 case '(': 
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                         encas = ENC_AS_QUOTED_STRING;
1777                         continue;
1778                 }
1779         }
1780
1781         switch (encas) {
1782         case ENC_AS_TOKEN:
1783                 g_string_append_printf(buf, "%s=%s", param, val);
1784                 break;
1785
1786         case ENC_AS_QUOTED_STRING:
1787                 g_string_append_printf(buf, "%s=\"%s\"", param, val);
1788                 break;
1789
1790         case ENC_AS_EXTENDED:
1791                 g_string_append_printf(buf, "%s*=%s''", param,
1792                         conv_get_locale_charset_str());
1793                 for (valpos = val; *valpos != '\0'; valpos++) {
1794                         if (IS_ASCII(*valpos) && isalnum(*valpos)) {
1795                                 g_string_append_printf(buf, "%c", *valpos);
1796                         } else {
1797                                 gchar hexstr[3] = "XX";
1798                                 get_hex_str(hexstr, *valpos);
1799                                 g_string_append_printf(buf, "%%%s", hexstr);
1800                         }
1801                 }
1802                 break;
1803         }
1804         
1805         if (buf->str && strlen(buf->str)) {
1806                 if (pdata->len + strlen(buf->str) + 2 > 76) {
1807                         fprintf(pdata->fp, ";\n %s", buf->str);
1808                         pdata->len = strlen(buf->str) + 1;
1809                 } else {
1810                         fprintf(pdata->fp, "; %s", buf->str);
1811                         pdata->len += strlen(buf->str) + 2;
1812                 }
1813         }
1814         g_string_free(buf, TRUE);
1815 }
1816
1817 void procmime_write_mime_header(MimeInfo *mimeinfo, FILE *fp)
1818 {
1819         struct TypeTable *type_table;
1820         ParametersData *pdata = g_new0(ParametersData, 1);
1821         debug_print("procmime_write_mime_header\n");
1822         
1823         pdata->fp = fp;
1824
1825         for (type_table = mime_type_table; type_table->str != NULL; type_table++)
1826                 if (mimeinfo->type == type_table->type) {
1827                         gchar *buf = g_strdup_printf(
1828                                 "Content-Type: %s/%s", type_table->str, mimeinfo->subtype);
1829                         fprintf(fp, "%s", buf);
1830                         pdata->len = strlen(buf);
1831                         g_free(buf);
1832                         break;
1833                 }
1834         g_hash_table_foreach(mimeinfo->typeparameters, write_parameters, pdata);
1835         g_free(pdata);
1836
1837         fprintf(fp, "\n");
1838
1839         if (mimeinfo->encoding_type != ENC_UNKNOWN)
1840                 fprintf(fp, "Content-Transfer-Encoding: %s\n", procmime_get_encoding_str(mimeinfo->encoding_type));
1841
1842         if (mimeinfo->description != NULL)
1843                 fprintf(fp, "Content-Description: %s\n", mimeinfo->description);
1844
1845         if (mimeinfo->id != NULL)
1846                 fprintf(fp, "Content-ID: %s\n", mimeinfo->id);
1847
1848         if (mimeinfo->disposition != DISPOSITIONTYPE_UNKNOWN) {
1849                 ParametersData *pdata = g_new0(ParametersData, 1);
1850                 gchar *buf = NULL;
1851                 if (mimeinfo->disposition == DISPOSITIONTYPE_INLINE)
1852                         buf = g_strdup("Content-Disposition: inline");
1853                 else if (mimeinfo->disposition == DISPOSITIONTYPE_ATTACHMENT)
1854                         buf = g_strdup("Content-Disposition: attachment");
1855                 else
1856                         buf = g_strdup("Content-Disposition: unknown");
1857
1858                 fprintf(fp, "%s", buf);
1859                 pdata->len = strlen(buf);
1860                 g_free(buf);
1861
1862                 pdata->fp = fp;
1863                 g_hash_table_foreach(mimeinfo->dispositionparameters, write_parameters, pdata);
1864                 g_free(pdata);
1865                 fprintf(fp, "\n");
1866         }
1867
1868         fprintf(fp, "\n");
1869 }
1870
1871 gint procmime_write_message_rfc822(MimeInfo *mimeinfo, FILE *fp)
1872 {
1873         FILE *infp;
1874         GNode *childnode;
1875         MimeInfo *child;
1876         gchar buf[BUFFSIZE];
1877         gboolean skip = FALSE;;
1878
1879         debug_print("procmime_write_message_rfc822\n");
1880
1881         /* write header */
1882         switch (mimeinfo->content) {
1883         case MIMECONTENT_FILE:
1884                 if ((infp = fopen(mimeinfo->data.filename, "rb")) == NULL) {
1885                         FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1886                         return -1;
1887                 }
1888                 fseek(infp, mimeinfo->offset, SEEK_SET);
1889                 while (fgets(buf, sizeof(buf), infp) == buf) {
1890                         if (buf[0] == '\n' && buf[1] == '\0')
1891                                 break;
1892                         if (skip && (buf[0] == ' ' || buf[0] == '\t'))
1893                                 continue;
1894                         if (g_ascii_strncasecmp(buf, "Mime-Version:", 13) == 0 ||
1895                             g_ascii_strncasecmp(buf, "Content-Type:", 13) == 0 ||
1896                             g_ascii_strncasecmp(buf, "Content-Transfer-Encoding:", 26) == 0 ||
1897                             g_ascii_strncasecmp(buf, "Content-Description:", 20) == 0 ||
1898                             g_ascii_strncasecmp(buf, "Content-ID:", 11) == 0 ||
1899                             g_ascii_strncasecmp(buf, "Content-Disposition:", 20) == 0) {
1900                                 skip = TRUE;
1901                                 continue;
1902                         }
1903                         fwrite(buf, sizeof(gchar), strlen(buf), fp);
1904                         skip = FALSE;
1905                 }
1906                 fclose(infp);
1907                 break;
1908
1909         case MIMECONTENT_MEM:
1910                 fwrite(mimeinfo->data.mem, strlen(mimeinfo->data.mem), sizeof(gchar), fp);
1911                 break;
1912
1913         default:
1914                 break;
1915         }
1916
1917         childnode = mimeinfo->node->children;
1918         if (childnode == NULL)
1919                 return -1;
1920
1921         child = (MimeInfo *) childnode->data;
1922         fprintf(fp, "Mime-Version: 1.0\n");
1923         procmime_write_mime_header(child, fp);
1924         return procmime_write_mimeinfo(child, fp);
1925 }
1926
1927 gint procmime_write_multipart(MimeInfo *mimeinfo, FILE *fp)
1928 {
1929         FILE *infp;
1930         GNode *childnode;
1931         gchar *boundary, *str, *str2;
1932         gchar buf[BUFFSIZE];
1933         gboolean firstboundary;
1934
1935         debug_print("procmime_write_multipart\n");
1936
1937         boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
1938
1939         switch (mimeinfo->content) {
1940         case MIMECONTENT_FILE:
1941                 if ((infp = fopen(mimeinfo->data.filename, "rb")) == NULL) {
1942                         FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1943                         return -1;
1944                 }
1945                 fseek(infp, mimeinfo->offset, SEEK_SET);
1946                 while (fgets(buf, sizeof(buf), infp) == buf) {
1947                         if (IS_BOUNDARY(buf, boundary, strlen(boundary)))
1948                                 break;
1949                         fwrite(buf, sizeof(gchar), strlen(buf), fp);
1950                 }
1951                 fclose(infp);
1952                 break;
1953
1954         case MIMECONTENT_MEM:
1955                 str = g_strdup(mimeinfo->data.mem);
1956                 if (((str2 = strstr(str, boundary)) != NULL) && ((str2 - str) >= 2) &&
1957                     (*(str2 - 1) == '-') && (*(str2 - 2) == '-'))
1958                         *(str2 - 2) = '\0';
1959                 fwrite(str, strlen(str), sizeof(gchar), fp);
1960                 g_free(str);
1961                 break;
1962
1963         default:
1964                 break;
1965         }
1966
1967         childnode = mimeinfo->node->children;
1968         firstboundary = TRUE;
1969         while (childnode != NULL) {
1970                 MimeInfo *child = childnode->data;
1971
1972                 if (firstboundary)
1973                         firstboundary = FALSE;
1974                 else
1975                         fprintf(fp, "\n");
1976                 fprintf(fp, "--%s\n", boundary);
1977
1978                 procmime_write_mime_header(child, fp);
1979                 if (procmime_write_mimeinfo(child, fp) < 0)
1980                         return -1;
1981
1982                 childnode = g_node_next_sibling(childnode);
1983         }       
1984         fprintf(fp, "\n--%s--\n", boundary);
1985
1986         return 0;
1987 }
1988
1989 gint procmime_write_mimeinfo(MimeInfo *mimeinfo, FILE *fp)
1990 {
1991         FILE *infp;
1992
1993         debug_print("procmime_write_mimeinfo\n");
1994
1995         if (G_NODE_IS_LEAF(mimeinfo->node)) {
1996                 switch (mimeinfo->content) {
1997                 case MIMECONTENT_FILE:
1998                         if ((infp = fopen(mimeinfo->data.filename, "rb")) == NULL) {
1999                                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2000                                 return -1;
2001                         }
2002                         copy_file_part_to_fp(infp, mimeinfo->offset, mimeinfo->length, fp);
2003                         fclose(infp);
2004                         return 0;
2005
2006                 case MIMECONTENT_MEM:
2007                         fwrite(mimeinfo->data.mem, strlen(mimeinfo->data.mem), sizeof(gchar), fp);
2008                         return 0;
2009
2010                 default:
2011                         return 0;
2012                 }
2013         } else {
2014                 /* Call writer for mime type */
2015                 switch (mimeinfo->type) {
2016                 case MIMETYPE_MESSAGE:
2017                         if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0)
2018                                 return procmime_write_message_rfc822(mimeinfo, fp);
2019                         break;
2020                         
2021                 case MIMETYPE_MULTIPART:
2022                         return procmime_write_multipart(mimeinfo, fp);
2023                         
2024                 default:
2025                         break;
2026                 }
2027
2028                 return -1;
2029         }
2030
2031         return 0;
2032 }