bc7800ac25e87b340a86e87615bd77253076b7ae
[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->type          = MIMETYPE_UNKNOWN;
59         mimeinfo->encoding_type = ENC_UNKNOWN;
60         mimeinfo->disposition   = DISPOSITIONTYPE_UNKNOWN;
61
62         mimeinfo->parameters = g_hash_table_new(g_str_hash, g_str_equal);
63         mimeinfo->node       = g_node_new(mimeinfo);
64         
65         return mimeinfo;
66 }
67
68 static gboolean procmime_mimeinfo_parameters_destroy(gpointer key, gpointer value, gpointer user_data)
69 {
70         g_free(key);
71         g_free(value);
72         
73         return TRUE;
74 }
75
76 static gboolean free_func(GNode *node, gpointer data)
77 {
78         MimeInfo *mimeinfo = (MimeInfo *) node->data;
79
80         if (mimeinfo->tmpfile)
81                 unlink(mimeinfo->filename);
82         g_free(mimeinfo->filename);
83
84         g_free(mimeinfo->subtype);
85         g_free(mimeinfo->description);
86         g_free(mimeinfo->id);
87
88         g_hash_table_foreach_remove(mimeinfo->parameters, procmime_mimeinfo_parameters_destroy, NULL);
89         g_hash_table_destroy(mimeinfo->parameters);
90
91         if (mimeinfo->privacy)
92                 privacy_free_privacydata(mimeinfo->privacy);
93
94         g_free(mimeinfo);
95
96         return FALSE;
97 }
98
99 void procmime_mimeinfo_free_all(MimeInfo *mimeinfo)
100 {
101         GNode *node;
102
103         g_return_if_fail(mimeinfo);
104
105         node = mimeinfo->node;
106         g_node_traverse(node, G_IN_ORDER, G_TRAVERSE_ALL, -1, free_func, NULL);
107
108         g_node_destroy(node);
109 }
110
111 #if 0 /* UNUSED */
112 MimeInfo *procmime_mimeinfo_insert(MimeInfo *parent, MimeInfo *mimeinfo)
113 {
114         MimeInfo *child = parent->children;
115
116         if (!child)
117                 parent->children = mimeinfo;
118         else {
119                 while (child->next != NULL)
120                         child = child->next;
121
122                 child->next = mimeinfo;
123         }
124
125         mimeinfo->parent = parent;
126         mimeinfo->level = parent->level + 1;
127
128         return mimeinfo;
129 }
130
131 void procmime_mimeinfo_replace(MimeInfo *old, MimeInfo *new)
132 {
133         MimeInfo *parent = old->parent;
134         MimeInfo *child;
135
136         g_return_if_fail(parent != NULL);
137         g_return_if_fail(new->next == NULL);
138
139         for (child = parent->children; child && child != old;
140              child = child->next)
141                 ;
142         if (!child) {
143                 g_warning("oops: parent can't find it's own child");
144                 return;
145         }
146         procmime_mimeinfo_free_all(old);
147
148         if (child == parent->children) {
149                 new->next = parent->children->next;
150                 parent->children = new;
151         } else {
152                 new->next = child->next;
153                 child = new;
154         }
155 }
156 #endif
157
158 MimeInfo *procmime_mimeinfo_parent(MimeInfo *mimeinfo)
159 {
160         g_return_val_if_fail(mimeinfo != NULL, NULL);
161         g_return_val_if_fail(mimeinfo->node != 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 = procmime_get_content_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 #warning FIXME_GTK2 HTML/RTF not yet utf8
533 /* CodeConverter seems to have no effect here */
534         } else if (mimeinfo->type == MIMETYPE_TEXT && !g_strcasecmp(mimeinfo->subtype, "html")) {
535                 HTMLParser *parser;
536                 CodeConverter *conv;
537
538                 conv = conv_code_converter_new(src_codeset);
539                 parser = html_parser_new(tmpfp, conv);
540                 while ((str = html_parse(parser)) != NULL) {
541                         fputs(str, outfp);
542                 }
543                 html_parser_destroy(parser);
544                 conv_code_converter_destroy(conv);
545         } else if (mimeinfo->type == MIMETYPE_TEXT && !g_strcasecmp(mimeinfo->subtype, "enriched")) {
546                 ERTFParser *parser;
547                 CodeConverter *conv;
548
549                 conv = conv_code_converter_new(src_codeset);
550                 parser = ertf_parser_new(tmpfp, conv);
551                 while ((str = ertf_parse(parser)) != NULL) {
552                         fputs(str, outfp);
553                 }
554                 ertf_parser_destroy(parser);
555                 conv_code_converter_destroy(conv);
556         } else if (mimeinfo->type == MIMETYPE_TEXT) {
557                 while (fgets(buf, sizeof(buf), tmpfp) != NULL) {
558                         str = conv_codeset_strdup(buf, src_codeset, CS_UTF_8);
559                         if (str) {
560                                 fputs(str, outfp);
561                                 g_free(str);
562                         } else {
563                                 conv_fail = TRUE;
564                                 fputs(buf, outfp);
565                         }
566                 }
567         }
568
569         if (conv_fail)
570                 g_warning("procmime_get_text_content(): Code conversion failed.\n");
571
572         fclose(tmpfp);
573         rewind(outfp);
574         unlink(tmpfile);
575         g_free(tmpfile);
576
577         return outfp;
578 }
579
580 /* search the first text part of (multipart) MIME message,
581    decode, convert it and output to outfp. */
582 FILE *procmime_get_first_text_content(MsgInfo *msginfo)
583 {
584         FILE *outfp = NULL;
585         MimeInfo *mimeinfo, *partinfo;
586
587         g_return_val_if_fail(msginfo != NULL, NULL);
588
589         mimeinfo = procmime_scan_message(msginfo);
590         if (!mimeinfo) return NULL;
591
592         partinfo = mimeinfo;
593         while (partinfo && partinfo->type != MIMETYPE_TEXT)
594                 partinfo = procmime_mimeinfo_next(partinfo);
595
596         if (partinfo)
597                 outfp = procmime_get_text_content(partinfo);
598
599         procmime_mimeinfo_free_all(mimeinfo);
600
601         return outfp;
602 }
603
604 gboolean procmime_find_string_part(MimeInfo *mimeinfo, const gchar *filename,
605                                    const gchar *str, gboolean case_sens)
606 {
607         FILE *outfp;
608         gchar buf[BUFFSIZE];
609         gchar *(* StrFindFunc) (const gchar *haystack, const gchar *needle);
610
611         g_return_val_if_fail(mimeinfo != NULL, FALSE);
612         g_return_val_if_fail(mimeinfo->type == MIMETYPE_TEXT, FALSE);
613         g_return_val_if_fail(str != NULL, FALSE);
614
615         outfp = procmime_get_text_content(mimeinfo);
616
617         if (!outfp)
618                 return FALSE;
619
620         if (case_sens)
621                 StrFindFunc = strstr;
622         else
623                 StrFindFunc = strcasestr;
624
625         while (fgets(buf, sizeof(buf), outfp) != NULL) {
626                 if (StrFindFunc(buf, str) != NULL) {
627                         fclose(outfp);
628                         return TRUE;
629                 }
630         }
631
632         fclose(outfp);
633
634         return FALSE;
635 }
636
637 gboolean procmime_find_string(MsgInfo *msginfo, const gchar *str,
638                               gboolean case_sens)
639 {
640         MimeInfo *mimeinfo;
641         MimeInfo *partinfo;
642         gchar *filename;
643         gboolean found = FALSE;
644
645         g_return_val_if_fail(msginfo != NULL, FALSE);
646         g_return_val_if_fail(str != NULL, FALSE);
647
648         filename = procmsg_get_message_file(msginfo);
649         if (!filename) return FALSE;
650         mimeinfo = procmime_scan_message(msginfo);
651
652         for (partinfo = mimeinfo; partinfo != NULL;
653              partinfo = procmime_mimeinfo_next(partinfo)) {
654                 if (partinfo->type == MIMETYPE_TEXT) {
655                         if (procmime_find_string_part
656                                 (partinfo, filename, str, case_sens) == TRUE) {
657                                 found = TRUE;
658                                 break;
659                         }
660                 }
661         }
662
663         procmime_mimeinfo_free_all(mimeinfo);
664         g_free(filename);
665
666         return found;
667 }
668
669 gchar *procmime_get_tmp_file_name(MimeInfo *mimeinfo)
670 {
671         static guint32 id = 0;
672         const gchar *base;
673         gchar *filename;
674         gchar f_prefix[10];
675
676         g_return_val_if_fail(mimeinfo != NULL, NULL);
677
678         g_snprintf(f_prefix, sizeof(f_prefix), "%08x.", id++);
679
680         if ((mimeinfo->type == MIMETYPE_TEXT) && !g_strcasecmp(mimeinfo->subtype, "html"))
681                 base = "mimetmp.html";
682         else {
683                 const gchar *basetmp;
684
685                 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
686                 if (basetmp == NULL)
687                         basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
688                 if (basetmp == NULL)
689                         basetmp = "mimetmp";
690                 base = g_basename(basetmp);
691                 if (*base == '\0') base = "mimetmp";
692                 Xstrdup_a(base, base, return NULL);
693                 subst_for_shellsafe_filename(base);
694         }
695
696         filename = g_strconcat(get_mime_tmp_dir(), G_DIR_SEPARATOR_S,
697                                f_prefix, base, NULL);
698
699         return filename;
700 }
701
702 static GList *mime_type_list = NULL;
703
704 gchar *procmime_get_mime_type(const gchar *filename)
705 {
706         static GHashTable *mime_type_table = NULL;
707         MimeType *mime_type;
708         const gchar *p;
709         gchar *ext;
710
711         if (!mime_type_table) {
712                 mime_type_table = procmime_get_mime_type_table();
713                 if (!mime_type_table) return NULL;
714         }
715
716         filename = g_basename(filename);
717         p = strrchr(filename, '.');
718         if (!p) return NULL;
719
720         Xstrdup_a(ext, p + 1, return NULL);
721         g_strdown(ext);
722         mime_type = g_hash_table_lookup(mime_type_table, ext);
723         if (mime_type) {
724                 gchar *str;
725
726                 str = g_strconcat(mime_type->type, "/", mime_type->sub_type,
727                                   NULL);
728                 return str;
729         }
730
731         return NULL;
732 }
733
734 static guint procmime_str_hash(gconstpointer gptr)
735 {
736         guint hash_result = 0;
737         const char *str;
738
739         for (str = gptr; str && *str; str++) {
740                 if (isupper(*str)) hash_result += (*str + ' ');
741                 else hash_result += *str;
742         }
743
744         return hash_result;
745 }
746
747 static gint procmime_str_equal(gconstpointer gptr1, gconstpointer gptr2)
748 {
749         const char *str1 = gptr1;
750         const char *str2 = gptr2;
751
752         return !strcasecmp(str1, str2);
753 }
754
755 static GHashTable *procmime_get_mime_type_table(void)
756 {
757         GHashTable *table = NULL;
758         GList *cur;
759         MimeType *mime_type;
760         gchar **exts;
761
762         if (!mime_type_list) {
763                 mime_type_list = procmime_get_mime_type_list();
764                 if (!mime_type_list) return NULL;
765         }
766
767         table = g_hash_table_new(procmime_str_hash, procmime_str_equal);
768
769         for (cur = mime_type_list; cur != NULL; cur = cur->next) {
770                 gint i;
771                 gchar *key;
772
773                 mime_type = (MimeType *)cur->data;
774
775                 if (!mime_type->extension) continue;
776
777                 exts = g_strsplit(mime_type->extension, " ", 16);
778                 for (i = 0; exts[i] != NULL; i++) {
779                         /* make the key case insensitive */
780                         g_strdown(exts[i]);
781                         /* use previously dup'd key on overwriting */
782                         if (g_hash_table_lookup(table, exts[i]))
783                                 key = exts[i];
784                         else
785                                 key = g_strdup(exts[i]);
786                         g_hash_table_insert(table, key, mime_type);
787                 }
788                 g_strfreev(exts);
789         }
790
791         return table;
792 }
793
794 GList *procmime_get_mime_type_list(void)
795 {
796         GList *list = NULL;
797         FILE *fp;
798         gchar buf[BUFFSIZE];
799         guchar *p;
800         gchar *delim;
801         MimeType *mime_type;
802
803         if (mime_type_list) 
804                 return mime_type_list;
805
806         if ((fp = fopen("/etc/mime.types", "rb")) == NULL) {
807                 if ((fp = fopen(SYSCONFDIR "/mime.types", "rb")) == NULL) {
808                         FILE_OP_ERROR(SYSCONFDIR "/mime.types", "fopen");
809                         return NULL;
810                 }
811         }
812
813         while (fgets(buf, sizeof(buf), fp) != NULL) {
814                 p = strchr(buf, '#');
815                 if (p) *p = '\0';
816                 g_strstrip(buf);
817
818                 p = buf;
819                 while (*p && !isspace(*p)) p++;
820                 if (*p) {
821                         *p = '\0';
822                         p++;
823                 }
824                 delim = strchr(buf, '/');
825                 if (delim == NULL) continue;
826                 *delim = '\0';
827
828                 mime_type = g_new(MimeType, 1);
829                 mime_type->type = g_strdup(buf);
830                 mime_type->sub_type = g_strdup(delim + 1);
831
832                 while (*p && isspace(*p)) p++;
833                 if (*p)
834                         mime_type->extension = g_strdup(p);
835                 else
836                         mime_type->extension = NULL;
837
838                 list = g_list_append(list, mime_type);
839         }
840
841         fclose(fp);
842
843         if (!list)
844                 g_warning("Can't read mime.types\n");
845
846         return list;
847 }
848
849 EncodingType procmime_get_encoding_for_charset(const gchar *charset)
850 {
851         if (!charset)
852                 return ENC_8BIT;
853         else if (!strncasecmp(charset, "ISO-2022-", 9) ||
854                  !strcasecmp(charset, "US-ASCII"))
855                 return ENC_7BIT;
856         else if (!strcasecmp(charset, "ISO-8859-5") ||
857                  !strncasecmp(charset, "KOI8-", 5) ||
858                  !strcasecmp(charset, "Windows-1251"))
859                 return ENC_8BIT;
860         else if (!strncasecmp(charset, "ISO-8859-", 9))
861                 return ENC_QUOTED_PRINTABLE;
862         else
863                 return ENC_8BIT;
864 }
865
866 EncodingType procmime_get_encoding_for_file(const gchar *file)
867 {
868         FILE *fp;
869         guchar buf[BUFSIZ];
870         size_t len;
871
872         if ((fp = fopen(file, "rb")) == NULL) {
873                 FILE_OP_ERROR(file, "fopen");
874                 return ENC_UNKNOWN;
875         }
876
877         while ((len = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
878                 guchar *p;
879                 gint i;
880
881                 for (p = buf, i = 0; i < len; p++, i++) {
882                         if (*p & 0x80) {
883                                 fclose(fp);
884                                 return ENC_BASE64;
885                         }
886                 }
887         }
888
889         fclose(fp);
890         return ENC_7BIT;
891 }
892
893 struct EncodingTable 
894 {
895         gchar *str;
896         EncodingType enc_type;
897 };
898
899 struct EncodingTable encoding_table[] = {
900         {"7bit", ENC_7BIT},
901         {"8bit", ENC_8BIT},
902         {"binary", ENC_BINARY},
903         {"quoted-printable", ENC_QUOTED_PRINTABLE},
904         {"base64", ENC_BASE64},
905         {"x-uuencode", ENC_UNKNOWN},
906         {NULL, ENC_UNKNOWN},
907 };
908
909 const gchar *procmime_get_encoding_str(EncodingType encoding)
910 {
911         struct EncodingTable *enc_table;
912         
913         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
914                 if (enc_table->enc_type == encoding)
915                         return enc_table->str;
916         }
917         return NULL;
918 }
919
920 /* --- NEW MIME STUFF --- */
921 struct TypeTable
922 {
923         gchar *str;
924         MimeMediaType type;
925 };
926
927 static struct TypeTable mime_type_table[] = {
928         {"text", MIMETYPE_TEXT},
929         {"image", MIMETYPE_IMAGE},
930         {"audio", MIMETYPE_AUDIO},
931         {"video", MIMETYPE_VIDEO},
932         {"application", MIMETYPE_APPLICATION},
933         {"message", MIMETYPE_MESSAGE},
934         {"multipart", MIMETYPE_MULTIPART},
935         {NULL, 0},
936 };
937
938 const gchar *procmime_get_type_str(MimeMediaType type)
939 {
940         struct TypeTable *type_table;
941         
942         for (type_table = mime_type_table; type_table->str != NULL; type_table++) {
943                 if (type_table->type == type)
944                         return type_table->str;
945         }
946         return NULL;
947 }
948
949 /*!
950  *\brief        Safe wrapper for content type string.
951  *
952  *\return       const gchar * Pointer to content type string. 
953  */
954 gchar *procmime_get_content_type_str(MimeMediaType type,
955                                            const char *subtype)
956 {
957         const gchar *type_str = NULL;
958
959         if (subtype == NULL || !(type_str = procmime_get_type_str(type)))
960                 return g_strdup("unknown");
961         return g_strdup_printf("%s/%s", type_str, subtype);
962 }
963
964 void procmime_parse_mimepart(MimeInfo *parent,
965                              gchar *content_type,
966                              gchar *content_encoding,
967                              gchar *content_description,
968                              gchar *content_id,
969                              gchar *content_disposition,
970                              const gchar *filename,
971                              guint offset,
972                              guint length);
973
974 void procmime_parse_message_rfc822(MimeInfo *mimeinfo)
975 {
976         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
977                                 {"Content-Transfer-Encoding:",
978                                                    NULL, FALSE},
979                                 {"Content-Description:",
980                                                    NULL, TRUE},
981                                 {"Content-ID:",
982                                                    NULL, TRUE},
983                                 {"Content-Disposition:",
984                                                    NULL, TRUE},
985                                 {"MIME-Version:",
986                                                    NULL, TRUE},
987                                 {NULL,             NULL, FALSE}};
988         guint content_start, i;
989         FILE *fp;
990         gint mime_major, mime_minor;
991
992         if (mimeinfo->encoding_type != ENC_BINARY && 
993            mimeinfo->encoding_type != ENC_7BIT && 
994            mimeinfo->encoding_type != ENC_8BIT)
995                 procmime_decode_content(mimeinfo);
996
997         fp = fopen(mimeinfo->filename, "rb");
998         if (fp == NULL) {
999                 FILE_OP_ERROR(mimeinfo->filename, "fopen");
1000                 return;
1001         }
1002         fseek(fp, mimeinfo->offset, SEEK_SET);
1003         procheader_get_header_fields(fp, hentry);
1004         if (hentry[0].body != NULL)
1005                 conv_unmime_header_overwrite(hentry[0].body);
1006         if (hentry[2].body != NULL)
1007                 conv_unmime_header_overwrite(hentry[2].body);
1008         if (hentry[4].body != NULL)
1009                 conv_unmime_header_overwrite(hentry[4].body);
1010         content_start = ftell(fp);
1011         fclose(fp);
1012
1013         if ((hentry[5].body != NULL) &&
1014             (sscanf(hentry[5].body, "%d.%d", &mime_major, &mime_minor) == 2) &&
1015             (mime_major == 1) && (mime_minor == 0)) {
1016                 procmime_parse_mimepart(mimeinfo,
1017                                         hentry[0].body, hentry[1].body,
1018                                         hentry[2].body, hentry[3].body, 
1019                                         hentry[4].body, 
1020                                         mimeinfo->filename, content_start,
1021                                         mimeinfo->length - (content_start - mimeinfo->offset));
1022         } else {
1023                 MimeInfo *subinfo;
1024
1025                 subinfo = procmime_mimeinfo_new();
1026                 subinfo->encoding_type = ENC_BINARY;
1027                 subinfo->type = MIMETYPE_TEXT;
1028                 subinfo->subtype = g_strdup("plain");
1029                 subinfo->filename = g_strdup(mimeinfo->filename);
1030                 subinfo->offset = content_start;
1031                 subinfo->length = mimeinfo->length - (content_start - mimeinfo->offset);
1032
1033                 g_node_append(mimeinfo->node, subinfo->node);
1034         }
1035         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1036                 g_free(hentry[i].body);
1037                 hentry[i].body = NULL;
1038         }
1039 }
1040
1041 void procmime_parse_multipart(MimeInfo *mimeinfo)
1042 {
1043         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1044                                 {"Content-Transfer-Encoding:",
1045                                                    NULL, FALSE},
1046                                 {"Content-Description:",
1047                                                    NULL, TRUE},
1048                                 {"Content-ID:",
1049                                                    NULL, TRUE},
1050                                 {"Content-Disposition:",
1051                                                    NULL, TRUE},
1052                                 {NULL,             NULL, FALSE}};
1053         gchar *p;
1054         gchar *boundary;
1055         gint boundary_len = 0, lastoffset = -1, i;
1056         gchar buf[BUFFSIZE];
1057         FILE *fp;
1058
1059         boundary = g_hash_table_lookup(mimeinfo->parameters, "boundary");
1060         if (!boundary)
1061                 return;
1062         boundary_len = strlen(boundary);
1063
1064         if (mimeinfo->encoding_type != ENC_BINARY && 
1065             mimeinfo->encoding_type != ENC_7BIT && 
1066             mimeinfo->encoding_type != ENC_8BIT)
1067                 procmime_decode_content(mimeinfo);
1068
1069         fp = fopen(mimeinfo->filename, "rb");
1070         if (fp == NULL) {
1071                 FILE_OP_ERROR(mimeinfo->filename, "fopen");
1072                 return;
1073         }
1074         fseek(fp, mimeinfo->offset, SEEK_SET);
1075         while ((p = fgets(buf, sizeof(buf), fp)) != NULL) {
1076                 if (ftell(fp) > (mimeinfo->offset + mimeinfo->length))
1077                         break;
1078
1079                 if (IS_BOUNDARY(buf, boundary, boundary_len)) {
1080                         if (lastoffset != -1) {
1081                                 procmime_parse_mimepart(mimeinfo,
1082                                                         hentry[0].body, hentry[1].body,
1083                                                         hentry[2].body, hentry[3].body, 
1084                                                         hentry[4].body, 
1085                                                         mimeinfo->filename, lastoffset,
1086                                                         (ftell(fp) - strlen(buf)) - lastoffset);
1087                         }
1088                         
1089                         if (buf[2 + boundary_len]     == '-' &&
1090                             buf[2 + boundary_len + 1] == '-')
1091                                 break;
1092
1093                         for (i = 0; i < (sizeof hentry / sizeof hentry[0]) ; i++) {
1094                                 g_free(hentry[i].body);
1095                                 hentry[i].body = NULL;
1096                         }
1097                         procheader_get_header_fields(fp, hentry);
1098                         if (hentry[0].body != NULL)
1099                                 conv_unmime_header_overwrite(hentry[0].body);
1100                         if (hentry[2].body != NULL)
1101                                 conv_unmime_header_overwrite(hentry[2].body);
1102                         if (hentry[4].body != NULL)
1103                                 conv_unmime_header_overwrite(hentry[4].body);
1104                         lastoffset = ftell(fp);
1105                 }
1106         }
1107         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1108                 g_free(hentry[i].body);
1109                 hentry[i].body = NULL;
1110         }
1111         fclose(fp);
1112 }
1113
1114 static void add_to_mimeinfo_parameters(gchar **parts, MimeInfo *mimeinfo)
1115 {
1116         gchar **strarray;
1117
1118         for (strarray = parts; *strarray != NULL; strarray++) {
1119                 gchar **parameters_parts;
1120
1121                 parameters_parts = g_strsplit(*strarray, "=", 2);
1122                 if ((parameters_parts[0] != NULL) && (parameters_parts[1] != NULL)) {
1123                         gchar *firstspace;
1124
1125                         g_strstrip(parameters_parts[0]);
1126                         g_strstrip(parameters_parts[1]);
1127                         g_strdown(parameters_parts[0]);
1128                         if (parameters_parts[1][0] == '"')
1129                                 extract_quote(parameters_parts[1], '"');
1130                         else if ((firstspace = strchr(parameters_parts[1], ' ')) != NULL)
1131                                 *firstspace = '\0';
1132                         if (g_hash_table_lookup(mimeinfo->parameters,
1133                                                parameters_parts[0]) == NULL)
1134                                 g_hash_table_insert(mimeinfo->parameters,
1135                                                     g_strdup(parameters_parts[0]),
1136                                                     g_strdup(parameters_parts[1]));
1137                 }
1138                 g_strfreev(parameters_parts);
1139         }
1140 }       
1141
1142 static void procmime_parse_content_type(const gchar *content_type, MimeInfo *mimeinfo)
1143 {
1144         gchar **content_type_parts;
1145         gchar **strarray;
1146         gchar *str;
1147         struct TypeTable *typetablearray;
1148         
1149         g_return_if_fail(content_type != NULL);
1150         g_return_if_fail(mimeinfo != NULL);
1151
1152         /* Split content type into parts and remove trailing
1153            and leading whitespaces from all strings */
1154         content_type_parts = g_strsplit(content_type, ";", 0);
1155         for (strarray = content_type_parts; *strarray != NULL; strarray++) {
1156                 g_strstrip(*strarray);
1157         }
1158
1159         /* Get mimeinfo->type and mimeinfo->subtype */
1160         str = content_type_parts[0];
1161         /* RFC 2045, page 13 says that the mime subtype is MANDATORY;
1162          * if it's not available we use the default Content-Type */
1163         if ((str == NULL) || (str[0] == '\0') || (strchr(str, '/') == NULL)) {
1164                 mimeinfo->type = MIMETYPE_TEXT;
1165                 mimeinfo->subtype = g_strdup("plain");
1166                 if (g_hash_table_lookup(mimeinfo->parameters,
1167                                        "charset") == NULL)
1168                         g_hash_table_insert(mimeinfo->parameters,
1169                                             g_strdup("charset"),
1170                                             g_strdup("us-ascii"));
1171         } else {
1172                 mimeinfo->type = MIMETYPE_UNKNOWN;
1173                 for (typetablearray = mime_type_table; typetablearray->str != NULL; typetablearray++) {
1174                         if (g_strncasecmp(str, typetablearray->str, strlen(typetablearray->str)) == 0 &&
1175                             str[strlen(typetablearray->str)] == '/') {
1176                                 mimeinfo->type = typetablearray->type;
1177                                 mimeinfo->subtype = g_strdup(str + strlen(typetablearray->str) + 1);
1178                                 break;
1179                         }
1180                 }
1181
1182                 /* Get mimeinfo->parmeters */
1183                 add_to_mimeinfo_parameters(&content_type_parts[1], mimeinfo);
1184         }
1185
1186         g_strfreev(content_type_parts);
1187 }
1188
1189 static void procmime_parse_content_disposition(const gchar *content_disposition, MimeInfo *mimeinfo)
1190 {
1191         gchar **content_disp_parts;
1192         gchar **strarray;
1193         gchar *str;
1194
1195         g_return_if_fail(content_disposition != NULL);
1196         g_return_if_fail(mimeinfo != NULL);
1197
1198         /* Split into parts and remove trailing
1199            and leading whitespaces from all strings */
1200         content_disp_parts = g_strsplit(content_disposition, ";", 0);
1201         for (strarray = content_disp_parts; *strarray != NULL; strarray++) {
1202                 g_strstrip(*strarray);
1203         }
1204         /* Get mimeinfo->disposition */
1205         str = content_disp_parts[0];
1206         if (str == NULL) {
1207                 g_strfreev(content_disp_parts);
1208                 return;
1209         }
1210         if (!g_strcasecmp(str, "inline")) 
1211                 mimeinfo->disposition = DISPOSITIONTYPE_INLINE;
1212         else if (!g_strcasecmp(str, "attachment"))
1213                 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1214         else
1215                 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1216         
1217         add_to_mimeinfo_parameters(&content_disp_parts[1], mimeinfo);
1218         g_strfreev(content_disp_parts);
1219 }
1220
1221
1222 static void procmime_parse_content_encoding(const gchar *content_encoding, MimeInfo *mimeinfo)
1223 {
1224         struct EncodingTable *enc_table;
1225         
1226         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1227                 if (g_strcasecmp(enc_table->str, content_encoding) == 0) {
1228                         mimeinfo->encoding_type = enc_table->enc_type;
1229                         return;
1230                 }
1231         }
1232         mimeinfo->encoding_type = ENC_UNKNOWN;
1233         return;
1234 }
1235
1236 void procmime_parse_mimepart(MimeInfo *parent,
1237                              gchar *content_type,
1238                              gchar *content_encoding,
1239                              gchar *content_description,
1240                              gchar *content_id,
1241                              gchar *content_disposition,
1242                              const gchar *filename,
1243                              guint offset,
1244                              guint length)
1245 {
1246         MimeInfo *mimeinfo;
1247
1248         /* Create MimeInfo */
1249         mimeinfo = procmime_mimeinfo_new();
1250         if (parent != NULL)
1251                 g_node_append(parent->node, mimeinfo->node);
1252         mimeinfo->filename = g_strdup(filename);
1253         mimeinfo->offset = offset;
1254         mimeinfo->length = length;
1255
1256         if (content_type != NULL) {
1257                 procmime_parse_content_type(content_type, mimeinfo);
1258         } else {
1259                 mimeinfo->type = MIMETYPE_TEXT;
1260                 mimeinfo->subtype = g_strdup("plain");
1261                 if (g_hash_table_lookup(mimeinfo->parameters,
1262                                        "charset") == NULL)
1263                         g_hash_table_insert(mimeinfo->parameters, g_strdup("charset"), g_strdup("us-ascii"));
1264         }
1265
1266         if (content_encoding != NULL) {
1267                 procmime_parse_content_encoding(content_encoding, mimeinfo);
1268         } else {
1269                 mimeinfo->encoding_type = ENC_7BIT;
1270         }
1271
1272         if (content_description != NULL)
1273                 mimeinfo->description = g_strdup(content_description);
1274         else
1275                 mimeinfo->description = NULL;
1276
1277         if (content_id != NULL)
1278                 mimeinfo->id = g_strdup(content_id);
1279         else
1280                 mimeinfo->id = NULL;
1281
1282         if (content_disposition != NULL) 
1283                 procmime_parse_content_disposition(content_disposition, mimeinfo);
1284         else
1285                 mimeinfo->disposition = DISPOSITIONTYPE_UNKNOWN;
1286
1287         /* Call parser for mime type */
1288         switch (mimeinfo->type) {
1289                 case MIMETYPE_MESSAGE:
1290                         if (g_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
1291                                 procmime_parse_message_rfc822(mimeinfo);
1292                         }
1293                         break;
1294                         
1295                 case MIMETYPE_MULTIPART:
1296                         procmime_parse_multipart(mimeinfo);
1297                         break;
1298                         
1299                 default:
1300                         break;
1301         }
1302 }
1303
1304 static gchar *typenames[] = {
1305     "text",
1306     "image",
1307     "audio",
1308     "video",
1309     "application",
1310     "message",
1311     "multipart",
1312     "unknown",
1313 };
1314
1315 static gboolean output_func(GNode *node, gpointer data)
1316 {
1317         guint i, depth;
1318         MimeInfo *mimeinfo = (MimeInfo *) node->data;
1319
1320         depth = g_node_depth(node);
1321         for (i = 0; i < depth; i++)
1322                 printf("    ");
1323         printf("%s/%s (offset:%d length:%d encoding: %d)\n", typenames[mimeinfo->type], mimeinfo->subtype, mimeinfo->offset, mimeinfo->length, mimeinfo->encoding_type);
1324
1325         return FALSE;
1326 }
1327
1328 static void output_mime_structure(MimeInfo *mimeinfo, int indent)
1329 {
1330         g_node_traverse(mimeinfo->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1, output_func, NULL);
1331 }
1332
1333 static MimeInfo *procmime_scan_file_with_offset(const gchar *filename, int offset)
1334 {
1335         MimeInfo *mimeinfo;
1336         struct stat buf;
1337
1338         stat(filename, &buf);
1339
1340         mimeinfo = procmime_mimeinfo_new();
1341         mimeinfo->encoding_type = ENC_BINARY;
1342         mimeinfo->type = MIMETYPE_MESSAGE;
1343         mimeinfo->subtype = g_strdup("rfc822");
1344         mimeinfo->filename = g_strdup(filename);
1345         mimeinfo->offset = offset;
1346         mimeinfo->length = buf.st_size - offset;
1347
1348         procmime_parse_message_rfc822(mimeinfo);
1349         if (debug_get_mode())
1350                 output_mime_structure(mimeinfo, 0);
1351
1352         return mimeinfo;
1353 }
1354
1355 MimeInfo *procmime_scan_file(gchar *filename)
1356 {
1357         MimeInfo *mimeinfo;
1358
1359         g_return_val_if_fail(filename != NULL, NULL);
1360
1361         mimeinfo = procmime_scan_file_with_offset(filename, 0);
1362
1363         return mimeinfo;
1364 }
1365
1366 MimeInfo *procmime_scan_queue_file(gchar *filename)
1367 {
1368         FILE *fp;
1369         MimeInfo *mimeinfo;
1370         gchar buf[BUFFSIZE];
1371         gint offset = 0;
1372
1373         g_return_val_if_fail(filename != NULL, NULL);
1374
1375         /* Open file */
1376         if ((fp = fopen(filename, "rb")) == NULL)
1377                 return NULL;
1378         /* Skip queue header */
1379         while (fgets(buf, sizeof(buf), fp) != NULL)
1380                 if (buf[0] == '\r' || buf[0] == '\n') break;
1381         offset = ftell(fp);
1382         fclose(fp);
1383
1384         mimeinfo = procmime_scan_file_with_offset(filename, offset);
1385
1386         return mimeinfo;
1387 }