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