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