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