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