* src/carray.h
[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         const 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                              const gchar *filename,
960                              guint offset,
961                              guint length);
962
963 void procmime_parse_message_rfc822(MimeInfo *mimeinfo)
964 {
965         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
966                                 {"Content-Transfer-Encoding:",
967                                                    NULL, FALSE},
968                                 {"Content-Description:",
969                                                    NULL, TRUE},
970                                 {"Content-ID:",
971                                                    NULL, TRUE},
972                                 {NULL,             NULL, FALSE}};
973         guint content_start, i;
974         FILE *fp;
975
976         if(mimeinfo->encoding_type != ENC_BINARY && 
977            mimeinfo->encoding_type != ENC_7BIT && 
978            mimeinfo->encoding_type != ENC_8BIT)
979                 procmime_decode_content(mimeinfo);
980
981         fp = fopen(mimeinfo->filename, "rb");
982         fseek(fp, mimeinfo->offset, SEEK_SET);
983         procheader_get_header_fields(fp, hentry);
984         content_start = ftell(fp);
985         fclose(fp);
986
987         procmime_parse_mimepart(mimeinfo,
988                                 hentry[0].body, hentry[1].body,
989                                 hentry[2].body, hentry[3].body, 
990                                 mimeinfo->filename, content_start,
991                                 mimeinfo->length - (content_start - mimeinfo->offset));
992         for (i = 0; i < 4; i++) {
993                 g_free(hentry[i].body);
994                 hentry[i].body = NULL;
995         }
996 }
997
998 void procmime_parse_multipart(MimeInfo *mimeinfo)
999 {
1000         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1001                                 {"Content-Transfer-Encoding:",
1002                                                    NULL, FALSE},
1003                                 {"Content-Description:",
1004                                                    NULL, TRUE},
1005                                 {"Content-ID:",
1006                                                    NULL, TRUE},
1007                                 {NULL,             NULL, FALSE}};
1008         gchar *p;
1009         gchar *boundary;
1010         gint boundary_len = 0, lastoffset = -1, i;
1011         gchar buf[BUFFSIZE];
1012         FILE *fp;
1013
1014         boundary = g_hash_table_lookup(mimeinfo->parameters, "boundary");
1015         if(!boundary)
1016                 return;
1017         boundary_len = strlen(boundary);
1018
1019         if(mimeinfo->encoding_type != ENC_BINARY && 
1020            mimeinfo->encoding_type != ENC_7BIT && 
1021            mimeinfo->encoding_type != ENC_8BIT)
1022                 procmime_decode_content(mimeinfo);
1023
1024         fp = fopen(mimeinfo->filename, "rb");
1025         fseek(fp, mimeinfo->offset, SEEK_SET);
1026         while ((p = fgets(buf, sizeof(buf), fp)) != NULL) {
1027                 if (ftell(fp) > (mimeinfo->offset + mimeinfo->length))
1028                         break;
1029
1030                 if (IS_BOUNDARY(buf, boundary, boundary_len)) {
1031                         if(lastoffset != -1) {
1032                                 procmime_parse_mimepart(mimeinfo,
1033                                                         hentry[0].body, hentry[1].body,
1034                                                         hentry[2].body, hentry[3].body, 
1035                                                         mimeinfo->filename, lastoffset,
1036                                                         (ftell(fp) - strlen(buf)) - lastoffset);
1037                         }
1038                         
1039                         if (buf[2 + boundary_len]     == '-' &&
1040                             buf[2 + boundary_len + 1] == '-')
1041                                 break;
1042
1043                         for (i = 0; i < 4; i++) {
1044                                 g_free(hentry[i].body);
1045                                 hentry[i].body = NULL;
1046                         }
1047                         procheader_get_header_fields(fp, hentry);
1048                         lastoffset = ftell(fp);
1049                 }
1050         }
1051         fclose(fp);
1052 }
1053
1054 static void procmime_parse_content_type(const gchar *content_type, MimeInfo *mimeinfo)
1055 {
1056         gchar **content_type_parts;
1057         gchar **strarray;
1058         gchar *str;
1059         struct TypeTable *typetablearray;
1060         
1061         /* Split content type into parts and remove trailing
1062            and leading whitespaces from all strings */
1063         content_type_parts = g_strsplit(content_type, ";", 0);
1064         for (strarray = content_type_parts; *strarray != NULL; strarray++) {
1065                 g_strstrip(*strarray);
1066         }
1067
1068         /* Get mimeinfo->type and mimeinfo->subtype */
1069         mimeinfo->type = MIMETYPE_UNKNOWN;
1070         str = content_type_parts[0];
1071         for (typetablearray = mime_type_table; typetablearray->str != NULL; typetablearray++) {
1072                 if (g_strncasecmp(str, typetablearray->str, strlen(typetablearray->str)) == 0 &&
1073                     str[strlen(typetablearray->str)] == '/') {
1074                         mimeinfo->type = typetablearray->type;
1075                         mimeinfo->subtype = g_strdup(str + strlen(typetablearray->str) + 1);
1076                         break;
1077                 }
1078         }
1079
1080         /* Get mimeinfo->parmeters */
1081         for (strarray = &content_type_parts[1]; *strarray != NULL; strarray++) {
1082                 gchar **parameters_parts;
1083
1084                 parameters_parts = g_strsplit(*strarray, "=", 1);
1085                 if ((parameters_parts[0] != NULL) && (parameters_parts[1] != NULL)) {
1086                         g_strdown(parameters_parts[0]);
1087                         if(parameters_parts[1][0] == '"')
1088                                 extract_quote(parameters_parts[1], '"');
1089
1090                         g_hash_table_insert(mimeinfo->parameters,
1091                                             g_strdup(parameters_parts[0]),
1092                                             g_strdup(parameters_parts[1]));
1093                 }
1094                 g_strfreev(parameters_parts);
1095         }
1096
1097         g_strfreev(content_type_parts);
1098 }
1099
1100 static void procmime_parse_content_encoding(const gchar *content_encoding, MimeInfo *mimeinfo)
1101 {
1102         struct EncodingTable *enc_table;
1103         
1104         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1105                 if (g_strcasecmp(enc_table->str, content_encoding) == 0) {
1106                         mimeinfo->encoding_type = enc_table->enc_type;
1107                         return;
1108                 }
1109         }
1110         mimeinfo->encoding_type = ENC_UNKNOWN;
1111         return;
1112 }
1113
1114 void procmime_parse_mimepart(MimeInfo *parent,
1115                              gchar *content_type,
1116                              gchar *content_encoding,
1117                              gchar *content_description,
1118                              gchar *content_id,
1119                              const gchar *filename,
1120                              guint offset,
1121                              guint length)
1122 {
1123         MimeInfo *mimeinfo;
1124
1125         /* Create MimeInfo */
1126         mimeinfo = procmime_mimeinfo_new();
1127         if (parent != NULL)
1128                 g_node_append(parent->node, mimeinfo->node);
1129         mimeinfo->filename = g_strdup(filename);
1130         mimeinfo->offset = offset;
1131         mimeinfo->length = length;
1132
1133         if (content_type != NULL) {
1134                 procmime_parse_content_type(content_type, mimeinfo);
1135         } else {
1136                 mimeinfo->type = MIMETYPE_TEXT;
1137                 mimeinfo->subtype = g_strdup("plain");
1138                 g_hash_table_insert(mimeinfo->parameters, g_strdup("charset"), g_strdup("us-ascii"));
1139         }
1140
1141         if (content_encoding != NULL) {
1142                 procmime_parse_content_encoding(content_encoding, mimeinfo);
1143         } else {
1144                 mimeinfo->encoding_type = ENC_7BIT;
1145         }
1146
1147         if (content_description != NULL)
1148                 mimeinfo->description = g_strdup(content_description);
1149         else
1150                 mimeinfo->description = NULL;
1151
1152         if (content_id != NULL)
1153                 mimeinfo->id = g_strdup(content_id);
1154         else
1155                 mimeinfo->id = NULL;
1156
1157         /* Call parser for mime type */
1158         switch (mimeinfo->type) {
1159                 case MIMETYPE_MESSAGE:
1160                         if (g_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
1161                                 procmime_parse_message_rfc822(mimeinfo);
1162                         }
1163                         break;
1164                         
1165                 case MIMETYPE_MULTIPART:
1166                         procmime_parse_multipart(mimeinfo);
1167                         break;
1168                         
1169                 default:
1170                         break;
1171         }
1172 }
1173
1174 static gchar *typenames[] = {
1175     "text",
1176     "image",
1177     "audio",
1178     "video",
1179     "application",
1180     "message",
1181     "multipart",
1182     "unknown",
1183 };
1184
1185 static gboolean output_func(GNode *node, gpointer data)
1186 {
1187         guint i, depth;
1188         MimeInfo *mimeinfo = (MimeInfo *) node->data;
1189
1190         depth = g_node_depth(node);
1191         for(i = 0; i < depth; i++)
1192                 printf("    ");
1193         printf("%s/%s (offset:%d length:%d encoding: %d)\n", typenames[mimeinfo->type], mimeinfo->subtype, mimeinfo->offset, mimeinfo->length, mimeinfo->encoding_type);
1194
1195         return FALSE;
1196 }
1197
1198 static void output_mime_structure(MimeInfo *mimeinfo, int indent)
1199 {
1200         g_node_traverse(mimeinfo->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1, output_func, NULL);
1201 }
1202
1203 static MimeInfo *procmime_scan_file_with_offset(const gchar *filename, int offset)
1204 {
1205         MimeInfo *mimeinfo;
1206         struct stat buf;
1207
1208         stat(filename, &buf);
1209
1210         mimeinfo = procmime_mimeinfo_new();
1211         mimeinfo->encoding_type = ENC_BINARY;
1212         mimeinfo->type = MIMETYPE_MESSAGE;
1213         mimeinfo->subtype = g_strdup("rfc822");
1214         mimeinfo->filename = g_strdup(filename);
1215         mimeinfo->offset = offset;
1216         mimeinfo->length = buf.st_size - offset;
1217
1218         procmime_parse_message_rfc822(mimeinfo);
1219         output_mime_structure(mimeinfo, 0);
1220
1221         return mimeinfo;
1222 }
1223
1224 MimeInfo *procmime_scan_file(gchar *filename)
1225 {
1226         MimeInfo *mimeinfo;
1227
1228         g_return_val_if_fail(filename != NULL, NULL);
1229
1230         mimeinfo = procmime_scan_file_with_offset(filename, 0);
1231
1232         return mimeinfo;
1233 }
1234
1235 MimeInfo *procmime_scan_queue_file(gchar *filename)
1236 {
1237         FILE *fp;
1238         MimeInfo *mimeinfo;
1239         gchar buf[BUFFSIZE];
1240         gint offset = 0;
1241
1242         g_return_val_if_fail(filename != NULL, NULL);
1243
1244         /* Open file */
1245         if((fp = fopen(filename, "rb")) == NULL)
1246                 return NULL;
1247         /* Skip queue header */
1248         while (fgets(buf, sizeof(buf), fp) != NULL)
1249                 if (buf[0] == '\r' || buf[0] == '\n') break;
1250         offset = ftell(fp);
1251         fclose(fp);
1252
1253         mimeinfo = procmime_scan_file_with_offset(filename, offset);
1254
1255         return mimeinfo;
1256 }