textview_show_mime_part(): rewrite text hint
[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             msginfo->folder->stype != F_DRAFT)
200                 mimeinfo = procmime_scan_file(filename);
201         else
202                 mimeinfo = procmime_scan_queue_file(filename);
203         g_free(filename);
204
205         return mimeinfo;
206 }
207
208 enum
209 {
210         H_CONTENT_TRANSFER_ENCODING = 0,
211         H_CONTENT_TYPE              = 1,
212         H_CONTENT_DISPOSITION       = 2,
213         H_CONTENT_DESCRIPTION       = 3,
214         H_SUBJECT                   = 4
215 };
216
217 const gchar *procmime_mimeinfo_get_parameter(MimeInfo *mimeinfo, const gchar *name)
218 {
219         g_return_val_if_fail(mimeinfo != NULL, NULL);
220         g_return_val_if_fail(name != NULL, NULL);
221         
222         return g_hash_table_lookup(mimeinfo->parameters, name);
223 }
224
225 gboolean procmime_decode_content(MimeInfo *mimeinfo)
226 {
227         gchar buf[BUFFSIZE];
228         gint readend;
229         gchar *tmpfilename;
230         gchar *mimetmpdir;
231         FILE *outfp, *infp;
232         struct stat statbuf;
233
234         g_return_val_if_fail(mimeinfo != NULL, FALSE);
235
236         if(mimeinfo->encoding_type == ENC_BINARY)
237                 return TRUE;
238
239         infp = fopen(mimeinfo->filename, "rb");
240         if(!infp) {
241                 perror("fopen");
242                 return FALSE;
243         }
244         fseek(infp, mimeinfo->offset, SEEK_SET);
245
246         mimetmpdir = get_mime_tmp_dir();
247         outfp = get_tmpfile_in_dir(mimetmpdir, &tmpfilename);
248         if (!outfp) {
249                 perror("tmpfile");
250                 return FALSE;
251         }
252
253         readend = mimeinfo->offset + mimeinfo->length;
254
255         if (mimeinfo->encoding_type == ENC_QUOTED_PRINTABLE) {
256                 while ((ftell(infp) < readend) && (fgets(buf, sizeof(buf), infp) != NULL)) {
257                         gint len;
258                         len = qp_decode_line(buf);
259                         fwrite(buf, len, 1, outfp);
260                 }
261         } else if (mimeinfo->encoding_type == ENC_BASE64) {
262                 gchar outbuf[BUFFSIZE];
263                 gint len;
264                 Base64Decoder *decoder;
265
266                 decoder = base64_decoder_new();
267                 while ((ftell(infp) < readend) && (fgets(buf, sizeof(buf), infp) != NULL)) {
268                         len = base64_decoder_decode(decoder, buf, outbuf);
269                         if (len < 0) {
270                                 g_warning("Bad BASE64 content\n");
271                                 break;
272                         }
273                         fwrite(outbuf, sizeof(gchar), len, outfp);
274                 }
275                 base64_decoder_free(decoder);
276         } else if (mimeinfo->encoding_type == ENC_X_UUENCODE) {
277                 gchar outbuf[BUFFSIZE];
278                 gint len;
279                 gboolean flag = FALSE;
280
281                 while ((ftell(infp) < readend) && (fgets(buf, sizeof(buf), infp) != NULL)) {
282                         if(!flag && strncmp(buf,"begin ", 6)) continue;
283
284                         if (flag) {
285                                 len = fromuutobits(outbuf, buf);
286                                 if (len <= 0) {
287                                         if (len < 0) 
288                                                 g_warning("Bad UUENCODE content(%d)\n", len);
289                                         break;
290                                 }
291                                 fwrite(outbuf, sizeof(gchar), len, outfp);
292                         } else
293                                 flag = TRUE;
294                 }
295         } else {
296                 while ((ftell(infp) < readend) && (fgets(buf, sizeof(buf), infp) != NULL)) {
297                         fputs(buf, outfp);
298                 }
299         }
300
301         fclose(outfp);
302         fclose(infp);
303
304         stat(tmpfilename, &statbuf);
305         if(mimeinfo->tmpfile)
306                 unlink(mimeinfo->filename);
307         g_free(mimeinfo->filename);
308         mimeinfo->filename = tmpfilename;
309         mimeinfo->tmpfile = TRUE;
310         mimeinfo->offset = 0;
311         mimeinfo->length = statbuf.st_size;
312         mimeinfo->encoding_type = ENC_BINARY;
313
314         return TRUE;
315 }
316
317 gint procmime_get_part(const gchar *outfile, MimeInfo *mimeinfo)
318 {
319         FILE *infp, *outfp;
320         gchar buf[BUFFSIZE];
321         gint restlength, readlength;
322
323         g_return_val_if_fail(outfile != NULL, -1);
324         g_return_val_if_fail(mimeinfo != NULL, -1);
325
326         if(mimeinfo->encoding_type != ENC_BINARY && !procmime_decode_content(mimeinfo))
327                 return -1;
328
329         if ((infp = fopen(mimeinfo->filename, "rb")) == NULL) {
330                 FILE_OP_ERROR(mimeinfo->filename, "fopen");
331                 return -1;
332         }
333         if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
334                 FILE_OP_ERROR(mimeinfo->filename, "fseek");
335                 fclose(infp);
336                 return -1;
337         }
338         if ((outfp = fopen(outfile, "wb")) == NULL) {
339                 FILE_OP_ERROR(outfile, "fopen");
340                 fclose(infp);
341                 return -1;
342         }
343
344         restlength = mimeinfo->length;
345
346         while ((restlength > 0) && ((readlength = fread(buf, 1, restlength > BUFFSIZE ? BUFFSIZE : restlength, infp)) > 0)) {
347                 fwrite(buf, 1, readlength, outfp);
348                 restlength -= readlength;
349         }
350
351         fclose(infp);
352         if (fclose(outfp) == EOF) {
353                 FILE_OP_ERROR(outfile, "fclose");
354                 unlink(outfile);
355                 return -1;
356         }
357
358         return 0;
359 }
360
361 struct ContentRenderer {
362         char * content_type;
363         char * renderer;
364 };
365
366 static GList * renderer_list = NULL;
367
368 static struct ContentRenderer *
369 content_renderer_new(char * content_type, char * renderer)
370 {
371         struct ContentRenderer * cr;
372
373         cr = g_new(struct ContentRenderer, 1);
374         if (cr == NULL)
375                 return NULL;
376
377         cr->content_type = g_strdup(content_type);
378         cr->renderer = g_strdup(renderer);
379
380         return cr;
381 }
382
383 static void content_renderer_free(struct ContentRenderer * cr)
384 {
385         g_free(cr->content_type);
386         g_free(cr->renderer);
387         g_free(cr);
388 }
389
390 void renderer_read_config(void)
391 {
392         gchar buf[BUFFSIZE];
393         FILE * f;
394         gchar * rcpath;
395
396         g_list_foreach(renderer_list, (GFunc) content_renderer_free, NULL);
397         renderer_list = NULL;
398
399         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, RENDERER_RC, NULL);
400         f = fopen(rcpath, "rb");
401         g_free(rcpath);
402         
403         if (f == NULL)
404                 return;
405
406         while (fgets(buf, BUFFSIZE, f)) {
407                 char * p;
408                 struct ContentRenderer * cr;
409
410                 strretchomp(buf);
411                 p = strchr(buf, ' ');
412                 if (p == NULL)
413                         continue;
414                 * p = 0;
415
416                 cr = content_renderer_new(buf, p + 1);
417                 if (cr == NULL)
418                         continue;
419
420                 renderer_list = g_list_append(renderer_list, cr);
421         }
422
423         fclose(f);
424 }
425
426 void renderer_write_config(void)
427 {
428         gchar * rcpath;
429         PrefFile *pfile;
430         GList * cur;
431
432         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, RENDERER_RC, NULL);
433         
434         if ((pfile = prefs_write_open(rcpath)) == NULL) {
435                 g_warning("failed to write configuration to file\n");
436                 g_free(rcpath);
437                 return;
438         }
439
440         g_free(rcpath);
441
442         for(cur = renderer_list ; cur != NULL ; cur = cur->next) {
443                 struct ContentRenderer * renderer;
444                 renderer = cur->data;
445                 fprintf(pfile->fp, "%s %s\n", renderer->content_type,
446                         renderer->renderer);
447         }
448
449         if (prefs_file_close(pfile) < 0) {
450                 g_warning("failed to write configuration to file\n");
451                 return;
452         }
453 }
454
455 FILE *procmime_get_text_content(MimeInfo *mimeinfo)
456 {
457         FILE *tmpfp, *outfp;
458         const gchar *src_codeset;
459         gboolean conv_fail = FALSE;
460         gchar buf[BUFFSIZE];
461         gchar *str;
462         struct ContentRenderer * renderer;
463         GList * cur;
464         gchar *tmpfile, *content_type;
465     
466         g_return_val_if_fail(mimeinfo != NULL, NULL);
467
468         if (!procmime_decode_content(mimeinfo))
469                 return NULL;
470
471         tmpfile = procmime_get_tmp_file_name(mimeinfo);
472         if (tmpfile == NULL)
473                 return NULL;
474
475         if (procmime_get_part(tmpfile, mimeinfo) < 0) {
476                 g_free(tmpfile);
477                 return NULL;
478         }
479
480         tmpfp = fopen(tmpfile, "rb");
481         if (tmpfp == NULL) {
482                 g_free(tmpfile);
483                 return NULL;
484         }
485
486         if ((outfp = my_tmpfile()) == NULL) {
487                 perror("tmpfile");
488                 fclose(tmpfp);
489                 g_free(tmpfile);
490                 return NULL;
491         }
492
493         src_codeset = prefs_common.force_charset
494                 ? prefs_common.force_charset : 
495                 procmime_mimeinfo_get_parameter(mimeinfo, "charset");
496
497         renderer = NULL;
498
499         content_type = g_strdup_printf("%s/%s", procmime_get_type_str(mimeinfo->type),
500                 mimeinfo->subtype);
501         for(cur = renderer_list ; cur != NULL ; cur = cur->next) {
502                 struct ContentRenderer * cr;
503
504                 cr = cur->data;
505                 if (g_strcasecmp(cr->content_type, content_type) == 0) {
506                         renderer = cr;
507                         break;
508                 }
509         }
510         g_free(content_type);
511
512         if (renderer != NULL) {
513                 FILE * p;
514                 int oldout;
515                 
516                 oldout = dup(1);
517                 
518                 dup2(fileno(outfp), 1);
519                 
520                 p = popen(renderer->renderer, "w");
521                 if (p != NULL) {
522                         size_t count;
523                         
524                         while ((count =
525                                 fread(buf, sizeof(char), sizeof(buf),
526                                       tmpfp)) > 0)
527                                 fwrite(buf, sizeof(char), count, p);
528                         pclose(p);
529                 }
530                 
531                 dup2(oldout, 1);
532         } else if (mimeinfo->type == MIMETYPE_TEXT && !g_strcasecmp(mimeinfo->subtype, "html")) {
533                 HTMLParser *parser;
534                 CodeConverter *conv;
535
536                 conv = conv_code_converter_new(src_codeset);
537                 parser = html_parser_new(tmpfp, conv);
538                 while ((str = html_parse(parser)) != NULL) {
539                         fputs(str, outfp);
540                 }
541                 html_parser_destroy(parser);
542                 conv_code_converter_destroy(conv);
543         } else if (mimeinfo->type == MIMETYPE_TEXT && !g_strcasecmp(mimeinfo->subtype, "enriched")) {
544                 ERTFParser *parser;
545                 CodeConverter *conv;
546
547                 conv = conv_code_converter_new(src_codeset);
548                 parser = ertf_parser_new(tmpfp, conv);
549                 while ((str = ertf_parse(parser)) != NULL) {
550                         fputs(str, outfp);
551                 }
552                 ertf_parser_destroy(parser);
553                 conv_code_converter_destroy(conv);
554         } else if (mimeinfo->type == MIMETYPE_TEXT) {
555                 while (fgets(buf, sizeof(buf), tmpfp) != NULL) {
556                         str = conv_codeset_strdup(buf, src_codeset, NULL);
557                         if (str) {
558                                 fputs(str, outfp);
559                                 g_free(str);
560                         } else {
561                                 conv_fail = TRUE;
562                                 fputs(buf, outfp);
563                         }
564                 }
565         }
566
567         if (conv_fail)
568                 g_warning("procmime_get_text_content(): Code conversion failed.\n");
569
570         fclose(tmpfp);
571         rewind(outfp);
572         unlink(tmpfile);
573         g_free(tmpfile);
574
575         return outfp;
576 }
577
578 /* search the first text part of (multipart) MIME message,
579    decode, convert it and output to outfp. */
580 FILE *procmime_get_first_text_content(MsgInfo *msginfo)
581 {
582         FILE *outfp = NULL;
583         MimeInfo *mimeinfo, *partinfo;
584
585         g_return_val_if_fail(msginfo != NULL, NULL);
586
587         mimeinfo = procmime_scan_message(msginfo);
588         if (!mimeinfo) return NULL;
589
590         partinfo = mimeinfo;
591         while (partinfo && partinfo->type != MIMETYPE_TEXT)
592                 partinfo = procmime_mimeinfo_next(partinfo);
593
594         if (partinfo)
595                 outfp = procmime_get_text_content(partinfo);
596
597         procmime_mimeinfo_free_all(mimeinfo);
598
599         return outfp;
600 }
601
602 gboolean procmime_find_string_part(MimeInfo *mimeinfo, const gchar *filename,
603                                    const gchar *str, gboolean case_sens)
604 {
605         FILE *outfp;
606         gchar buf[BUFFSIZE];
607         gchar *(* StrFindFunc) (const gchar *haystack, const gchar *needle);
608
609         g_return_val_if_fail(mimeinfo != NULL, FALSE);
610         g_return_val_if_fail(mimeinfo->type == MIMETYPE_TEXT, FALSE);
611         g_return_val_if_fail(str != NULL, FALSE);
612
613         outfp = procmime_get_text_content(mimeinfo);
614
615         if (!outfp)
616                 return FALSE;
617
618         if (case_sens)
619                 StrFindFunc = strstr;
620         else
621                 StrFindFunc = strcasestr;
622
623         while (fgets(buf, sizeof(buf), outfp) != NULL) {
624                 if (StrFindFunc(buf, str) != NULL) {
625                         fclose(outfp);
626                         return TRUE;
627                 }
628         }
629
630         fclose(outfp);
631
632         return FALSE;
633 }
634
635 gboolean procmime_find_string(MsgInfo *msginfo, const gchar *str,
636                               gboolean case_sens)
637 {
638         MimeInfo *mimeinfo;
639         MimeInfo *partinfo;
640         gchar *filename;
641         gboolean found = FALSE;
642
643         g_return_val_if_fail(msginfo != NULL, FALSE);
644         g_return_val_if_fail(str != NULL, FALSE);
645
646         filename = procmsg_get_message_file(msginfo);
647         if (!filename) return FALSE;
648         mimeinfo = procmime_scan_message(msginfo);
649
650         for (partinfo = mimeinfo; partinfo != NULL;
651              partinfo = procmime_mimeinfo_next(partinfo)) {
652                 if (partinfo->type == MIMETYPE_TEXT) {
653                         if (procmime_find_string_part
654                                 (partinfo, filename, str, case_sens) == TRUE) {
655                                 found = TRUE;
656                                 break;
657                         }
658                 }
659         }
660
661         procmime_mimeinfo_free_all(mimeinfo);
662         g_free(filename);
663
664         return found;
665 }
666
667 gchar *procmime_get_tmp_file_name(MimeInfo *mimeinfo)
668 {
669         static guint32 id = 0;
670         gchar *base;
671         gchar *filename;
672         gchar f_prefix[10];
673
674         g_return_val_if_fail(mimeinfo != NULL, NULL);
675
676         g_snprintf(f_prefix, sizeof(f_prefix), "%08x.", id++);
677
678         if ((mimeinfo->type == MIMETYPE_TEXT) && !g_strcasecmp(mimeinfo->subtype, "html"))
679                 base = "mimetmp.html";
680         else {
681                 base = 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         for (i = 0; i < 4; i++) {
1038                 g_free(hentry[i].body);
1039                 hentry[i].body = NULL;
1040         }
1041         fclose(fp);
1042 }
1043
1044 static void procmime_parse_content_type(const gchar *content_type, MimeInfo *mimeinfo)
1045 {
1046         gchar **content_type_parts;
1047         gchar **strarray;
1048         gchar *str;
1049         struct TypeTable *typetablearray;
1050         
1051         g_return_if_fail(content_type != NULL);
1052         g_return_if_fail(mimeinfo != NULL);
1053         
1054         /* Split content type into parts and remove trailing
1055            and leading whitespaces from all strings */
1056         content_type_parts = g_strsplit(content_type, ";", 0);
1057         for (strarray = content_type_parts; *strarray != NULL; strarray++) {
1058                 g_strstrip(*strarray);
1059         }
1060
1061         /* Get mimeinfo->type and mimeinfo->subtype */
1062         mimeinfo->type = MIMETYPE_UNKNOWN;
1063         str = content_type_parts[0];
1064         if (str == NULL) {
1065                 g_strfreev(content_type_parts);
1066                 return;
1067         }
1068         for (typetablearray = mime_type_table; typetablearray->str != NULL; typetablearray++) {
1069                 if (g_strncasecmp(str, typetablearray->str, strlen(typetablearray->str)) == 0 &&
1070                     str[strlen(typetablearray->str)] == '/') {
1071                         mimeinfo->type = typetablearray->type;
1072                         mimeinfo->subtype = g_strdup(str + strlen(typetablearray->str) + 1);
1073                         break;
1074                 }
1075         }
1076
1077         /* Get mimeinfo->parmeters */
1078         for (strarray = &content_type_parts[1]; *strarray != NULL; strarray++) {
1079                 gchar **parameters_parts;
1080
1081                 parameters_parts = g_strsplit(*strarray, "=", 1);
1082                 if ((parameters_parts[0] != NULL) && (parameters_parts[1] != NULL)) {
1083                         g_strdown(parameters_parts[0]);
1084                         if(parameters_parts[1][0] == '"')
1085                                 extract_quote(parameters_parts[1], '"');
1086
1087                         g_hash_table_insert(mimeinfo->parameters,
1088                                             g_strdup(parameters_parts[0]),
1089                                             g_strdup(parameters_parts[1]));
1090                 }
1091                 g_strfreev(parameters_parts);
1092         }
1093
1094         g_strfreev(content_type_parts);
1095 }
1096
1097 static void procmime_parse_content_encoding(const gchar *content_encoding, MimeInfo *mimeinfo)
1098 {
1099         struct EncodingTable *enc_table;
1100         
1101         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1102                 if (g_strcasecmp(enc_table->str, content_encoding) == 0) {
1103                         mimeinfo->encoding_type = enc_table->enc_type;
1104                         return;
1105                 }
1106         }
1107         mimeinfo->encoding_type = ENC_UNKNOWN;
1108         return;
1109 }
1110
1111 void procmime_parse_mimepart(MimeInfo *parent,
1112                              gchar *content_type,
1113                              gchar *content_encoding,
1114                              gchar *content_description,
1115                              gchar *content_id,
1116                              const gchar *filename,
1117                              guint offset,
1118                              guint length)
1119 {
1120         MimeInfo *mimeinfo;
1121
1122         /* Create MimeInfo */
1123         mimeinfo = procmime_mimeinfo_new();
1124         if (parent != NULL)
1125                 g_node_append(parent->node, mimeinfo->node);
1126         mimeinfo->filename = g_strdup(filename);
1127         mimeinfo->offset = offset;
1128         mimeinfo->length = length;
1129
1130         if (content_type != NULL) {
1131                 procmime_parse_content_type(content_type, mimeinfo);
1132         } else {
1133                 mimeinfo->type = MIMETYPE_TEXT;
1134                 mimeinfo->subtype = g_strdup("plain");
1135                 g_hash_table_insert(mimeinfo->parameters, g_strdup("charset"), g_strdup("us-ascii"));
1136         }
1137
1138         if (content_encoding != NULL) {
1139                 procmime_parse_content_encoding(content_encoding, mimeinfo);
1140         } else {
1141                 mimeinfo->encoding_type = ENC_7BIT;
1142         }
1143
1144         if (content_description != NULL)
1145                 mimeinfo->description = g_strdup(content_description);
1146         else
1147                 mimeinfo->description = NULL;
1148
1149         if (content_id != NULL)
1150                 mimeinfo->id = g_strdup(content_id);
1151         else
1152                 mimeinfo->id = NULL;
1153
1154         /* Call parser for mime type */
1155         switch (mimeinfo->type) {
1156                 case MIMETYPE_MESSAGE:
1157                         if (g_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
1158                                 procmime_parse_message_rfc822(mimeinfo);
1159                         }
1160                         break;
1161                         
1162                 case MIMETYPE_MULTIPART:
1163                         procmime_parse_multipart(mimeinfo);
1164                         break;
1165                         
1166                 default:
1167                         break;
1168         }
1169 }
1170
1171 static gchar *typenames[] = {
1172     "text",
1173     "image",
1174     "audio",
1175     "video",
1176     "application",
1177     "message",
1178     "multipart",
1179     "unknown",
1180 };
1181
1182 static gboolean output_func(GNode *node, gpointer data)
1183 {
1184         guint i, depth;
1185         MimeInfo *mimeinfo = (MimeInfo *) node->data;
1186
1187         depth = g_node_depth(node);
1188         for(i = 0; i < depth; i++)
1189                 printf("    ");
1190         printf("%s/%s (offset:%d length:%d encoding: %d)\n", typenames[mimeinfo->type], mimeinfo->subtype, mimeinfo->offset, mimeinfo->length, mimeinfo->encoding_type);
1191
1192         return FALSE;
1193 }
1194
1195 static void output_mime_structure(MimeInfo *mimeinfo, int indent)
1196 {
1197         g_node_traverse(mimeinfo->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1, output_func, NULL);
1198 }
1199
1200 static MimeInfo *procmime_scan_file_with_offset(const gchar *filename, int offset)
1201 {
1202         MimeInfo *mimeinfo;
1203         struct stat buf;
1204
1205         stat(filename, &buf);
1206
1207         mimeinfo = procmime_mimeinfo_new();
1208         mimeinfo->encoding_type = ENC_BINARY;
1209         mimeinfo->type = MIMETYPE_MESSAGE;
1210         mimeinfo->subtype = g_strdup("rfc822");
1211         mimeinfo->filename = g_strdup(filename);
1212         mimeinfo->offset = offset;
1213         mimeinfo->length = buf.st_size - offset;
1214
1215         procmime_parse_message_rfc822(mimeinfo);
1216         output_mime_structure(mimeinfo, 0);
1217
1218         return mimeinfo;
1219 }
1220
1221 MimeInfo *procmime_scan_file(gchar *filename)
1222 {
1223         MimeInfo *mimeinfo;
1224
1225         g_return_val_if_fail(filename != NULL, NULL);
1226
1227         mimeinfo = procmime_scan_file_with_offset(filename, 0);
1228
1229         return mimeinfo;
1230 }
1231
1232 MimeInfo *procmime_scan_queue_file(gchar *filename)
1233 {
1234         FILE *fp;
1235         MimeInfo *mimeinfo;
1236         gchar buf[BUFFSIZE];
1237         gint offset = 0;
1238
1239         g_return_val_if_fail(filename != NULL, NULL);
1240
1241         /* Open file */
1242         if((fp = fopen(filename, "rb")) == NULL)
1243                 return NULL;
1244         /* Skip queue header */
1245         while (fgets(buf, sizeof(buf), fp) != NULL)
1246                 if (buf[0] == '\r' || buf[0] == '\n') break;
1247         offset = ftell(fp);
1248         fclose(fp);
1249
1250         mimeinfo = procmime_scan_file_with_offset(filename, offset);
1251
1252         return mimeinfo;
1253 }