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