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