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