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