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