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