0.9.6claws52
[claws.git] / src / procmime.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2003 Hiroyuki Yamamoto
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 <glib.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <sys/types.h>
32 #include <sys/stat.h>
33 #include <unistd.h>
34
35 #include "intl.h"
36 #include "procmime.h"
37 #include "procheader.h"
38 #include "base64.h"
39 #include "quoted-printable.h"
40 #include "uuencode.h"
41 #include "unmime.h"
42 #include "html.h"
43 #include "enriched.h"
44 #include "codeconv.h"
45 #include "utils.h"
46 #include "prefs_common.h"
47
48 #include "prefs_gtk.h"
49
50 static GHashTable *procmime_get_mime_type_table (void);
51
52 MimeInfo *procmime_mimeinfo_new(void)
53 {
54         MimeInfo *mimeinfo;
55
56         mimeinfo = g_new0(MimeInfo, 1);
57         mimeinfo->type          = MIMETYPE_UNKNOWN;
58         mimeinfo->encoding_type = ENC_UNKNOWN;
59
60         mimeinfo->parameters = g_hash_table_new(g_str_hash, g_str_equal);
61         mimeinfo->node       = g_node_new(mimeinfo);
62
63         return mimeinfo;
64 }
65
66 static gboolean procmime_mimeinfo_parameters_destroy(gpointer key, gpointer value, gpointer user_data)
67 {
68         g_free(key);
69         g_free(value);
70         
71         return TRUE;
72 }
73
74 static gboolean free_func(GNode *node, gpointer data)
75 {
76         MimeInfo *mimeinfo = (MimeInfo *) node->data;
77
78         g_free(mimeinfo->encoding);
79         g_free(mimeinfo->name);
80         g_free(mimeinfo->content_disposition);
81         if(mimeinfo->tmpfile)
82                 unlink(mimeinfo->filename);
83         g_free(mimeinfo->filename);
84
85         g_free(mimeinfo->subtype);
86         g_free(mimeinfo->description);
87         g_free(mimeinfo->id);
88
89         g_hash_table_foreach_remove(mimeinfo->parameters, procmime_mimeinfo_parameters_destroy, NULL);
90         g_hash_table_destroy(mimeinfo->parameters);
91
92         if (mimeinfo->privacy)
93                 privacy_free_privacydata(mimeinfo->privacy);
94
95         g_free(mimeinfo);
96
97         return FALSE;
98 }
99
100 void procmime_mimeinfo_free_all(MimeInfo *mimeinfo)
101 {
102         GNode *node;
103
104         g_return_if_fail(mimeinfo);
105
106         node = mimeinfo->node;
107         g_node_traverse(node, G_IN_ORDER, G_TRAVERSE_ALL, -1, free_func, NULL);
108
109         g_node_destroy(node);
110 }
111
112 #if 0 /* UNUSED */
113 MimeInfo *procmime_mimeinfo_insert(MimeInfo *parent, MimeInfo *mimeinfo)
114 {
115         MimeInfo *child = parent->children;
116
117         if (!child)
118                 parent->children = mimeinfo;
119         else {
120                 while (child->next != NULL)
121                         child = child->next;
122
123                 child->next = mimeinfo;
124         }
125
126         mimeinfo->parent = parent;
127         mimeinfo->level = parent->level + 1;
128
129         return mimeinfo;
130 }
131
132 void procmime_mimeinfo_replace(MimeInfo *old, MimeInfo *new)
133 {
134         MimeInfo *parent = old->parent;
135         MimeInfo *child;
136
137         g_return_if_fail(parent != NULL);
138         g_return_if_fail(new->next == NULL);
139
140         for (child = parent->children; child && child != old;
141              child = child->next)
142                 ;
143         if (!child) {
144                 g_warning("oops: parent can't find it's own child");
145                 return;
146         }
147         procmime_mimeinfo_free_all(old);
148
149         if (child == parent->children) {
150                 new->next = parent->children->next;
151                 parent->children = new;
152         } else {
153                 new->next = child->next;
154                 child = new;
155         }
156 }
157 #endif
158
159 MimeInfo *procmime_mimeinfo_parent(MimeInfo *mimeinfo)
160 {
161         g_return_val_if_fail(mimeinfo != NULL, NULL);
162
163         if (mimeinfo->node->parent == NULL)
164                 return NULL;
165         return (MimeInfo *) mimeinfo->node->parent->data;
166 }
167
168 MimeInfo *procmime_mimeinfo_next(MimeInfo *mimeinfo)
169 {
170         g_return_val_if_fail(mimeinfo != NULL, NULL);
171         g_return_val_if_fail(mimeinfo->node != NULL, NULL);
172
173         if (mimeinfo->node->children)
174                 return (MimeInfo *) mimeinfo->node->children->data;
175         if (mimeinfo->node->next)
176                 return (MimeInfo *) mimeinfo->node->next->data;
177
178         if (mimeinfo->node->parent == NULL)
179                 return NULL;
180
181         while (mimeinfo->node->parent != NULL) {
182                 mimeinfo = (MimeInfo *) mimeinfo->node->parent->data;
183                 if (mimeinfo->node->next)
184                         return (MimeInfo *) mimeinfo->node->next->data;
185         }
186
187         return NULL;
188 }
189
190 MimeInfo *procmime_scan_message(MsgInfo *msginfo)
191 {
192         gchar *filename;
193         MimeInfo *mimeinfo;
194
195         filename = procmsg_get_message_file(msginfo);
196         if(!filename)
197                 return NULL;
198         if (msginfo->folder->stype != F_QUEUE)
199                 mimeinfo = procmime_scan_file(filename);
200         else
201                 mimeinfo = procmime_scan_queue_file(filename);
202         g_free(filename);
203
204         return mimeinfo;
205 }
206
207 enum
208 {
209         H_CONTENT_TRANSFER_ENCODING = 0,
210         H_CONTENT_TYPE              = 1,
211         H_CONTENT_DISPOSITION       = 2,
212         H_CONTENT_DESCRIPTION       = 3,
213         H_SUBJECT                   = 4
214 };
215
216 const gchar *procmime_mimeinfo_get_parameter(MimeInfo *mimeinfo, const gchar *name)
217 {
218         g_return_val_if_fail(mimeinfo != NULL, NULL);
219         g_return_val_if_fail(name != NULL, NULL);
220         
221         return g_hash_table_lookup(mimeinfo->parameters, name);
222 }
223
224 gboolean procmime_decode_content(MimeInfo *mimeinfo)
225 {
226         gchar buf[BUFFSIZE];
227         gint readend;
228         gchar *tmpfilename;
229         gchar *mimetmpdir;
230         FILE *outfp, *infp;
231         struct stat statbuf;
232
233         g_return_val_if_fail(mimeinfo != NULL, FALSE);
234
235         if(mimeinfo->encoding_type == ENC_BINARY)
236                 return TRUE;
237
238         infp = fopen(mimeinfo->filename, "rb");
239         if(!infp) {
240                 perror("fopen");
241                 return FALSE;
242         }
243         fseek(infp, mimeinfo->offset, SEEK_SET);
244
245         mimetmpdir = get_mime_tmp_dir();
246         outfp = get_tmpfile_in_dir(mimetmpdir, &tmpfilename);
247         if (!outfp) {
248                 perror("tmpfile");
249                 return FALSE;
250         }
251
252         readend = mimeinfo->offset + mimeinfo->length;
253
254         if (mimeinfo->encoding_type == ENC_QUOTED_PRINTABLE) {
255                 while ((ftell(infp) < readend) && (fgets(buf, sizeof(buf), infp) != NULL)) {
256                         gint len;
257                         len = qp_decode_line(buf);
258                         fwrite(buf, len, 1, outfp);
259                 }
260         } else if (mimeinfo->encoding_type == ENC_BASE64) {
261                 gchar outbuf[BUFFSIZE];
262                 gint len;
263                 Base64Decoder *decoder;
264
265                 decoder = base64_decoder_new();
266                 while ((ftell(infp) < readend) && (fgets(buf, sizeof(buf), infp) != NULL)) {
267                         len = base64_decoder_decode(decoder, buf, outbuf);
268                         if (len < 0) {
269                                 g_warning("Bad BASE64 content\n");
270                                 break;
271                         }
272                         fwrite(outbuf, sizeof(gchar), len, outfp);
273                 }
274                 base64_decoder_free(decoder);
275         } else if (mimeinfo->encoding_type == ENC_X_UUENCODE) {
276                 gchar outbuf[BUFFSIZE];
277                 gint len;
278                 gboolean flag = FALSE;
279
280                 while ((ftell(infp) < readend) && (fgets(buf, sizeof(buf), infp) != NULL)) {
281                         if(!flag && strncmp(buf,"begin ", 6)) continue;
282
283                         if (flag) {
284                                 len = fromuutobits(outbuf, buf);
285                                 if (len <= 0) {
286                                         if (len < 0) 
287                                                 g_warning("Bad UUENCODE content(%d)\n", len);
288                                         break;
289                                 }
290                                 fwrite(outbuf, sizeof(gchar), len, outfp);
291                         } else
292                                 flag = TRUE;
293                 }
294         } else {
295                 while ((ftell(infp) < readend) && (fgets(buf, sizeof(buf), infp) != NULL)) {
296                         fputs(buf, outfp);
297                 }
298         }
299
300         fclose(outfp);
301         fclose(infp);
302
303         stat(tmpfilename, &statbuf);
304         if(mimeinfo->tmpfile)
305                 unlink(mimeinfo->filename);
306         g_free(mimeinfo->filename);
307         mimeinfo->filename = tmpfilename;
308         mimeinfo->tmpfile = TRUE;
309         mimeinfo->offset = 0;
310         mimeinfo->length = statbuf.st_size;
311         mimeinfo->encoding_type = ENC_BINARY;
312
313         return TRUE;
314 }
315
316 gint procmime_get_part(const gchar *outfile, MimeInfo *mimeinfo)
317 {
318         FILE *infp, *outfp;
319         gchar buf[BUFFSIZE];
320         gint restlength, readlength;
321
322         g_return_val_if_fail(outfile != NULL, -1);
323         g_return_val_if_fail(mimeinfo != NULL, -1);
324
325         if(mimeinfo->encoding_type != ENC_BINARY && !procmime_decode_content(mimeinfo))
326                 return -1;
327
328         if ((infp = fopen(mimeinfo->filename, "rb")) == NULL) {
329                 FILE_OP_ERROR(mimeinfo->filename, "fopen");
330                 return -1;
331         }
332         if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
333                 FILE_OP_ERROR(mimeinfo->filename, "fseek");
334                 fclose(infp);
335                 return -1;
336         }
337         if ((outfp = fopen(outfile, "wb")) == NULL) {
338                 FILE_OP_ERROR(outfile, "fopen");
339                 fclose(infp);
340                 return -1;
341         }
342
343         restlength = mimeinfo->length;
344
345         while ((restlength > 0) && ((readlength = fread(buf, 1, restlength > BUFFSIZE ? BUFFSIZE : restlength, infp)) > 0)) {
346                 fwrite(buf, 1, readlength, outfp);
347                 restlength -= readlength;
348         }
349
350         fclose(infp);
351         if (fclose(outfp) == EOF) {
352                 FILE_OP_ERROR(outfile, "fclose");
353                 unlink(outfile);
354                 return -1;
355         }
356
357         return 0;
358 }
359
360 struct ContentRenderer {
361         char * content_type;
362         char * renderer;
363 };
364
365 static GList * renderer_list = NULL;
366
367 static struct ContentRenderer *
368 content_renderer_new(char * content_type, char * renderer)
369 {
370         struct ContentRenderer * cr;
371
372         cr = g_new(struct ContentRenderer, 1);
373         if (cr == NULL)
374                 return NULL;
375
376         cr->content_type = g_strdup(content_type);
377         cr->renderer = g_strdup(renderer);
378
379         return cr;
380 }
381
382 static void content_renderer_free(struct ContentRenderer * cr)
383 {
384         g_free(cr->content_type);
385         g_free(cr->renderer);
386         g_free(cr);
387 }
388
389 void renderer_read_config(void)
390 {
391         gchar buf[BUFFSIZE];
392         FILE * f;
393         gchar * rcpath;
394
395         g_list_foreach(renderer_list, (GFunc) content_renderer_free, NULL);
396         renderer_list = NULL;
397
398         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, RENDERER_RC, NULL);
399         f = fopen(rcpath, "rb");
400         g_free(rcpath);
401         
402         if (f == NULL)
403                 return;
404
405         while (fgets(buf, BUFFSIZE, f)) {
406                 char * p;
407                 struct ContentRenderer * cr;
408
409                 strretchomp(buf);
410                 p = strchr(buf, ' ');
411                 if (p == NULL)
412                         continue;
413                 * p = 0;
414
415                 cr = content_renderer_new(buf, p + 1);
416                 if (cr == NULL)
417                         continue;
418
419                 renderer_list = g_list_append(renderer_list, cr);
420         }
421
422         fclose(f);
423 }
424
425 void renderer_write_config(void)
426 {
427         gchar * rcpath;
428         PrefFile *pfile;
429         GList * cur;
430
431         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, RENDERER_RC, NULL);
432         
433         if ((pfile = prefs_write_open(rcpath)) == NULL) {
434                 g_warning("failed to write configuration to file\n");
435                 g_free(rcpath);
436                 return;
437         }
438
439         g_free(rcpath);
440
441         for(cur = renderer_list ; cur != NULL ; cur = cur->next) {
442                 struct ContentRenderer * renderer;
443                 renderer = cur->data;
444                 fprintf(pfile->fp, "%s %s\n", renderer->content_type,
445                         renderer->renderer);
446         }
447
448         if (prefs_file_close(pfile) < 0) {
449                 g_warning("failed to write configuration to file\n");
450                 return;
451         }
452 }
453
454 FILE *procmime_get_text_content(MimeInfo *mimeinfo)
455 {
456         FILE *tmpfp, *outfp;
457         const gchar *src_codeset;
458         gboolean conv_fail = FALSE;
459         gchar buf[BUFFSIZE];
460         gchar *str;
461         struct ContentRenderer * renderer;
462         GList * cur;
463         gchar *tmpfile, *content_type;
464     
465         g_return_val_if_fail(mimeinfo != NULL, NULL);
466
467         if (!procmime_decode_content(mimeinfo))
468                 return NULL;
469
470         tmpfile = procmime_get_tmp_file_name(mimeinfo);
471         if (tmpfile == NULL)
472                 return NULL;
473
474         if (procmime_get_part(tmpfile, mimeinfo) < 0) {
475                 g_free(tmpfile);
476                 return NULL;
477         }
478
479         tmpfp = fopen(tmpfile, "rb");
480         if (tmpfp == NULL) {
481                 g_free(tmpfile);
482                 return NULL;
483         }
484
485         if ((outfp = my_tmpfile()) == NULL) {
486                 perror("tmpfile");
487                 fclose(tmpfp);
488                 g_free(tmpfile);
489                 return NULL;
490         }
491
492         src_codeset = prefs_common.force_charset
493                 ? prefs_common.force_charset : 
494                 procmime_mimeinfo_get_parameter(mimeinfo, "charset");
495
496         renderer = NULL;
497
498         content_type = g_strdup_printf("%s/%s", procmime_get_type_str(mimeinfo->type),
499                 mimeinfo->subtype);
500         for(cur = renderer_list ; cur != NULL ; cur = cur->next) {
501                 struct ContentRenderer * cr;
502
503                 cr = cur->data;
504                 if (g_strcasecmp(cr->content_type, content_type) == 0) {
505                         renderer = cr;
506                         break;
507                 }
508         }
509         g_free(content_type);
510
511         if (renderer != NULL) {
512                 FILE * p;
513                 int oldout;
514                 
515                 oldout = dup(1);
516                 
517                 dup2(fileno(outfp), 1);
518                 
519                 p = popen(renderer->renderer, "w");
520                 if (p != NULL) {
521                         size_t count;
522                         
523                         while ((count =
524                                 fread(buf, sizeof(char), sizeof(buf),
525                                       tmpfp)) > 0)
526                                 fwrite(buf, sizeof(char), count, p);
527                         pclose(p);
528                 }
529                 
530                 dup2(oldout, 1);
531         } else if (mimeinfo->type == MIMETYPE_TEXT && !g_strcasecmp(mimeinfo->subtype, "html")) {
532                 HTMLParser *parser;
533                 CodeConverter *conv;
534
535                 conv = conv_code_converter_new(src_codeset);
536                 parser = html_parser_new(tmpfp, conv);
537                 while ((str = html_parse(parser)) != NULL) {
538                         fputs(str, outfp);
539                 }
540                 html_parser_destroy(parser);
541                 conv_code_converter_destroy(conv);
542         } else if (mimeinfo->type == MIMETYPE_TEXT && !g_strcasecmp(mimeinfo->subtype, "enriched")) {
543                 ERTFParser *parser;
544                 CodeConverter *conv;
545
546                 conv = conv_code_converter_new(src_codeset);
547                 parser = ertf_parser_new(tmpfp, conv);
548                 while ((str = ertf_parse(parser)) != NULL) {
549                         fputs(str, outfp);
550                 }
551                 ertf_parser_destroy(parser);
552                 conv_code_converter_destroy(conv);
553         } else if (mimeinfo->type == MIMETYPE_TEXT) {
554                 while (fgets(buf, sizeof(buf), tmpfp) != NULL) {
555                         str = conv_codeset_strdup(buf, src_codeset, NULL);
556                         if (str) {
557                                 fputs(str, outfp);
558                                 g_free(str);
559                         } else {
560                                 conv_fail = TRUE;
561                                 fputs(buf, outfp);
562                         }
563                 }
564         }
565
566         if (conv_fail)
567                 g_warning("procmime_get_text_content(): Code conversion failed.\n");
568
569         fclose(tmpfp);
570         rewind(outfp);
571         unlink(tmpfile);
572         g_free(tmpfile);
573
574         return outfp;
575 }
576
577 /* search the first text part of (multipart) MIME message,
578    decode, convert it and output to outfp. */
579 FILE *procmime_get_first_text_content(MsgInfo *msginfo)
580 {
581         FILE *outfp = NULL;
582         MimeInfo *mimeinfo, *partinfo;
583
584         g_return_val_if_fail(msginfo != NULL, NULL);
585
586         mimeinfo = procmime_scan_message(msginfo);
587         if (!mimeinfo) return NULL;
588
589         partinfo = mimeinfo;
590         while (partinfo && partinfo->type != MIMETYPE_TEXT)
591                 partinfo = procmime_mimeinfo_next(partinfo);
592
593         if (partinfo)
594                 outfp = procmime_get_text_content(partinfo);
595
596         procmime_mimeinfo_free_all(mimeinfo);
597
598         return outfp;
599 }
600
601 gboolean procmime_find_string_part(MimeInfo *mimeinfo, const gchar *filename,
602                                    const gchar *str, gboolean case_sens)
603 {
604         FILE *infp, *outfp;
605         gchar buf[BUFFSIZE];
606         gchar *(* StrFindFunc) (const gchar *haystack, const gchar *needle);
607
608         g_return_val_if_fail(mimeinfo != NULL, FALSE);
609         g_return_val_if_fail(mimeinfo->type == MIMETYPE_TEXT, FALSE);
610         g_return_val_if_fail(str != NULL, FALSE);
611
612         outfp = procmime_get_text_content(mimeinfo);
613
614         if (!outfp)
615                 return FALSE;
616
617         if (case_sens)
618                 StrFindFunc = strstr;
619         else
620                 StrFindFunc = strcasestr;
621
622         while (fgets(buf, sizeof(buf), outfp) != NULL) {
623                 if (StrFindFunc(buf, str) != NULL) {
624                         fclose(outfp);
625                         return TRUE;
626                 }
627         }
628
629         fclose(outfp);
630
631         return FALSE;
632 }
633
634 gboolean procmime_find_string(MsgInfo *msginfo, const gchar *str,
635                               gboolean case_sens)
636 {
637         MimeInfo *mimeinfo;
638         MimeInfo *partinfo;
639         gchar *filename;
640         gboolean found = FALSE;
641
642         g_return_val_if_fail(msginfo != NULL, FALSE);
643         g_return_val_if_fail(str != NULL, FALSE);
644
645         filename = procmsg_get_message_file(msginfo);
646         if (!filename) return FALSE;
647         mimeinfo = procmime_scan_message(msginfo);
648
649         for (partinfo = mimeinfo; partinfo != NULL;
650              partinfo = procmime_mimeinfo_next(partinfo)) {
651                 if (partinfo->type == MIMETYPE_TEXT) {
652                         if (procmime_find_string_part
653                                 (partinfo, filename, str, case_sens) == TRUE) {
654                                 found = TRUE;
655                                 break;
656                         }
657                 }
658         }
659
660         procmime_mimeinfo_free_all(mimeinfo);
661         g_free(filename);
662
663         return found;
664 }
665
666 gchar *procmime_get_tmp_file_name(MimeInfo *mimeinfo)
667 {
668         static guint32 id = 0;
669         gchar *base;
670         gchar *filename;
671         gchar f_prefix[10];
672
673         g_return_val_if_fail(mimeinfo != NULL, NULL);
674
675         g_snprintf(f_prefix, sizeof(f_prefix), "%08x.", id++);
676
677         if ((mimeinfo->type == MIMETYPE_TEXT) && !g_strcasecmp(mimeinfo->subtype, "html"))
678                 base = "mimetmp.html";
679         else {
680                 base = mimeinfo->filename ? mimeinfo->filename
681                         : mimeinfo->name ? mimeinfo->name : "mimetmp";
682                 base = g_basename(base);
683                 if (*base == '\0') base = "mimetmp";
684                 Xstrdup_a(base, base, return NULL);
685                 subst_for_filename(base);
686         }
687
688         filename = g_strconcat(get_mime_tmp_dir(), G_DIR_SEPARATOR_S,
689                                f_prefix, base, NULL);
690
691         return filename;
692 }
693
694 static GList *mime_type_list = NULL;
695
696 gchar *procmime_get_mime_type(const gchar *filename)
697 {
698         static GHashTable *mime_type_table = NULL;
699         MimeType *mime_type;
700         const gchar *p;
701         gchar *ext;
702
703         if (!mime_type_table) {
704                 mime_type_table = procmime_get_mime_type_table();
705                 if (!mime_type_table) return NULL;
706         }
707
708         filename = g_basename(filename);
709         p = strrchr(filename, '.');
710         if (!p) return NULL;
711
712         Xstrdup_a(ext, p + 1, return NULL);
713         g_strdown(ext);
714         mime_type = g_hash_table_lookup(mime_type_table, ext);
715         if (mime_type) {
716                 gchar *str;
717
718                 str = g_strconcat(mime_type->type, "/", mime_type->sub_type,
719                                   NULL);
720                 return str;
721         }
722
723         return NULL;
724 }
725
726 static guint procmime_str_hash(gconstpointer gptr)
727 {
728         guint hash_result = 0;
729         const char *str;
730
731         for (str = gptr; str && *str; str++) {
732                 if (isupper(*str)) hash_result += (*str + ' ');
733                 else hash_result += *str;
734         }
735
736         return hash_result;
737 }
738
739 static gint procmime_str_equal(gconstpointer gptr1, gconstpointer gptr2)
740 {
741         const char *str1 = gptr1;
742         const char *str2 = gptr2;
743
744         return !strcasecmp(str1, str2);
745 }
746
747 static GHashTable *procmime_get_mime_type_table(void)
748 {
749         GHashTable *table = NULL;
750         GList *cur;
751         MimeType *mime_type;
752         gchar **exts;
753
754         if (!mime_type_list) {
755                 mime_type_list = procmime_get_mime_type_list();
756                 if (!mime_type_list) return NULL;
757         }
758
759         table = g_hash_table_new(procmime_str_hash, procmime_str_equal);
760
761         for (cur = mime_type_list; cur != NULL; cur = cur->next) {
762                 gint i;
763                 gchar *key;
764
765                 mime_type = (MimeType *)cur->data;
766
767                 if (!mime_type->extension) continue;
768
769                 exts = g_strsplit(mime_type->extension, " ", 16);
770                 for (i = 0; exts[i] != NULL; i++) {
771                         /* make the key case insensitive */
772                         g_strdown(exts[i]);
773                         /* use previously dup'd key on overwriting */
774                         if (g_hash_table_lookup(table, exts[i]))
775                                 key = exts[i];
776                         else
777                                 key = g_strdup(exts[i]);
778                         g_hash_table_insert(table, key, mime_type);
779                 }
780                 g_strfreev(exts);
781         }
782
783         return table;
784 }
785
786 GList *procmime_get_mime_type_list(void)
787 {
788         GList *list = NULL;
789         FILE *fp;
790         gchar buf[BUFFSIZE];
791         gchar *p, *delim;
792         MimeType *mime_type;
793
794         if (mime_type_list) 
795                 return mime_type_list;
796
797         if ((fp = fopen("/etc/mime.types", "rb")) == NULL) {
798                 if ((fp = fopen(SYSCONFDIR "/mime.types", "rb")) == NULL) {
799                         FILE_OP_ERROR(SYSCONFDIR "/mime.types", "fopen");
800                         return NULL;
801                 }
802         }
803
804         while (fgets(buf, sizeof(buf), fp) != NULL) {
805                 p = strchr(buf, '#');
806                 if (p) *p = '\0';
807                 g_strstrip(buf);
808
809                 p = buf;
810                 while (*p && !isspace(*p)) p++;
811                 if (*p) {
812                         *p = '\0';
813                         p++;
814                 }
815                 delim = strchr(buf, '/');
816                 if (delim == NULL) continue;
817                 *delim = '\0';
818
819                 mime_type = g_new(MimeType, 1);
820                 mime_type->type = g_strdup(buf);
821                 mime_type->sub_type = g_strdup(delim + 1);
822
823                 while (*p && isspace(*p)) p++;
824                 if (*p)
825                         mime_type->extension = g_strdup(p);
826                 else
827                         mime_type->extension = NULL;
828
829                 list = g_list_append(list, mime_type);
830         }
831
832         fclose(fp);
833
834         if (!list)
835                 g_warning("Can't read mime.types\n");
836
837         return list;
838 }
839
840 EncodingType procmime_get_encoding_for_charset(const gchar *charset)
841 {
842         if (!charset)
843                 return ENC_8BIT;
844         else if (!strncasecmp(charset, "ISO-2022-", 9) ||
845                  !strcasecmp(charset, "US-ASCII"))
846                 return ENC_7BIT;
847         else if (!strcasecmp(charset, "ISO-8859-5") ||
848                  !strncasecmp(charset, "KOI8-", 5) ||
849                  !strcasecmp(charset, "Windows-1251"))
850                 return ENC_8BIT;
851         else if (!strncasecmp(charset, "ISO-8859-", 9))
852                 return ENC_QUOTED_PRINTABLE;
853         else
854                 return ENC_8BIT;
855 }
856
857 EncodingType procmime_get_encoding_for_file(const gchar *file)
858 {
859         FILE *fp;
860         guchar buf[BUFSIZ];
861         size_t len;
862
863         if ((fp = fopen(file, "rb")) == NULL) {
864                 FILE_OP_ERROR(file, "fopen");
865                 return ENC_UNKNOWN;
866         }
867
868         while ((len = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
869                 guchar *p;
870                 gint i;
871
872                 for (p = buf, i = 0; i < len; p++, i++) {
873                         if (*p & 0x80) {
874                                 fclose(fp);
875                                 return ENC_BASE64;
876                         }
877                 }
878         }
879
880         fclose(fp);
881         return ENC_7BIT;
882 }
883
884 struct EncodingTable 
885 {
886         gchar *str;
887         EncodingType enc_type;
888 };
889
890 struct EncodingTable encoding_table[] = {
891         {"7bit", ENC_7BIT},
892         {"8bit", ENC_8BIT},
893         {"binary", ENC_BINARY},
894         {"quoted-printable", ENC_QUOTED_PRINTABLE},
895         {"base64", ENC_BASE64},
896         {"x-uuencode", ENC_UNKNOWN},
897         {NULL, ENC_UNKNOWN},
898 };
899
900 const gchar *procmime_get_encoding_str(EncodingType encoding)
901 {
902         struct EncodingTable *enc_table;
903         
904         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
905                 if (enc_table->enc_type == encoding)
906                         return enc_table->str;
907         }
908         return NULL;
909 }
910
911 /* --- NEW MIME STUFF --- */
912 struct TypeTable
913 {
914         gchar *str;
915         MimeMediaType type;
916 };
917
918 static struct TypeTable mime_type_table[] = {
919         {"text", MIMETYPE_TEXT},
920         {"image", MIMETYPE_IMAGE},
921         {"audio", MIMETYPE_AUDIO},
922         {"video", MIMETYPE_VIDEO},
923         {"application", MIMETYPE_APPLICATION},
924         {"message", MIMETYPE_MESSAGE},
925         {"multipart", MIMETYPE_MULTIPART},
926         {NULL, 0},
927 };
928
929 const gchar *procmime_get_type_str(MimeMediaType type)
930 {
931         struct TypeTable *type_table;
932         
933         for (type_table = mime_type_table; type_table->str != NULL; type_table++) {
934                 if (type_table->type == type)
935                         return type_table->str;
936         }
937         return NULL;
938 }
939
940 void procmime_parse_mimepart(MimeInfo *parent,
941                              gchar *content_type,
942                              gchar *content_encoding,
943                              gchar *content_description,
944                              gchar *content_id,
945                              const gchar *filename,
946                              guint offset,
947                              guint length);
948
949 void procmime_parse_message_rfc822(MimeInfo *mimeinfo)
950 {
951         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
952                                 {"Content-Transfer-Encoding:",
953                                                    NULL, FALSE},
954                                 {"Content-Description:",
955                                                    NULL, TRUE},
956                                 {"Content-ID:",
957                                                    NULL, TRUE},
958                                 {NULL,             NULL, FALSE}};
959         guint content_start, i;
960         FILE *fp;
961
962         if(mimeinfo->encoding_type != ENC_BINARY && 
963            mimeinfo->encoding_type != ENC_7BIT && 
964            mimeinfo->encoding_type != ENC_8BIT)
965                 procmime_decode_content(mimeinfo);
966
967         fp = fopen(mimeinfo->filename, "rb");
968         fseek(fp, mimeinfo->offset, SEEK_SET);
969         procheader_get_header_fields(fp, hentry);
970         content_start = ftell(fp);
971         fclose(fp);
972
973         procmime_parse_mimepart(mimeinfo,
974                                 hentry[0].body, hentry[1].body,
975                                 hentry[2].body, hentry[3].body, 
976                                 mimeinfo->filename, content_start,
977                                 mimeinfo->length - (content_start - mimeinfo->offset));
978         for (i = 0; i < 4; i++) {
979                 g_free(hentry[i].body);
980                 hentry[i].body = NULL;
981         }
982 }
983
984 void procmime_parse_multipart(MimeInfo *mimeinfo)
985 {
986         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
987                                 {"Content-Transfer-Encoding:",
988                                                    NULL, FALSE},
989                                 {"Content-Description:",
990                                                    NULL, TRUE},
991                                 {"Content-ID:",
992                                                    NULL, TRUE},
993                                 {NULL,             NULL, FALSE}};
994         gchar *p;
995         gchar *boundary;
996         gint boundary_len = 0, lastoffset = -1, i;
997         gchar buf[BUFFSIZE];
998         FILE *fp;
999
1000         boundary = g_hash_table_lookup(mimeinfo->parameters, "boundary");
1001         if(!boundary)
1002                 return;
1003         boundary_len = strlen(boundary);
1004
1005         if(mimeinfo->encoding_type != ENC_BINARY && 
1006            mimeinfo->encoding_type != ENC_7BIT && 
1007            mimeinfo->encoding_type != ENC_8BIT)
1008                 procmime_decode_content(mimeinfo);
1009
1010         fp = fopen(mimeinfo->filename, "rb");
1011         fseek(fp, mimeinfo->offset, SEEK_SET);
1012         while ((p = fgets(buf, sizeof(buf), fp)) != NULL) {
1013                 if (ftell(fp) > (mimeinfo->offset + mimeinfo->length))
1014                         break;
1015
1016                 if (IS_BOUNDARY(buf, boundary, boundary_len)) {
1017                         if(lastoffset != -1) {
1018                                 procmime_parse_mimepart(mimeinfo,
1019                                                         hentry[0].body, hentry[1].body,
1020                                                         hentry[2].body, hentry[3].body, 
1021                                                         mimeinfo->filename, lastoffset,
1022                                                         (ftell(fp) - strlen(buf)) - lastoffset);
1023                         }
1024                         
1025                         if (buf[2 + boundary_len]     == '-' &&
1026                             buf[2 + boundary_len + 1] == '-')
1027                                 break;
1028
1029                         for (i = 0; i < 4; i++) {
1030                                 g_free(hentry[i].body);
1031                                 hentry[i].body = NULL;
1032                         }
1033                         procheader_get_header_fields(fp, hentry);
1034                         lastoffset = ftell(fp);
1035                 }
1036         }
1037         fclose(fp);
1038 }
1039
1040 static void procmime_parse_content_type(const gchar *content_type, MimeInfo *mimeinfo)
1041 {
1042         gchar **content_type_parts;
1043         gchar **strarray;
1044         gchar *str;
1045         struct TypeTable *typetablearray;
1046         
1047         /* Split content type into parts and remove trailing
1048            and leading whitespaces from all strings */
1049         content_type_parts = g_strsplit(content_type, ";", 0);
1050         for (strarray = content_type_parts; *strarray != NULL; strarray++) {
1051                 g_strstrip(*strarray);
1052         }
1053
1054         /* Get mimeinfo->type and mimeinfo->subtype */
1055         mimeinfo->type = MIMETYPE_UNKNOWN;
1056         str = content_type_parts[0];
1057         for (typetablearray = mime_type_table; typetablearray->str != NULL; typetablearray++) {
1058                 if (g_strncasecmp(str, typetablearray->str, strlen(typetablearray->str)) == 0 &&
1059                     str[strlen(typetablearray->str)] == '/') {
1060                         mimeinfo->type = typetablearray->type;
1061                         mimeinfo->subtype = g_strdup(str + strlen(typetablearray->str) + 1);
1062                         break;
1063                 }
1064         }
1065
1066         /* Get mimeinfo->parmeters */
1067         for (strarray = &content_type_parts[1]; *strarray != NULL; strarray++) {
1068                 gchar **parameters_parts;
1069
1070                 parameters_parts = g_strsplit(*strarray, "=", 1);
1071                 if ((parameters_parts[0] != NULL) && (parameters_parts[1] != NULL)) {
1072                         g_strdown(parameters_parts[0]);
1073                         if(parameters_parts[1][0] == '"')
1074                                 extract_quote(parameters_parts[1], '"');
1075
1076                         g_hash_table_insert(mimeinfo->parameters,
1077                                             g_strdup(parameters_parts[0]),
1078                                             g_strdup(parameters_parts[1]));
1079                 }
1080                 g_strfreev(parameters_parts);
1081         }
1082
1083         g_strfreev(content_type_parts);
1084 }
1085
1086 static void procmime_parse_content_encoding(const gchar *content_encoding, MimeInfo *mimeinfo)
1087 {
1088         struct EncodingTable *enc_table;
1089         
1090         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1091                 if (g_strcasecmp(enc_table->str, content_encoding) == 0) {
1092                         mimeinfo->encoding_type = enc_table->enc_type;
1093                         return;
1094                 }
1095         }
1096         mimeinfo->encoding_type = ENC_UNKNOWN;
1097         return;
1098 }
1099
1100 void procmime_parse_mimepart(MimeInfo *parent,
1101                              gchar *content_type,
1102                              gchar *content_encoding,
1103                              gchar *content_description,
1104                              gchar *content_id,
1105                              const gchar *filename,
1106                              guint offset,
1107                              guint length)
1108 {
1109         MimeInfo *mimeinfo;
1110
1111         /* Create MimeInfo */
1112         mimeinfo = procmime_mimeinfo_new();
1113         if (parent != NULL)
1114                 g_node_append(parent->node, mimeinfo->node);
1115         mimeinfo->filename = g_strdup(filename);
1116         mimeinfo->offset = offset;
1117         mimeinfo->length = length;
1118
1119         if (content_type != NULL) {
1120                 procmime_parse_content_type(content_type, mimeinfo);
1121         } else {
1122                 mimeinfo->type = MIMETYPE_TEXT;
1123                 mimeinfo->subtype = g_strdup("plain");
1124                 g_hash_table_insert(mimeinfo->parameters, g_strdup("charset"), g_strdup("us-ascii"));
1125         }
1126
1127         if (content_encoding != NULL) {
1128                 procmime_parse_content_encoding(content_encoding, mimeinfo);
1129         } else {
1130                 mimeinfo->encoding_type = ENC_7BIT;
1131         }
1132
1133         if (content_description != NULL)
1134                 mimeinfo->description = g_strdup(content_description);
1135         else
1136                 mimeinfo->description = NULL;
1137
1138         if (content_id != NULL)
1139                 mimeinfo->id = g_strdup(content_id);
1140         else
1141                 mimeinfo->id = NULL;
1142
1143         /* Call parser for mime type */
1144         switch (mimeinfo->type) {
1145                 case MIMETYPE_MESSAGE:
1146                         if (g_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
1147                                 procmime_parse_message_rfc822(mimeinfo);
1148                         }
1149                         break;
1150                         
1151                 case MIMETYPE_MULTIPART:
1152                         procmime_parse_multipart(mimeinfo);
1153                         break;
1154                         
1155                 default:
1156                         break;
1157         }
1158 }
1159
1160 static gchar *typenames[] = {
1161     "text",
1162     "image",
1163     "audio",
1164     "video",
1165     "application",
1166     "message",
1167     "multipart",
1168     "unknown",
1169 };
1170
1171 static gboolean output_func(GNode *node, gpointer data)
1172 {
1173         guint i, depth;
1174         MimeInfo *mimeinfo = (MimeInfo *) node->data;
1175
1176         depth = g_node_depth(node);
1177         for(i = 0; i < depth; i++)
1178                 printf("    ");
1179         printf("%s/%s (offset:%d length:%d encoding: %d)\n", typenames[mimeinfo->type], mimeinfo->subtype, mimeinfo->offset, mimeinfo->length, mimeinfo->encoding_type);
1180
1181         return FALSE;
1182 }
1183
1184 static void output_mime_structure(MimeInfo *mimeinfo, int indent)
1185 {
1186         g_node_traverse(mimeinfo->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1, output_func, NULL);
1187 }
1188
1189 static MimeInfo *procmime_scan_file_with_offset(const gchar *filename, int offset)
1190 {
1191         MimeInfo *mimeinfo;
1192         struct stat buf;
1193
1194         stat(filename, &buf);
1195
1196         mimeinfo = procmime_mimeinfo_new();
1197         mimeinfo->encoding_type = ENC_BINARY;
1198         mimeinfo->type = MIMETYPE_MESSAGE;
1199         mimeinfo->subtype = g_strdup("rfc822");
1200         mimeinfo->filename = g_strdup(filename);
1201         mimeinfo->offset = offset;
1202         mimeinfo->length = buf.st_size - offset;
1203
1204         procmime_parse_message_rfc822(mimeinfo);
1205         output_mime_structure(mimeinfo, 0);
1206
1207         return mimeinfo;
1208 }
1209
1210 MimeInfo *procmime_scan_file(gchar *filename)
1211 {
1212         MimeInfo *mimeinfo;
1213
1214         g_return_val_if_fail(filename != NULL, NULL);
1215
1216         mimeinfo = procmime_scan_file_with_offset(filename, 0);
1217
1218         return mimeinfo;
1219 }
1220
1221 MimeInfo *procmime_scan_queue_file(gchar *filename)
1222 {
1223         FILE *fp;
1224         MimeInfo *mimeinfo;
1225         gchar buf[BUFFSIZE];
1226         gint offset = 0;
1227
1228         g_return_val_if_fail(filename != NULL, NULL);
1229
1230         /* Open file */
1231         if((fp = fopen(filename, "rb")) == NULL)
1232                 return NULL;
1233         /* Skip queue header */
1234         while (fgets(buf, sizeof(buf), fp) != NULL)
1235                 if (buf[0] == '\r' || buf[0] == '\n') break;
1236         offset = ftell(fp);
1237         fclose(fp);
1238
1239         mimeinfo = procmime_scan_file_with_offset(filename, offset);
1240
1241         return mimeinfo;
1242 }