replace deprecated gtk_signal... functions
[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, a;
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         fseek(fp, mimeinfo->offset, SEEK_SET);
999         procheader_get_header_fields(fp, hentry);
1000         if (hentry[0].body != NULL)
1001                 conv_unmime_header_overwrite(hentry[0].body);
1002         if (hentry[2].body != NULL)
1003                 conv_unmime_header_overwrite(hentry[2].body);
1004         if (hentry[4].body != NULL)
1005                 conv_unmime_header_overwrite(hentry[4].body);
1006         content_start = ftell(fp);
1007         fclose(fp);
1008
1009         if ((hentry[5].body != NULL) &&
1010             (sscanf(hentry[5].body, "%d.%d", &mime_major, &mime_minor) == 2) &&
1011             (mime_major == 1) && (mime_minor == 0)) {
1012                 procmime_parse_mimepart(mimeinfo,
1013                                         hentry[0].body, hentry[1].body,
1014                                         hentry[2].body, hentry[3].body, 
1015                                         hentry[4].body, 
1016                                         mimeinfo->filename, content_start,
1017                                         mimeinfo->length - (content_start - mimeinfo->offset));
1018         } else {
1019                 MimeInfo *subinfo;
1020
1021                 subinfo = procmime_mimeinfo_new();
1022                 subinfo->encoding_type = ENC_BINARY;
1023                 subinfo->type = MIMETYPE_TEXT;
1024                 subinfo->subtype = g_strdup("plain");
1025                 subinfo->filename = g_strdup(mimeinfo->filename);
1026                 subinfo->offset = content_start;
1027                 subinfo->length = mimeinfo->length - (content_start - mimeinfo->offset);
1028
1029                 g_node_append(mimeinfo->node, subinfo->node);
1030         }
1031         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1032                 g_free(hentry[i].body);
1033                 hentry[i].body = NULL;
1034         }
1035 }
1036
1037 void procmime_parse_multipart(MimeInfo *mimeinfo)
1038 {
1039         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1040                                 {"Content-Transfer-Encoding:",
1041                                                    NULL, FALSE},
1042                                 {"Content-Description:",
1043                                                    NULL, TRUE},
1044                                 {"Content-ID:",
1045                                                    NULL, TRUE},
1046                                 {"Content-Disposition:",
1047                                                    NULL, TRUE},
1048                                 {NULL,             NULL, FALSE}};
1049         gchar *p;
1050         gchar *boundary;
1051         gint boundary_len = 0, lastoffset = -1, i;
1052         gchar buf[BUFFSIZE];
1053         FILE *fp;
1054
1055         boundary = g_hash_table_lookup(mimeinfo->parameters, "boundary");
1056         if (!boundary)
1057                 return;
1058         boundary_len = strlen(boundary);
1059
1060         if (mimeinfo->encoding_type != ENC_BINARY && 
1061             mimeinfo->encoding_type != ENC_7BIT && 
1062             mimeinfo->encoding_type != ENC_8BIT)
1063                 procmime_decode_content(mimeinfo);
1064
1065         fp = fopen(mimeinfo->filename, "rb");
1066         fseek(fp, mimeinfo->offset, SEEK_SET);
1067         while ((p = fgets(buf, sizeof(buf), fp)) != NULL) {
1068                 if (ftell(fp) > (mimeinfo->offset + mimeinfo->length))
1069                         break;
1070
1071                 if (IS_BOUNDARY(buf, boundary, boundary_len)) {
1072                         if (lastoffset != -1) {
1073                                 procmime_parse_mimepart(mimeinfo,
1074                                                         hentry[0].body, hentry[1].body,
1075                                                         hentry[2].body, hentry[3].body, 
1076                                                         hentry[4].body, 
1077                                                         mimeinfo->filename, lastoffset,
1078                                                         (ftell(fp) - strlen(buf)) - lastoffset);
1079                         }
1080                         
1081                         if (buf[2 + boundary_len]     == '-' &&
1082                             buf[2 + boundary_len + 1] == '-')
1083                                 break;
1084
1085                         for (i = 0; i < (sizeof hentry / sizeof hentry[0]) ; i++) {
1086                                 g_free(hentry[i].body);
1087                                 hentry[i].body = NULL;
1088                         }
1089                         procheader_get_header_fields(fp, hentry);
1090                         if (hentry[0].body != NULL)
1091                                 conv_unmime_header_overwrite(hentry[0].body);
1092                         if (hentry[2].body != NULL)
1093                                 conv_unmime_header_overwrite(hentry[2].body);
1094                         if (hentry[4].body != NULL)
1095                                 conv_unmime_header_overwrite(hentry[4].body);
1096                         lastoffset = ftell(fp);
1097                 }
1098         }
1099         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1100                 g_free(hentry[i].body);
1101                 hentry[i].body = NULL;
1102         }
1103         fclose(fp);
1104 }
1105
1106 static void add_to_mimeinfo_parameters(gchar **parts, MimeInfo *mimeinfo)
1107 {
1108         gchar **strarray;
1109
1110         for (strarray = parts; *strarray != NULL; strarray++) {
1111                 gchar **parameters_parts;
1112
1113                 parameters_parts = g_strsplit(*strarray, "=", 2);
1114                 if ((parameters_parts[0] != NULL) && (parameters_parts[1] != NULL)) {
1115                         gchar *firstspace;
1116
1117                         g_strstrip(parameters_parts[0]);
1118                         g_strstrip(parameters_parts[1]);
1119                         g_strdown(parameters_parts[0]);
1120                         if (parameters_parts[1][0] == '"')
1121                                 extract_quote(parameters_parts[1], '"');
1122                         else if ((firstspace = strchr(parameters_parts[1], ' ')) != NULL)
1123                                 *firstspace = '\0';
1124                         if (g_hash_table_lookup(mimeinfo->parameters,
1125                                                parameters_parts[0]) == NULL)
1126                                 g_hash_table_insert(mimeinfo->parameters,
1127                                                     g_strdup(parameters_parts[0]),
1128                                                     g_strdup(parameters_parts[1]));
1129                 }
1130                 g_strfreev(parameters_parts);
1131         }
1132 }       
1133
1134 static void procmime_parse_content_type(const gchar *content_type, MimeInfo *mimeinfo)
1135 {
1136         gchar **content_type_parts;
1137         gchar **strarray;
1138         gchar *str;
1139         struct TypeTable *typetablearray;
1140         
1141         g_return_if_fail(content_type != NULL);
1142         g_return_if_fail(mimeinfo != NULL);
1143
1144         /* Split content type into parts and remove trailing
1145            and leading whitespaces from all strings */
1146         content_type_parts = g_strsplit(content_type, ";", 0);
1147         for (strarray = content_type_parts; *strarray != NULL; strarray++) {
1148                 g_strstrip(*strarray);
1149         }
1150
1151         /* Get mimeinfo->type and mimeinfo->subtype */
1152         str = content_type_parts[0];
1153         /* RFC 2045, page 13 says that the mime subtype is MANDATORY;
1154          * if it's not available we use the default Content-Type */
1155         if ((str == NULL) || (str[0] == '\0') || (strchr(str, '/') == NULL)) {
1156                 mimeinfo->type = MIMETYPE_TEXT;
1157                 mimeinfo->subtype = g_strdup("plain");
1158                 if (g_hash_table_lookup(mimeinfo->parameters,
1159                                        "charset") == NULL)
1160                         g_hash_table_insert(mimeinfo->parameters,
1161                                             g_strdup("charset"),
1162                                             g_strdup("us-ascii"));
1163         } else {
1164                 mimeinfo->type = MIMETYPE_UNKNOWN;
1165                 for (typetablearray = mime_type_table; typetablearray->str != NULL; typetablearray++) {
1166                         if (g_strncasecmp(str, typetablearray->str, strlen(typetablearray->str)) == 0 &&
1167                             str[strlen(typetablearray->str)] == '/') {
1168                                 mimeinfo->type = typetablearray->type;
1169                                 mimeinfo->subtype = g_strdup(str + strlen(typetablearray->str) + 1);
1170                                 break;
1171                         }
1172                 }
1173
1174                 /* Get mimeinfo->parmeters */
1175                 add_to_mimeinfo_parameters(&content_type_parts[1], mimeinfo);
1176         }
1177
1178         g_strfreev(content_type_parts);
1179 }
1180
1181 static void procmime_parse_content_disposition(const gchar *content_disposition, MimeInfo *mimeinfo)
1182 {
1183         gchar **content_disp_parts;
1184         gchar **strarray;
1185         gchar *str;
1186
1187         g_return_if_fail(content_disposition != NULL);
1188         g_return_if_fail(mimeinfo != NULL);
1189
1190         /* Split into parts and remove trailing
1191            and leading whitespaces from all strings */
1192         content_disp_parts = g_strsplit(content_disposition, ";", 0);
1193         for (strarray = content_disp_parts; *strarray != NULL; strarray++) {
1194                 g_strstrip(*strarray);
1195         }
1196         /* Get mimeinfo->disposition */
1197         str = content_disp_parts[0];
1198         if (str == NULL) {
1199                 g_strfreev(content_disp_parts);
1200                 return;
1201         }
1202         if (!g_strcasecmp(str, "inline")) 
1203                 mimeinfo->disposition = DISPOSITIONTYPE_INLINE;
1204         else if (!g_strcasecmp(str, "attachment"))
1205                 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1206         else
1207                 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1208         
1209         add_to_mimeinfo_parameters(&content_disp_parts[1], mimeinfo);
1210         g_strfreev(content_disp_parts);
1211 }
1212
1213
1214 static void procmime_parse_content_encoding(const gchar *content_encoding, MimeInfo *mimeinfo)
1215 {
1216         struct EncodingTable *enc_table;
1217         
1218         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1219                 if (g_strcasecmp(enc_table->str, content_encoding) == 0) {
1220                         mimeinfo->encoding_type = enc_table->enc_type;
1221                         return;
1222                 }
1223         }
1224         mimeinfo->encoding_type = ENC_UNKNOWN;
1225         return;
1226 }
1227
1228 void procmime_parse_mimepart(MimeInfo *parent,
1229                              gchar *content_type,
1230                              gchar *content_encoding,
1231                              gchar *content_description,
1232                              gchar *content_id,
1233                              gchar *content_disposition,
1234                              const gchar *filename,
1235                              guint offset,
1236                              guint length)
1237 {
1238         MimeInfo *mimeinfo;
1239
1240         /* Create MimeInfo */
1241         mimeinfo = procmime_mimeinfo_new();
1242         if (parent != NULL)
1243                 g_node_append(parent->node, mimeinfo->node);
1244         mimeinfo->filename = g_strdup(filename);
1245         mimeinfo->offset = offset;
1246         mimeinfo->length = length;
1247
1248         if (content_type != NULL) {
1249                 procmime_parse_content_type(content_type, mimeinfo);
1250         } else {
1251                 mimeinfo->type = MIMETYPE_TEXT;
1252                 mimeinfo->subtype = g_strdup("plain");
1253                 if (g_hash_table_lookup(mimeinfo->parameters,
1254                                        "charset") == NULL)
1255                         g_hash_table_insert(mimeinfo->parameters, g_strdup("charset"), g_strdup("us-ascii"));
1256         }
1257
1258         if (content_encoding != NULL) {
1259                 procmime_parse_content_encoding(content_encoding, mimeinfo);
1260         } else {
1261                 mimeinfo->encoding_type = ENC_7BIT;
1262         }
1263
1264         if (content_description != NULL)
1265                 mimeinfo->description = g_strdup(content_description);
1266         else
1267                 mimeinfo->description = NULL;
1268
1269         if (content_id != NULL)
1270                 mimeinfo->id = g_strdup(content_id);
1271         else
1272                 mimeinfo->id = NULL;
1273
1274         if (content_disposition != NULL) 
1275                 procmime_parse_content_disposition(content_disposition, mimeinfo);
1276         else
1277                 mimeinfo->disposition = DISPOSITIONTYPE_UNKNOWN;
1278
1279         /* Call parser for mime type */
1280         switch (mimeinfo->type) {
1281                 case MIMETYPE_MESSAGE:
1282                         if (g_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
1283                                 procmime_parse_message_rfc822(mimeinfo);
1284                         }
1285                         break;
1286                         
1287                 case MIMETYPE_MULTIPART:
1288                         procmime_parse_multipart(mimeinfo);
1289                         break;
1290                         
1291                 default:
1292                         break;
1293         }
1294 }
1295
1296 static gchar *typenames[] = {
1297     "text",
1298     "image",
1299     "audio",
1300     "video",
1301     "application",
1302     "message",
1303     "multipart",
1304     "unknown",
1305 };
1306
1307 static gboolean output_func(GNode *node, gpointer data)
1308 {
1309         guint i, depth;
1310         MimeInfo *mimeinfo = (MimeInfo *) node->data;
1311
1312         depth = g_node_depth(node);
1313         for (i = 0; i < depth; i++)
1314                 printf("    ");
1315         printf("%s/%s (offset:%d length:%d encoding: %d)\n", typenames[mimeinfo->type], mimeinfo->subtype, mimeinfo->offset, mimeinfo->length, mimeinfo->encoding_type);
1316
1317         return FALSE;
1318 }
1319
1320 static void output_mime_structure(MimeInfo *mimeinfo, int indent)
1321 {
1322         g_node_traverse(mimeinfo->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1, output_func, NULL);
1323 }
1324
1325 static MimeInfo *procmime_scan_file_with_offset(const gchar *filename, int offset)
1326 {
1327         MimeInfo *mimeinfo;
1328         struct stat buf;
1329
1330         stat(filename, &buf);
1331
1332         mimeinfo = procmime_mimeinfo_new();
1333         mimeinfo->encoding_type = ENC_BINARY;
1334         mimeinfo->type = MIMETYPE_MESSAGE;
1335         mimeinfo->subtype = g_strdup("rfc822");
1336         mimeinfo->filename = g_strdup(filename);
1337         mimeinfo->offset = offset;
1338         mimeinfo->length = buf.st_size - offset;
1339
1340         procmime_parse_message_rfc822(mimeinfo);
1341         if (debug_get_mode())
1342                 output_mime_structure(mimeinfo, 0);
1343
1344         return mimeinfo;
1345 }
1346
1347 MimeInfo *procmime_scan_file(gchar *filename)
1348 {
1349         MimeInfo *mimeinfo;
1350
1351         g_return_val_if_fail(filename != NULL, NULL);
1352
1353         mimeinfo = procmime_scan_file_with_offset(filename, 0);
1354
1355         return mimeinfo;
1356 }
1357
1358 MimeInfo *procmime_scan_queue_file(gchar *filename)
1359 {
1360         FILE *fp;
1361         MimeInfo *mimeinfo;
1362         gchar buf[BUFFSIZE];
1363         gint offset = 0;
1364
1365         g_return_val_if_fail(filename != NULL, NULL);
1366
1367         /* Open file */
1368         if ((fp = fopen(filename, "rb")) == NULL)
1369                 return NULL;
1370         /* Skip queue header */
1371         while (fgets(buf, sizeof(buf), fp) != NULL)
1372                 if (buf[0] == '\r' || buf[0] == '\n') break;
1373         offset = ftell(fp);
1374         fclose(fp);
1375
1376         mimeinfo = procmime_scan_file_with_offset(filename, offset);
1377
1378         return mimeinfo;
1379 }