0.9.6claws40
[claws.git] / src / procmime.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2003 Hiroyuki Yamamoto
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include "defs.h"
25
26 #include <glib.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <sys/types.h>
32 #include <sys/stat.h>
33 #include <unistd.h>
34
35 #include "intl.h"
36 #include "procmime.h"
37 #include "procheader.h"
38 #include "base64.h"
39 #include "quoted-printable.h"
40 #include "uuencode.h"
41 #include "unmime.h"
42 #include "html.h"
43 #include "enriched.h"
44 #include "codeconv.h"
45 #include "utils.h"
46 #include "prefs_common.h"
47
48 #include "prefs_gtk.h"
49
50 static GHashTable *procmime_get_mime_type_table (void);
51
52 MimeInfo *procmime_mimeinfo_new(void)
53 {
54         MimeInfo *mimeinfo;
55
56         mimeinfo = g_new0(MimeInfo, 1);
57         mimeinfo->type          = MIMETYPE_UNKNOWN;
58         mimeinfo->encoding_type = ENC_UNKNOWN;
59
60         mimeinfo->parameters = g_hash_table_new(g_str_hash, g_str_equal);
61         mimeinfo->node       = g_node_new(mimeinfo);
62
63         return mimeinfo;
64 }
65
66 static gboolean procmime_mimeinfo_parameters_destroy(gpointer key, gpointer value, gpointer user_data)
67 {
68         g_free(key);
69         g_free(value);
70         
71         return TRUE;
72 }
73
74 static gboolean free_func(GNode *node, gpointer data)
75 {
76         MimeInfo *mimeinfo = (MimeInfo *) node->data;
77
78         g_free(mimeinfo->encoding);
79         g_free(mimeinfo->name);
80         g_free(mimeinfo->content_disposition);
81         if(mimeinfo->tmpfile)
82                 unlink(mimeinfo->filename);
83         g_free(mimeinfo->filename);
84
85         g_free(mimeinfo->subtype);
86         g_free(mimeinfo->description);
87         g_free(mimeinfo->id);
88
89         g_hash_table_foreach_remove(mimeinfo->parameters, procmime_mimeinfo_parameters_destroy, NULL);
90         g_hash_table_destroy(mimeinfo->parameters);
91
92         if (mimeinfo->privacy)
93                 privacy_free_privacydata(mimeinfo->privacy);
94
95         g_free(mimeinfo);
96
97         return FALSE;
98 }
99
100 void procmime_mimeinfo_free_all(MimeInfo *mimeinfo)
101 {
102         GNode *node;
103
104         g_return_if_fail(mimeinfo);
105
106         node = mimeinfo->node;
107         g_node_traverse(node, G_IN_ORDER, G_TRAVERSE_ALL, -1, free_func, NULL);
108
109         g_node_destroy(node);
110 }
111
112 #if 0 /* UNUSED */
113 MimeInfo *procmime_mimeinfo_insert(MimeInfo *parent, MimeInfo *mimeinfo)
114 {
115         MimeInfo *child = parent->children;
116
117         if (!child)
118                 parent->children = mimeinfo;
119         else {
120                 while (child->next != NULL)
121                         child = child->next;
122
123                 child->next = mimeinfo;
124         }
125
126         mimeinfo->parent = parent;
127         mimeinfo->level = parent->level + 1;
128
129         return mimeinfo;
130 }
131
132 void procmime_mimeinfo_replace(MimeInfo *old, MimeInfo *new)
133 {
134         MimeInfo *parent = old->parent;
135         MimeInfo *child;
136
137         g_return_if_fail(parent != NULL);
138         g_return_if_fail(new->next == NULL);
139
140         for (child = parent->children; child && child != old;
141              child = child->next)
142                 ;
143         if (!child) {
144                 g_warning("oops: parent can't find it's own child");
145                 return;
146         }
147         procmime_mimeinfo_free_all(old);
148
149         if (child == parent->children) {
150                 new->next = parent->children->next;
151                 parent->children = new;
152         } else {
153                 new->next = child->next;
154                 child = new;
155         }
156 }
157 #endif
158
159 MimeInfo *procmime_mimeinfo_parent(MimeInfo *mimeinfo)
160 {
161         g_return_val_if_fail(mimeinfo != NULL, NULL);
162
163         if (mimeinfo->node->parent == NULL)
164                 return NULL;
165         return (MimeInfo *) mimeinfo->node->parent->data;
166 }
167
168 MimeInfo *procmime_mimeinfo_next(MimeInfo *mimeinfo)
169 {
170         if (!mimeinfo) return 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         for (mimeinfo = (MimeInfo *) mimeinfo->node->parent->data; mimeinfo != NULL;
178              mimeinfo = (MimeInfo *) mimeinfo->node->parent->data) {
179                 if (mimeinfo->node->next)
180                         return (MimeInfo *) mimeinfo->node->next->data;
181         }
182
183         return NULL;
184 }
185
186 MimeInfo *procmime_scan_message(MsgInfo *msginfo)
187 {
188         gchar *filename;
189         MimeInfo *mimeinfo;
190
191         filename = procmsg_get_message_file(msginfo);
192         if(!filename)
193                 return NULL;
194         if (msginfo->folder->stype != F_QUEUE)
195                 mimeinfo = procmime_scan_file(filename);
196         else
197                 mimeinfo = procmime_scan_queue_file(filename);
198         g_free(filename);
199
200         return mimeinfo;
201 }
202
203 enum
204 {
205         H_CONTENT_TRANSFER_ENCODING = 0,
206         H_CONTENT_TYPE              = 1,
207         H_CONTENT_DISPOSITION       = 2,
208         H_CONTENT_DESCRIPTION       = 3,
209         H_SUBJECT                   = 4
210 };
211
212 const gchar *procmime_mimeinfo_get_parameter(MimeInfo *mimeinfo, const gchar *name)
213 {
214         g_return_val_if_fail(mimeinfo != NULL, NULL);
215         g_return_val_if_fail(name != NULL, NULL);
216         
217         return g_hash_table_lookup(mimeinfo->parameters, name);
218 }
219
220 gboolean procmime_decode_content(MimeInfo *mimeinfo)
221 {
222         gchar buf[BUFFSIZE];
223         gint readend;
224         gchar *tmpfilename;
225         gchar *mimetmpdir;
226         FILE *outfp, *infp;
227         struct stat statbuf;
228
229         g_return_val_if_fail(mimeinfo != NULL, FALSE);
230
231         if(mimeinfo->encoding_type == ENC_BINARY)
232                 return TRUE;
233
234         infp = fopen(mimeinfo->filename, "rb");
235         if(!infp) {
236                 perror("fopen");
237                 return FALSE;
238         }
239         fseek(infp, mimeinfo->offset, SEEK_SET);
240
241         mimetmpdir = get_mime_tmp_dir();
242         outfp = get_tmpfile_in_dir(mimetmpdir, &tmpfilename);
243         if (!outfp) {
244                 perror("tmpfile");
245                 return FALSE;
246         }
247
248         readend = mimeinfo->offset + mimeinfo->length;
249
250         if (mimeinfo->encoding_type == ENC_QUOTED_PRINTABLE) {
251                 while ((ftell(infp) < readend) && (fgets(buf, sizeof(buf), infp) != NULL)) {
252                         gint len;
253                         len = qp_decode_line(buf);
254                         fwrite(buf, len, 1, outfp);
255                 }
256         } else if (mimeinfo->encoding_type == ENC_BASE64) {
257                 gchar outbuf[BUFFSIZE];
258                 gint len;
259                 Base64Decoder *decoder;
260
261                 decoder = base64_decoder_new();
262                 while ((ftell(infp) < readend) && (fgets(buf, sizeof(buf), infp) != NULL)) {
263                         len = base64_decoder_decode(decoder, buf, outbuf);
264                         if (len < 0) {
265                                 g_warning("Bad BASE64 content\n");
266                                 break;
267                         }
268                         fwrite(outbuf, sizeof(gchar), len, outfp);
269                 }
270                 base64_decoder_free(decoder);
271         } else if (mimeinfo->encoding_type == ENC_X_UUENCODE) {
272                 gchar outbuf[BUFFSIZE];
273                 gint len;
274                 gboolean flag = FALSE;
275
276                 while ((ftell(infp) < readend) && (fgets(buf, sizeof(buf), infp) != NULL)) {
277                         if(!flag && strncmp(buf,"begin ", 6)) continue;
278
279                         if (flag) {
280                                 len = fromuutobits(outbuf, buf);
281                                 if (len <= 0) {
282                                         if (len < 0) 
283                                                 g_warning("Bad UUENCODE content(%d)\n", len);
284                                         break;
285                                 }
286                                 fwrite(outbuf, sizeof(gchar), len, outfp);
287                         } else
288                                 flag = TRUE;
289                 }
290         } else {
291                 while ((ftell(infp) < readend) && (fgets(buf, sizeof(buf), infp) != NULL)) {
292                         fputs(buf, outfp);
293                 }
294         }
295
296         fclose(outfp);
297         fclose(infp);
298
299         stat(tmpfilename, &statbuf);
300         if(mimeinfo->tmpfile)
301                 unlink(mimeinfo->filename);
302         g_free(mimeinfo->filename);
303         mimeinfo->filename = tmpfilename;
304         mimeinfo->tmpfile = TRUE;
305         mimeinfo->offset = 0;
306         mimeinfo->length = statbuf.st_size;
307         mimeinfo->encoding_type = ENC_BINARY;
308
309         return TRUE;
310 }
311
312 gint procmime_get_part(const gchar *outfile, MimeInfo *mimeinfo)
313 {
314         FILE *infp, *outfp;
315         gchar buf[BUFFSIZE];
316         gint restlength, readlength;
317
318         g_return_val_if_fail(outfile != NULL, -1);
319         g_return_val_if_fail(mimeinfo != NULL, -1);
320
321         if(mimeinfo->encoding_type != ENC_BINARY && !procmime_decode_content(mimeinfo))
322                 return -1;
323
324         if ((infp = fopen(mimeinfo->filename, "rb")) == NULL) {
325                 FILE_OP_ERROR(mimeinfo->filename, "fopen");
326                 return -1;
327         }
328         if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
329                 FILE_OP_ERROR(mimeinfo->filename, "fseek");
330                 fclose(infp);
331                 return -1;
332         }
333         if ((outfp = fopen(outfile, "wb")) == NULL) {
334                 FILE_OP_ERROR(outfile, "fopen");
335                 fclose(infp);
336                 return -1;
337         }
338
339         restlength = mimeinfo->length;
340
341         while ((restlength > 0) && ((readlength = fread(buf, 1, restlength > BUFFSIZE ? BUFFSIZE : restlength, infp)) > 0)) {
342                 fwrite(buf, 1, readlength, outfp);
343                 restlength -= readlength;
344         }
345
346         fclose(infp);
347         if (fclose(outfp) == EOF) {
348                 FILE_OP_ERROR(outfile, "fclose");
349                 unlink(outfile);
350                 return -1;
351         }
352
353         return 0;
354 }
355
356 struct ContentRenderer {
357         char * content_type;
358         char * renderer;
359 };
360
361 static GList * renderer_list = NULL;
362
363 static struct ContentRenderer *
364 content_renderer_new(char * content_type, char * renderer)
365 {
366         struct ContentRenderer * cr;
367
368         cr = g_new(struct ContentRenderer, 1);
369         if (cr == NULL)
370                 return NULL;
371
372         cr->content_type = g_strdup(content_type);
373         cr->renderer = g_strdup(renderer);
374
375         return cr;
376 }
377
378 static void content_renderer_free(struct ContentRenderer * cr)
379 {
380         g_free(cr->content_type);
381         g_free(cr->renderer);
382         g_free(cr);
383 }
384
385 void renderer_read_config(void)
386 {
387         gchar buf[BUFFSIZE];
388         FILE * f;
389         gchar * rcpath;
390
391         g_list_foreach(renderer_list, (GFunc) content_renderer_free, NULL);
392         renderer_list = NULL;
393
394         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, RENDERER_RC, NULL);
395         f = fopen(rcpath, "rb");
396         g_free(rcpath);
397         
398         if (f == NULL)
399                 return;
400
401         while (fgets(buf, BUFFSIZE, f)) {
402                 char * p;
403                 struct ContentRenderer * cr;
404
405                 strretchomp(buf);
406                 p = strchr(buf, ' ');
407                 if (p == NULL)
408                         continue;
409                 * p = 0;
410
411                 cr = content_renderer_new(buf, p + 1);
412                 if (cr == NULL)
413                         continue;
414
415                 renderer_list = g_list_append(renderer_list, cr);
416         }
417
418         fclose(f);
419 }
420
421 void renderer_write_config(void)
422 {
423         gchar * rcpath;
424         PrefFile *pfile;
425         GList * cur;
426
427         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, RENDERER_RC, NULL);
428         
429         if ((pfile = prefs_write_open(rcpath)) == NULL) {
430                 g_warning("failed to write configuration to file\n");
431                 g_free(rcpath);
432                 return;
433         }
434
435         g_free(rcpath);
436
437         for(cur = renderer_list ; cur != NULL ; cur = cur->next) {
438                 struct ContentRenderer * renderer;
439                 renderer = cur->data;
440                 fprintf(pfile->fp, "%s %s\n", renderer->content_type,
441                         renderer->renderer);
442         }
443
444         if (prefs_file_close(pfile) < 0) {
445                 g_warning("failed to write configuration to file\n");
446                 return;
447         }
448 }
449
450 FILE *procmime_get_text_content(MimeInfo *mimeinfo)
451 {
452         FILE *tmpfp, *outfp;
453         gchar *src_codeset;
454         gboolean conv_fail = FALSE;
455         gchar buf[BUFFSIZE];
456         gchar *str;
457         struct ContentRenderer * renderer;
458         GList * cur;
459         gchar *tmpfile, *content_type;
460     
461         g_return_val_if_fail(mimeinfo != NULL, NULL);
462
463         if (!procmime_decode_content(mimeinfo))
464                 return NULL;
465
466         tmpfile = procmime_get_tmp_file_name(mimeinfo);
467         if (tmpfile == NULL)
468                 return NULL;
469
470         if (procmime_get_part(tmpfile, mimeinfo) < 0) {
471                 g_free(tmpfile);
472                 return NULL;
473         }
474
475         tmpfp = fopen(tmpfile, "rb");
476         if (tmpfp == NULL) {
477                 g_free(tmpfile);
478                 return NULL;
479         }
480
481         if ((outfp = my_tmpfile()) == NULL) {
482                 perror("tmpfile");
483                 fclose(tmpfp);
484                 g_free(tmpfile);
485                 return NULL;
486         }
487
488         src_codeset = prefs_common.force_charset
489                 ? prefs_common.force_charset : 
490                 procmime_mimeinfo_get_parameter(mimeinfo, "charset");
491
492         renderer = NULL;
493
494         content_type = g_strdup_printf("%s/%s", procmime_get_type_str(mimeinfo->type),
495                 mimeinfo->subtype);
496         for(cur = renderer_list ; cur != NULL ; cur = cur->next) {
497                 struct ContentRenderer * cr;
498
499                 cr = cur->data;
500                 if (g_strcasecmp(cr->content_type, content_type) == 0) {
501                         renderer = cr;
502                         break;
503                 }
504         }
505         g_free(content_type);
506
507         if (renderer != NULL) {
508                 FILE * p;
509                 int oldout;
510                 
511                 oldout = dup(1);
512                 
513                 dup2(fileno(outfp), 1);
514                 
515                 p = popen(renderer->renderer, "w");
516                 if (p != NULL) {
517                         size_t count;
518                         
519                         while ((count =
520                                 fread(buf, sizeof(char), sizeof(buf),
521                                       tmpfp)) > 0)
522                                 fwrite(buf, sizeof(char), count, p);
523                         pclose(p);
524                 }
525                 
526                 dup2(oldout, 1);
527         } else if (mimeinfo->type == MIMETYPE_TEXT && !g_strcasecmp(mimeinfo->subtype, "html")) {
528                 HTMLParser *parser;
529                 CodeConverter *conv;
530
531                 conv = conv_code_converter_new(src_codeset);
532                 parser = html_parser_new(tmpfp, conv);
533                 while ((str = html_parse(parser)) != NULL) {
534                         fputs(str, outfp);
535                 }
536                 html_parser_destroy(parser);
537                 conv_code_converter_destroy(conv);
538         } else if (mimeinfo->type == MIMETYPE_TEXT && !g_strcasecmp(mimeinfo->subtype, "enriched")) {
539                 ERTFParser *parser;
540                 CodeConverter *conv;
541
542                 conv = conv_code_converter_new(src_codeset);
543                 parser = ertf_parser_new(tmpfp, conv);
544                 while ((str = ertf_parse(parser)) != NULL) {
545                         fputs(str, outfp);
546                 }
547                 ertf_parser_destroy(parser);
548                 conv_code_converter_destroy(conv);
549         } else if (mimeinfo->type == MIMETYPE_TEXT) {
550                 while (fgets(buf, sizeof(buf), tmpfp) != NULL) {
551                         str = conv_codeset_strdup(buf, src_codeset, NULL);
552                         if (str) {
553                                 fputs(str, outfp);
554                                 g_free(str);
555                         } else {
556                                 conv_fail = TRUE;
557                                 fputs(buf, outfp);
558                         }
559                 }
560         }
561
562         if (conv_fail)
563                 g_warning("procmime_get_text_content(): Code conversion failed.\n");
564
565         fclose(tmpfp);
566         rewind(outfp);
567         unlink(tmpfile);
568         g_free(tmpfile);
569
570         return outfp;
571 }
572
573 /* search the first text part of (multipart) MIME message,
574    decode, convert it and output to outfp. */
575 FILE *procmime_get_first_text_content(MsgInfo *msginfo)
576 {
577         FILE *outfp = NULL;
578         MimeInfo *mimeinfo, *partinfo;
579
580         g_return_val_if_fail(msginfo != NULL, NULL);
581
582         mimeinfo = procmime_scan_message(msginfo);
583         if (!mimeinfo) return NULL;
584
585         partinfo = mimeinfo;
586         while (partinfo && partinfo->type != MIMETYPE_TEXT)
587                 partinfo = procmime_mimeinfo_next(partinfo);
588
589         if (partinfo)
590                 outfp = procmime_get_text_content(partinfo);
591
592         procmime_mimeinfo_free_all(mimeinfo);
593
594         return outfp;
595 }
596
597 gboolean procmime_find_string_part(MimeInfo *mimeinfo, const gchar *filename,
598                                    const gchar *str, gboolean case_sens)
599 {
600         return FALSE;
601
602 #if 0   /* FIXME */
603         FILE *infp, *outfp;
604         gchar buf[BUFFSIZE];
605         gchar *(* StrFindFunc) (const gchar *haystack, const gchar *needle);
606
607         g_return_val_if_fail(mimeinfo != NULL, FALSE);
608         g_return_val_if_fail(mimeinfo->mime_type == MIME_TEXT ||
609                              mimeinfo->mime_type == MIME_TEXT_HTML ||
610                              mimeinfo->mime_type == MIME_TEXT_ENRICHED, FALSE);
611         g_return_val_if_fail(str != NULL, FALSE);
612
613         if ((infp = fopen(filename, "rb")) == NULL) {
614                 FILE_OP_ERROR(filename, "fopen");
615                 return FALSE;
616         }
617
618         outfp = procmime_get_text_content(mimeinfo, infp);
619         fclose(infp);
620
621         if (!outfp)
622                 return FALSE;
623
624         if (case_sens)
625                 StrFindFunc = strstr;
626         else
627                 StrFindFunc = strcasestr;
628
629         while (fgets(buf, sizeof(buf), outfp) != NULL) {
630                 if (StrFindFunc(buf, str) != NULL) {
631                         fclose(outfp);
632                         return TRUE;
633                 }
634         }
635
636         fclose(outfp);
637
638         return FALSE;
639 #endif
640 }
641
642 gboolean procmime_find_string(MsgInfo *msginfo, const gchar *str,
643                               gboolean case_sens)
644 {
645         return FALSE;
646
647 #if 0   /* FIXME */
648         MimeInfo *mimeinfo;
649         MimeInfo *partinfo;
650         gchar *filename;
651         gboolean found = FALSE;
652
653         g_return_val_if_fail(msginfo != NULL, FALSE);
654         g_return_val_if_fail(str != NULL, FALSE);
655
656         filename = procmsg_get_message_file(msginfo);
657         if (!filename) return FALSE;
658         mimeinfo = procmime_scan_message(msginfo);
659
660         for (partinfo = mimeinfo; partinfo != NULL;
661              partinfo = procmime_mimeinfo_next(partinfo)) {
662                 if (partinfo->mime_type == MIME_TEXT ||
663                     partinfo->mime_type == MIME_TEXT_HTML ||
664                     partinfo->mime_type == MIME_TEXT_ENRICHED) {
665                         if (procmime_find_string_part
666                                 (partinfo, filename, str, case_sens) == TRUE) {
667                                 found = TRUE;
668                                 break;
669                         }
670                 }
671         }
672
673         procmime_mimeinfo_free_all(mimeinfo);
674         g_free(filename);
675
676         return found;
677 #endif
678 }
679
680 gchar *procmime_get_tmp_file_name(MimeInfo *mimeinfo)
681 {
682         static guint32 id = 0;
683         gchar *base;
684         gchar *filename;
685         gchar f_prefix[10];
686
687         g_return_val_if_fail(mimeinfo != NULL, NULL);
688
689         g_snprintf(f_prefix, sizeof(f_prefix), "%08x.", id++);
690
691         if ((mimeinfo->type == MIMETYPE_TEXT) && !g_strcasecmp(mimeinfo->subtype, "html"))
692                 base = "mimetmp.html";
693         else {
694                 base = mimeinfo->filename ? mimeinfo->filename
695                         : mimeinfo->name ? mimeinfo->name : "mimetmp";
696                 base = g_basename(base);
697                 if (*base == '\0') base = "mimetmp";
698                 Xstrdup_a(base, base, return NULL);
699                 subst_for_filename(base);
700         }
701
702         filename = g_strconcat(get_mime_tmp_dir(), G_DIR_SEPARATOR_S,
703                                f_prefix, base, NULL);
704
705         return filename;
706 }
707
708 static GList *mime_type_list = NULL;
709
710 gchar *procmime_get_mime_type(const gchar *filename)
711 {
712         static GHashTable *mime_type_table = NULL;
713         MimeType *mime_type;
714         const gchar *p;
715         gchar *ext;
716
717         if (!mime_type_table) {
718                 mime_type_table = procmime_get_mime_type_table();
719                 if (!mime_type_table) return NULL;
720         }
721
722         filename = g_basename(filename);
723         p = strrchr(filename, '.');
724         if (!p) return NULL;
725
726         Xstrdup_a(ext, p + 1, return NULL);
727         g_strdown(ext);
728         mime_type = g_hash_table_lookup(mime_type_table, ext);
729         if (mime_type) {
730                 gchar *str;
731
732                 str = g_strconcat(mime_type->type, "/", mime_type->sub_type,
733                                   NULL);
734                 return str;
735         }
736
737         return NULL;
738 }
739
740 static guint procmime_str_hash(gconstpointer gptr)
741 {
742         guint hash_result = 0;
743         const char *str;
744
745         for (str = gptr; str && *str; str++) {
746                 if (isupper(*str)) hash_result += (*str + ' ');
747                 else hash_result += *str;
748         }
749
750         return hash_result;
751 }
752
753 static gint procmime_str_equal(gconstpointer gptr1, gconstpointer gptr2)
754 {
755         const char *str1 = gptr1;
756         const char *str2 = gptr2;
757
758         return !strcasecmp(str1, str2);
759 }
760
761 static GHashTable *procmime_get_mime_type_table(void)
762 {
763         GHashTable *table = NULL;
764         GList *cur;
765         MimeType *mime_type;
766         gchar **exts;
767
768         if (!mime_type_list) {
769                 mime_type_list = procmime_get_mime_type_list();
770                 if (!mime_type_list) return NULL;
771         }
772
773         table = g_hash_table_new(procmime_str_hash, procmime_str_equal);
774
775         for (cur = mime_type_list; cur != NULL; cur = cur->next) {
776                 gint i;
777                 gchar *key;
778
779                 mime_type = (MimeType *)cur->data;
780
781                 if (!mime_type->extension) continue;
782
783                 exts = g_strsplit(mime_type->extension, " ", 16);
784                 for (i = 0; exts[i] != NULL; i++) {
785                         /* make the key case insensitive */
786                         g_strdown(exts[i]);
787                         /* use previously dup'd key on overwriting */
788                         if (g_hash_table_lookup(table, exts[i]))
789                                 key = exts[i];
790                         else
791                                 key = g_strdup(exts[i]);
792                         g_hash_table_insert(table, key, mime_type);
793                 }
794                 g_strfreev(exts);
795         }
796
797         return table;
798 }
799
800 GList *procmime_get_mime_type_list(void)
801 {
802         GList *list = NULL;
803         FILE *fp;
804         gchar buf[BUFFSIZE];
805         gchar *p, *delim;
806         MimeType *mime_type;
807
808         if (mime_type_list) 
809                 return mime_type_list;
810
811         if ((fp = fopen("/etc/mime.types", "rb")) == NULL) {
812                 if ((fp = fopen(SYSCONFDIR "/mime.types", "rb")) == NULL) {
813                         FILE_OP_ERROR(SYSCONFDIR "/mime.types", "fopen");
814                         return NULL;
815                 }
816         }
817
818         while (fgets(buf, sizeof(buf), fp) != NULL) {
819                 p = strchr(buf, '#');
820                 if (p) *p = '\0';
821                 g_strstrip(buf);
822
823                 p = buf;
824                 while (*p && !isspace(*p)) p++;
825                 if (*p) {
826                         *p = '\0';
827                         p++;
828                 }
829                 delim = strchr(buf, '/');
830                 if (delim == NULL) continue;
831                 *delim = '\0';
832
833                 mime_type = g_new(MimeType, 1);
834                 mime_type->type = g_strdup(buf);
835                 mime_type->sub_type = g_strdup(delim + 1);
836
837                 while (*p && isspace(*p)) p++;
838                 if (*p)
839                         mime_type->extension = g_strdup(p);
840                 else
841                         mime_type->extension = NULL;
842
843                 list = g_list_append(list, mime_type);
844         }
845
846         fclose(fp);
847
848         if (!list)
849                 g_warning("Can't read mime.types\n");
850
851         return list;
852 }
853
854 EncodingType procmime_get_encoding_for_charset(const gchar *charset)
855 {
856         if (!charset)
857                 return ENC_8BIT;
858         else if (!strncasecmp(charset, "ISO-2022-", 9) ||
859                  !strcasecmp(charset, "US-ASCII"))
860                 return ENC_7BIT;
861         else if (!strcasecmp(charset, "ISO-8859-5") ||
862                  !strncasecmp(charset, "KOI8-", 5) ||
863                  !strcasecmp(charset, "Windows-1251"))
864                 return ENC_8BIT;
865         else if (!strncasecmp(charset, "ISO-8859-", 9))
866                 return ENC_QUOTED_PRINTABLE;
867         else
868                 return ENC_8BIT;
869 }
870
871 EncodingType procmime_get_encoding_for_file(const gchar *file)
872 {
873         FILE *fp;
874         guchar buf[BUFSIZ];
875         size_t len;
876
877         if ((fp = fopen(file, "rb")) == NULL) {
878                 FILE_OP_ERROR(file, "fopen");
879                 return ENC_UNKNOWN;
880         }
881
882         while ((len = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
883                 guchar *p;
884                 gint i;
885
886                 for (p = buf, i = 0; i < len; p++, i++) {
887                         if (*p & 0x80) {
888                                 fclose(fp);
889                                 return ENC_BASE64;
890                         }
891                 }
892         }
893
894         fclose(fp);
895         return ENC_7BIT;
896 }
897
898 struct EncodingTable 
899 {
900         gchar *str;
901         EncodingType enc_type;
902 };
903
904 struct EncodingTable encoding_table[] = {
905         {"7bit", ENC_7BIT},
906         {"8bit", ENC_8BIT},
907         {"binary", ENC_BINARY},
908         {"quoted-printable", ENC_QUOTED_PRINTABLE},
909         {"base64", ENC_BASE64},
910         {"x-uuencode", ENC_UNKNOWN},
911         {NULL, ENC_UNKNOWN},
912 };
913
914 const gchar *procmime_get_encoding_str(EncodingType encoding)
915 {
916         struct EncodingTable *enc_table;
917         
918         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
919                 if (enc_table->enc_type == encoding)
920                         return enc_table->str;
921         }
922         return NULL;
923 }
924
925 /* --- NEW MIME STUFF --- */
926 struct TypeTable
927 {
928         gchar *str;
929         MimeMediaType type;
930 };
931
932 static struct TypeTable mime_type_table[] = {
933         {"text", MIMETYPE_TEXT},
934         {"image", MIMETYPE_IMAGE},
935         {"audio", MIMETYPE_AUDIO},
936         {"video", MIMETYPE_VIDEO},
937         {"application", MIMETYPE_APPLICATION},
938         {"message", MIMETYPE_MESSAGE},
939         {"multipart", MIMETYPE_MULTIPART},
940         {NULL, 0},
941 };
942
943 const gchar *procmime_get_type_str(MimeMediaType type)
944 {
945         struct TypeTable *type_table;
946         
947         for (type_table = mime_type_table; type_table->str != NULL; type_table++) {
948                 if (type_table->type == type)
949                         return type_table->str;
950         }
951         return NULL;
952 }
953
954 void procmime_parse_mimepart(MimeInfo *parent,
955                              gchar *content_type,
956                              gchar *content_encoding,
957                              gchar *content_description,
958                              gchar *content_id,
959                              FILE *fp,
960                              const gchar *filename,
961                              guint offset,
962                              guint length);
963
964 void procmime_parse_message_rfc822(MimeInfo *mimeinfo, FILE *fp)
965 {
966         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
967                                 {"Content-Transfer-Encoding:",
968                                                    NULL, FALSE},
969                                 {"Content-Description:",
970                                                    NULL, TRUE},
971                                 {"Content-ID:",
972                                                    NULL, TRUE},
973                                 {NULL,             NULL, FALSE}};
974         guint content_start, i;
975
976         fseek(fp, mimeinfo->offset, SEEK_SET);
977         procheader_get_header_fields(fp, hentry);
978         content_start = ftell(fp);
979
980         procmime_parse_mimepart(mimeinfo,
981                                 hentry[0].body, hentry[1].body,
982                                 hentry[2].body, hentry[3].body, 
983                                 fp, mimeinfo->filename, content_start,
984                                 mimeinfo->length - (content_start - mimeinfo->offset));
985         for (i = 0; i < 4; i++) {
986                 g_free(hentry[i].body);
987                 hentry[i].body = NULL;
988         }
989 }
990
991 void procmime_parse_multipart(MimeInfo *mimeinfo, FILE *fp)
992 {
993         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
994                                 {"Content-Transfer-Encoding:",
995                                                    NULL, FALSE},
996                                 {"Content-Description:",
997                                                    NULL, TRUE},
998                                 {"Content-ID:",
999                                                    NULL, TRUE},
1000                                 {NULL,             NULL, FALSE}};
1001         gchar *p;
1002         gchar *boundary;
1003         gint boundary_len = 0, lastoffset = -1, i;
1004         gchar buf[BUFFSIZE];
1005
1006         boundary = g_hash_table_lookup(mimeinfo->parameters, "boundary");
1007         if(!boundary)
1008                 return;
1009         boundary_len = strlen(boundary);
1010
1011         fseek(fp, mimeinfo->offset, SEEK_SET);
1012         while ((p = fgets(buf, sizeof(buf), fp)) != NULL) {
1013                 if (ftell(fp) > (mimeinfo->offset + mimeinfo->length))
1014                         break;
1015
1016                 if (IS_BOUNDARY(buf, boundary, boundary_len)) {
1017                         if(lastoffset != -1) {
1018                                 procmime_parse_mimepart(mimeinfo,
1019                                                         hentry[0].body, hentry[1].body,
1020                                                         hentry[2].body, hentry[3].body, 
1021                                                         fp, mimeinfo->filename, lastoffset,
1022                                                         (ftell(fp) - strlen(buf)) - lastoffset);
1023                         }
1024                         
1025                         if (buf[2 + boundary_len]     == '-' &&
1026                             buf[2 + boundary_len + 1] == '-')
1027                                 break;
1028
1029                         for (i = 0; i < 4; i++) {
1030                                 g_free(hentry[i].body);
1031                                 hentry[i].body = NULL;
1032                         }
1033                         procheader_get_header_fields(fp, hentry);
1034                         lastoffset = ftell(fp);
1035                 }
1036         }
1037 }
1038
1039 static void procmime_parse_content_type(const gchar *content_type, MimeInfo *mimeinfo)
1040 {
1041         gchar **content_type_parts;
1042         gchar **strarray;
1043         gchar *str;
1044         struct TypeTable *typetablearray;
1045         
1046         /* Split content type into parts and remove trailing
1047            and leading whitespaces from all strings */
1048         content_type_parts = g_strsplit(content_type, ";", 0);
1049         for (strarray = content_type_parts; *strarray != NULL; strarray++) {
1050                 g_strstrip(*strarray);
1051         }
1052
1053         /* Get mimeinfo->type and mimeinfo->subtype */
1054         mimeinfo->type = MIMETYPE_UNKNOWN;
1055         str = content_type_parts[0];
1056         for (typetablearray = mime_type_table; typetablearray->str != NULL; typetablearray++) {
1057                 if (g_strncasecmp(str, typetablearray->str, strlen(typetablearray->str)) == 0 &&
1058                     str[strlen(typetablearray->str)] == '/') {
1059                         mimeinfo->type = typetablearray->type;
1060                         mimeinfo->subtype = g_strdup(str + strlen(typetablearray->str) + 1);
1061                         break;
1062                 }
1063         }
1064
1065         /* Get mimeinfo->parmeters */
1066         for (strarray = &content_type_parts[1]; *strarray != NULL; strarray++) {
1067                 gchar **parameters_parts;
1068
1069                 parameters_parts = g_strsplit(*strarray, "=", 1);
1070                 if ((parameters_parts[0] != NULL) && (parameters_parts[1] != NULL)) {
1071                         g_strdown(parameters_parts[0]);
1072                         if(parameters_parts[1][0] == '"')
1073                                 extract_quote(parameters_parts[1], '"');
1074
1075                         g_hash_table_insert(mimeinfo->parameters,
1076                                             g_strdup(parameters_parts[0]),
1077                                             g_strdup(parameters_parts[1]));
1078                 }
1079                 g_strfreev(parameters_parts);
1080         }
1081
1082         g_strfreev(content_type_parts);
1083 }
1084
1085 static void procmime_parse_content_encoding(const gchar *content_encoding, MimeInfo *mimeinfo)
1086 {
1087         struct EncodingTable *enc_table;
1088         
1089         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1090                 if (g_strcasecmp(enc_table->str, content_encoding) == 0) {
1091                         mimeinfo->encoding_type = enc_table->enc_type;
1092                         return;
1093                 }
1094         }
1095         mimeinfo->encoding_type = ENC_UNKNOWN;
1096         return;
1097 }
1098
1099 void procmime_parse_mimepart(MimeInfo *parent,
1100                              gchar *content_type,
1101                              gchar *content_encoding,
1102                              gchar *content_description,
1103                              gchar *content_id,
1104                              FILE *fp,
1105                              const gchar *filename,
1106                              guint offset,
1107                              guint length)
1108 {
1109         MimeInfo *mimeinfo;
1110         guint oldpos;
1111
1112         g_return_if_fail(fp != NULL);
1113
1114         /* Create MimeInfo */
1115         mimeinfo = procmime_mimeinfo_new();
1116         if (parent != NULL)
1117                 g_node_append(parent->node, mimeinfo->node);
1118         mimeinfo->filename = g_strdup(filename);
1119         mimeinfo->offset = offset;
1120         mimeinfo->length = length;
1121
1122         if (content_type != NULL) {
1123                 procmime_parse_content_type(content_type, mimeinfo);
1124         } else {
1125                 mimeinfo->type = MIMETYPE_TEXT;
1126                 mimeinfo->subtype = g_strdup("plain");
1127                 g_hash_table_insert(mimeinfo->parameters, g_strdup("charset"), g_strdup("us-ascii"));
1128         }
1129
1130         if (content_encoding != NULL) {
1131                 procmime_parse_content_encoding(content_encoding, mimeinfo);
1132         } else {
1133                 mimeinfo->encoding_type = ENC_7BIT;
1134         }
1135
1136         if (content_description != NULL)
1137                 mimeinfo->description = g_strdup(content_description);
1138         else
1139                 mimeinfo->description = NULL;
1140
1141         if (content_id != NULL)
1142                 mimeinfo->id = g_strdup(content_id);
1143         else
1144                 mimeinfo->id = NULL;
1145
1146         oldpos = ftell(fp);
1147         /* Call parser for mime type */
1148         switch (mimeinfo->type) {
1149                 case MIMETYPE_MESSAGE:
1150                         if (g_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
1151                                 procmime_parse_message_rfc822(mimeinfo, fp);
1152                         }
1153                         break;
1154                         
1155                 case MIMETYPE_MULTIPART:
1156                         procmime_parse_multipart(mimeinfo, fp);
1157                         break;
1158                         
1159                 default:
1160                         break;
1161         }
1162         fseek(fp, oldpos, SEEK_SET);
1163 }
1164
1165 static gchar *typenames[] = {
1166     "text",
1167     "image",
1168     "audio",
1169     "video",
1170     "application",
1171     "message",
1172     "multipart",
1173     "unknown",
1174 };
1175
1176 static gboolean output_func(GNode *node, gpointer data)
1177 {
1178         guint i, depth;
1179         MimeInfo *mimeinfo = (MimeInfo *) node->data;
1180
1181         depth = g_node_depth(node);
1182         for(i = 0; i < depth; i++)
1183                 printf("    ");
1184         printf("%s/%s (offset:%d length:%d encoding: %d)\n", typenames[mimeinfo->type], mimeinfo->subtype, mimeinfo->offset, mimeinfo->length, mimeinfo->encoding_type);
1185
1186         return FALSE;
1187 }
1188
1189 static void output_mime_structure(MimeInfo *mimeinfo, int indent)
1190 {
1191         g_node_traverse(mimeinfo->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1, output_func, NULL);
1192 }
1193
1194 MimeInfo *procmime_scan_fp(FILE *fp, const gchar *filename)
1195 {
1196         MimeInfo *mimeinfo;
1197         gint offset;
1198         struct stat stat;
1199
1200         fstat(fileno(fp), &stat);
1201         offset = ftell(fp);
1202
1203         mimeinfo = procmime_mimeinfo_new();
1204         mimeinfo->type = MIMETYPE_MESSAGE;
1205         mimeinfo->subtype = g_strdup("rfc822");
1206         mimeinfo->filename = g_strdup(filename);
1207         mimeinfo->offset = offset;
1208         mimeinfo->length = stat.st_size - offset;
1209
1210         procmime_parse_message_rfc822(mimeinfo, fp);
1211         output_mime_structure(mimeinfo, 0);
1212
1213         return mimeinfo;
1214 }
1215
1216 MimeInfo *procmime_scan_file(gchar *filename)
1217 {
1218         FILE *fp;
1219         MimeInfo *mimeinfo;
1220
1221         g_return_val_if_fail(filename != NULL, NULL);
1222
1223         /* Open file */
1224         if((fp = fopen(filename, "rb")) == NULL)
1225                 return NULL;
1226
1227         mimeinfo = procmime_scan_fp(fp, filename);
1228
1229         fclose(fp);
1230
1231         return mimeinfo;
1232 }
1233
1234 MimeInfo *procmime_scan_queue_file(gchar *filename)
1235 {
1236         FILE *fp;
1237         MimeInfo *mimeinfo;
1238         gchar buf[BUFFSIZE];
1239
1240         g_return_val_if_fail(filename != NULL, NULL);
1241
1242         /* Open file */
1243         if((fp = fopen(filename, "rb")) == NULL)
1244                 return NULL;
1245
1246         /* Skip queue header */
1247         while (fgets(buf, sizeof(buf), fp) != NULL)
1248                 if (buf[0] == '\r' || buf[0] == '\n') break;
1249
1250         mimeinfo = procmime_scan_fp(fp, filename);
1251
1252         fclose(fp);
1253
1254         return mimeinfo;
1255 }