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