fix bug "[ 537413 ] false varification of pgp-signature"
[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;
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                                 /*pgp signatures should NOT have a name */
407                                 if (strcasecmp(mimeinfo->content_type, "application/pgp-signature"))
408                                         mimeinfo->name = g_strdup(tmp);
409                         } else if (!strcasecmp(attr, "boundary"))
410                                 mimeinfo->boundary = g_strdup(value);
411                 }
412
413                 if (!delim) break;
414                 p = delim + 1;
415         }
416
417         if (mimeinfo->mime_type == MIME_MULTIPART && !mimeinfo->boundary)
418                 mimeinfo->mime_type = MIME_TEXT;
419 }
420
421 void procmime_scan_content_disposition(MimeInfo *mimeinfo,
422                                        const gchar *content_disposition)
423 {
424         gchar *delim, *p, *dispos;
425         gchar *buf;
426
427         if (conv_get_current_charset() == C_EUC_JP &&
428             strchr(content_disposition, '\033')) {
429                 gint len;
430                 len = strlen(content_disposition) * 2 + 1;
431                 Xalloca(buf, len, return);
432                 conv_jistoeuc(buf, len, content_disposition);
433         } else
434                 Xstrdup_a(buf, content_disposition, return);
435
436         if ((delim = strchr(buf, ';'))) *delim = '\0';
437         mimeinfo->content_disposition = dispos = g_strdup(g_strstrip(buf));
438
439         if (!delim) return;
440         p = delim + 1;
441
442         for (;;) {
443                 gchar *eq;
444                 gchar *attr, *value;
445
446                 if ((delim = strchr(p, ';'))) *delim = '\0';
447
448                 if (!(eq = strchr(p, '='))) break;
449
450                 *eq = '\0';
451                 attr = p;
452                 g_strstrip(attr);
453                 value = eq + 1;
454                 g_strstrip(value);
455
456                 if (*value == '"')
457                         extract_quote(value, '"');
458                 else {
459                         eliminate_parenthesis(value, '(', ')');
460                         g_strstrip(value);
461                 }
462
463                 if (*value) {
464                         if (!strcasecmp(attr, "filename")) {
465                                 gchar *tmp;
466                                 size_t len;
467
468                                 len = strlen(value) + 1;
469                                 Xalloca(tmp, len, return);
470                                 conv_unmime_header(tmp, len, value, NULL);
471                                 g_free(mimeinfo->filename);
472                                 /*pgp signatures should NOT have a name */
473                                 if (strcasecmp(mimeinfo->content_type, "application/pgp-signature"))
474                                         mimeinfo->filename = g_strdup(tmp);
475                                 break;
476                         }
477                 }
478
479                 if (!delim) break;
480                 p = delim + 1;
481         }
482 }
483
484 void procmime_scan_content_description(MimeInfo *mimeinfo,
485                                        const gchar *content_description)
486 {
487         gchar *buf;
488
489         gchar *tmp;
490         size_t blen;
491
492         if (conv_get_current_charset() == C_EUC_JP &&
493             strchr(content_description, '\033')) {
494                 gint len;
495                 len = strlen(content_description) * 2 + 1;
496                 Xalloca(buf, len, return);
497                 conv_jistoeuc(buf, len, content_description);
498         } else
499                 Xstrdup_a(buf, content_description, return);
500         
501         blen = strlen(buf) + 1;
502         Xalloca(tmp, blen, return);
503         conv_unmime_header(tmp, blen, buf, NULL);
504         g_free(mimeinfo->name);
505         /*pgp signatures should NOT have a name */
506         if (strcasecmp(mimeinfo->content_type, "application/pgp-signature"))
507                 mimeinfo->name = g_strdup(tmp);
508 }
509
510 void procmime_scan_subject(MimeInfo *mimeinfo,
511                            const gchar *subject)
512 {
513         gchar *buf;
514
515         gchar *tmp;
516         size_t blen;
517
518         if (conv_get_current_charset() == C_EUC_JP &&
519             strchr(subject, '\033')) {
520                 gint len;
521                 len = strlen(subject) * 2 + 1;
522                 Xalloca(buf, len, return);
523                 conv_jistoeuc(buf, len, subject);
524         } else
525                 Xstrdup_a(buf, subject, return);
526         
527         blen = strlen(buf) + 1;
528         Xalloca(tmp, blen, return);
529         conv_unmime_header(tmp, blen, buf, NULL);
530         g_free(mimeinfo->name);
531         mimeinfo->name = g_strdup(tmp);
532 }
533
534 enum
535 {
536         H_CONTENT_TRANSFER_ENCODING = 0,
537         H_CONTENT_TYPE              = 1,
538         H_CONTENT_DISPOSITION       = 2,
539         H_CONTENT_DESCRIPTION       = 3,
540         H_SUBJECT                   = 4
541 };
542
543 MimeInfo *procmime_scan_mime_header(FILE *fp)
544 {
545         static HeaderEntry hentry[] = {{"Content-Transfer-Encoding:",
546                                                           NULL, FALSE},
547                                        {"Content-Type:", NULL, TRUE},
548                                        {"Content-Disposition:",
549                                                           NULL, TRUE},
550                                        {"Content-description:",
551                                                           NULL, TRUE},
552                                        {"Subject:",
553                                                           NULL, TRUE},
554                                        {NULL,             NULL, FALSE}};
555         gchar buf[BUFFSIZE];
556         gint hnum;
557         HeaderEntry *hp;
558         MimeInfo *mimeinfo;
559
560         g_return_val_if_fail(fp != NULL, NULL);
561
562         mimeinfo = procmime_mimeinfo_new();
563         mimeinfo->mime_type = MIME_TEXT;
564         mimeinfo->encoding_type = ENC_7BIT;
565         mimeinfo->fpos = ftell(fp);
566
567         while ((hnum = procheader_get_one_field(buf, sizeof(buf), fp, hentry))
568                != -1) {
569                 hp = hentry + hnum;
570
571                 if (H_CONTENT_TRANSFER_ENCODING == hnum) {
572                         procmime_scan_encoding
573                                 (mimeinfo, buf + strlen(hp->name));
574                 } else if (H_CONTENT_TYPE == hnum) {
575                         procmime_scan_content_type
576                                 (mimeinfo, buf + strlen(hp->name));
577                 } else if (H_CONTENT_DISPOSITION == hnum) {
578                         procmime_scan_content_disposition
579                                 (mimeinfo, buf + strlen(hp->name));
580                 } else if (H_CONTENT_DESCRIPTION == hnum) {
581                         procmime_scan_content_description
582                                 (mimeinfo, buf + strlen(hp->name));
583                 } else if (H_SUBJECT == hnum) {
584                         procmime_scan_subject
585                                 (mimeinfo, buf + strlen(hp->name));
586                 }
587         }
588
589         if (mimeinfo->mime_type == MIME_APPLICATION_OCTET_STREAM &&
590             mimeinfo->name) {
591                 const gchar *type;
592                 type = procmime_get_mime_type(mimeinfo->name);
593                 if (type)
594                         mimeinfo->mime_type = procmime_scan_mime_type(type);
595         }
596
597         if (!mimeinfo->content_type)
598                         mimeinfo->content_type = g_strdup("text/plain");
599
600         return mimeinfo;
601 }
602
603 FILE *procmime_decode_content(FILE *outfp, FILE *infp, MimeInfo *mimeinfo)
604 {
605         gchar buf[BUFFSIZE];
606         gchar *boundary = NULL;
607         gint boundary_len = 0;
608         gboolean tmp_file = FALSE;
609
610         g_return_val_if_fail(infp != NULL, NULL);
611         g_return_val_if_fail(mimeinfo != NULL, NULL);
612
613         if (!outfp) {
614                 outfp = my_tmpfile();
615                 if (!outfp) {
616                         perror("tmpfile");
617                         return NULL;
618                 }
619                 tmp_file = TRUE;
620         }
621
622         if (mimeinfo->parent && mimeinfo->parent->boundary) {
623                 boundary = mimeinfo->parent->boundary;
624                 boundary_len = strlen(boundary);
625         }
626
627         if (mimeinfo->encoding_type == ENC_QUOTED_PRINTABLE) {
628                 while (fgets(buf, sizeof(buf), infp) != NULL &&
629                        (!boundary ||
630                         !IS_BOUNDARY(buf, boundary, boundary_len))) {
631                         gint len;
632                         len = unmime_quoted_printable_line(buf);
633                         fwrite(buf, len, 1, outfp);
634                 }
635         } else if (mimeinfo->encoding_type == ENC_BASE64) {
636                 gchar outbuf[BUFFSIZE];
637                 gint len;
638                 Base64Decoder *decoder;
639
640                 decoder = base64_decoder_new();
641                 while (fgets(buf, sizeof(buf), infp) != NULL &&
642                        (!boundary ||
643                         !IS_BOUNDARY(buf, boundary, boundary_len))) {
644                         len = base64_decoder_decode(decoder, buf, outbuf);
645                         if (len < 0) {
646                                 g_warning("Bad BASE64 content\n");
647                                 break;
648                         }
649                         fwrite(outbuf, sizeof(gchar), len, outfp);
650                 }
651                 base64_decoder_free(decoder);
652         } else if (mimeinfo->encoding_type == ENC_X_UUENCODE) {
653                 gchar outbuf[BUFFSIZE];
654                 gint len;
655                 gboolean flag = FALSE;
656
657                 while (fgets(buf, sizeof(buf), infp) != NULL &&
658                        (!boundary ||
659                         !IS_BOUNDARY(buf, boundary, boundary_len))) {
660                         if(!flag && strncmp(buf,"begin ", 6)) continue;
661
662                         if (flag) {
663                                 len = fromuutobits(outbuf, buf);
664                                 if (len <= 0) {
665                                         if (len < 0) 
666                                                 g_warning("Bad UUENCODE content(%d)\n", len);
667                                         break;
668                                 }
669                                 fwrite(outbuf, sizeof(gchar), len, outfp);
670                         } else
671                                 flag = TRUE;
672                 }
673         } else {
674                 while (fgets(buf, sizeof(buf), infp) != NULL &&
675                        (!boundary ||
676                         !IS_BOUNDARY(buf, boundary, boundary_len))) {
677                         fputs(buf, outfp);
678                 }
679         }
680
681         if (tmp_file) rewind(outfp);
682         return outfp;
683 }
684
685 gint procmime_get_part(const gchar *outfile, const gchar *infile,
686                        MimeInfo *mimeinfo)
687 {
688         FILE *infp, *outfp;
689         gchar buf[BUFFSIZE];
690
691         g_return_val_if_fail(outfile != NULL, -1);
692         g_return_val_if_fail(infile != NULL, -1);
693         g_return_val_if_fail(mimeinfo != NULL, -1);
694
695         if ((infp = fopen(infile, "rb")) == NULL) {
696                 FILE_OP_ERROR(infile, "fopen");
697                 return -1;
698         }
699         if (fseek(infp, mimeinfo->fpos, SEEK_SET) < 0) {
700                 FILE_OP_ERROR(infile, "fseek");
701                 fclose(infp);
702                 return -1;
703         }
704         if ((outfp = fopen(outfile, "wb")) == NULL) {
705                 FILE_OP_ERROR(outfile, "fopen");
706                 fclose(infp);
707                 return -1;
708         }
709
710         while (fgets(buf, sizeof(buf), infp) != NULL)
711                 if (buf[0] == '\r' || buf[0] == '\n') break;
712
713         procmime_decode_content(outfp, infp, mimeinfo);
714
715         fclose(infp);
716         if (fclose(outfp) == EOF) {
717                 FILE_OP_ERROR(outfile, "fclose");
718                 unlink(outfile);
719                 return -1;
720         }
721
722         return 0;
723 }
724
725 struct ContentRenderer {
726         char * content_type;
727         char * renderer;
728 };
729
730 static GList * renderer_list = NULL;
731
732 static struct ContentRenderer *
733 content_renderer_new(char * content_type, char * renderer)
734 {
735         struct ContentRenderer * cr;
736
737         cr = g_new(struct ContentRenderer, 1);
738         if (cr == NULL)
739                 return NULL;
740
741         cr->content_type = g_strdup(content_type);
742         cr->renderer = g_strdup(renderer);
743
744         return cr;
745 }
746
747 static void content_renderer_free(struct ContentRenderer * cr)
748 {
749         g_free(cr->content_type);
750         g_free(cr->renderer);
751         g_free(cr);
752 }
753
754 void renderer_read_config(void)
755 {
756         gchar buf[BUFFSIZE];
757         FILE * f;
758         gchar * rcpath;
759
760         g_list_foreach(renderer_list, (GFunc) content_renderer_free, NULL);
761         renderer_list = NULL;
762
763         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, RENDERER_RC, NULL);
764         f = fopen(rcpath, "rb");
765         g_free(rcpath);
766         
767         if (f == NULL)
768                 return;
769
770         while (fgets(buf, BUFFSIZE, f)) {
771                 char * p;
772                 struct ContentRenderer * cr;
773
774                 strretchomp(buf);
775                 p = strchr(buf, ' ');
776                 if (p == NULL)
777                         continue;
778                 * p = 0;
779
780                 cr = content_renderer_new(buf, p + 1);
781                 if (cr == NULL)
782                         continue;
783
784                 renderer_list = g_list_append(renderer_list, cr);
785         }
786
787         fclose(f);
788 }
789
790 void renderer_write_config(void)
791 {
792         gchar * rcpath;
793         PrefFile *pfile;
794         GList * cur;
795
796         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, RENDERER_RC, NULL);
797         
798         if ((pfile = prefs_write_open(rcpath)) == NULL) {
799                 g_warning(_("failed to write configuration to file\n"));
800                 g_free(rcpath);
801                 return;
802         }
803
804         g_free(rcpath);
805
806         for(cur = renderer_list ; cur != NULL ; cur = cur->next) {
807                 struct ContentRenderer * renderer;
808                 renderer = cur->data;
809                 fprintf(pfile->fp, "%s %s\n", renderer->content_type,
810                         renderer->renderer);
811         }
812
813         if (prefs_write_close(pfile) < 0) {
814                 g_warning(_("failed to write configuration to file\n"));
815                 return;
816         }
817 }
818
819 FILE *procmime_get_text_content(MimeInfo *mimeinfo, FILE *infp)
820 {
821         FILE *tmpfp, *outfp;
822         gchar *src_codeset;
823         gboolean conv_fail = FALSE;
824         gchar buf[BUFFSIZE];
825         gchar *str;
826         struct ContentRenderer * renderer;
827         GList * cur;
828
829         g_return_val_if_fail(mimeinfo != NULL, NULL);
830         g_return_val_if_fail(infp != NULL, NULL);
831         g_return_val_if_fail(mimeinfo->mime_type == MIME_TEXT ||
832                              mimeinfo->mime_type == MIME_TEXT_HTML ||
833                              mimeinfo->mime_type == MIME_TEXT_ENRICHED, NULL);
834
835         if (fseek(infp, mimeinfo->fpos, SEEK_SET) < 0) {
836                 perror("fseek");
837                 return NULL;
838         }
839
840         while (fgets(buf, sizeof(buf), infp) != NULL)
841                 if (buf[0] == '\r' || buf[0] == '\n') break;
842
843         tmpfp = procmime_decode_content(NULL, infp, mimeinfo);
844         if (!tmpfp)
845                 return NULL;
846
847         if ((outfp = my_tmpfile()) == NULL) {
848                 perror("tmpfile");
849                 fclose(tmpfp);
850                 return NULL;
851         }
852
853         src_codeset = prefs_common.force_charset
854                 ? prefs_common.force_charset : mimeinfo->charset;
855
856         renderer = NULL;
857
858         for(cur = renderer_list ; cur != NULL ; cur = cur->next) {
859                 struct ContentRenderer * cr;
860                 cr = cur->data;
861                 if (g_strcasecmp(cr->content_type,
862                                  mimeinfo->content_type) == 0) {
863                         renderer = cr;
864                         break;
865                 }
866         }
867
868         if (renderer != NULL) {
869                 FILE * p;
870                 int oldout;
871                 
872                 oldout = dup(1);
873                 
874                 dup2(fileno(outfp), 1);
875                 
876                 p = popen(renderer->renderer, "w");
877                 if (p != NULL) {
878                         size_t count;
879                         
880                         while ((count =
881                                 fread(buf, sizeof(char), sizeof(buf),
882                                       tmpfp)) > 0)
883                                 fwrite(buf, sizeof(char), count, p);
884                         pclose(p);
885                 }
886                 
887                 dup2(oldout, 1);
888         } else if (mimeinfo->mime_type == MIME_TEXT) {
889                 while (fgets(buf, sizeof(buf), tmpfp) != NULL) {
890                         str = conv_codeset_strdup(buf, src_codeset, NULL);
891                         if (str) {
892                                 fputs(str, outfp);
893                                 g_free(str);
894                         } else {
895                                 conv_fail = TRUE;
896                                 fputs(buf, outfp);
897                         }
898                 }
899         } else if (mimeinfo->mime_type == MIME_TEXT_HTML) {
900                 HTMLParser *parser;
901                 CodeConverter *conv;
902
903                 conv = conv_code_converter_new(src_codeset);
904                 parser = html_parser_new(tmpfp, conv);
905                 while ((str = html_parse(parser)) != NULL) {
906                         fputs(str, outfp);
907                 }
908                 html_parser_destroy(parser);
909                 conv_code_converter_destroy(conv);
910         } else if (mimeinfo->mime_type == MIME_TEXT_ENRICHED) {
911                 ERTFParser *parser;
912                 CodeConverter *conv;
913
914                 conv = conv_code_converter_new(src_codeset);
915                 parser = ertf_parser_new(tmpfp, conv);
916                 while ((str = ertf_parse(parser)) != NULL) {
917                         fputs(str, outfp);
918                 }
919                 ertf_parser_destroy(parser);
920                 conv_code_converter_destroy(conv);
921         }
922
923         if (conv_fail)
924                 g_warning(_("procmime_get_text_content(): Code conversion failed.\n"));
925
926         fclose(tmpfp);
927         rewind(outfp);
928
929         return outfp;
930 }
931
932 /* search the first text part of (multipart) MIME message,
933    decode, convert it and output to outfp. */
934 FILE *procmime_get_first_text_content(MsgInfo *msginfo)
935 {
936         FILE *infp, *outfp = NULL;
937         MimeInfo *mimeinfo, *partinfo;
938
939         g_return_val_if_fail(msginfo != NULL, NULL);
940
941         mimeinfo = procmime_scan_message(msginfo);
942         if (!mimeinfo) return NULL;
943
944         if ((infp = procmsg_open_message(msginfo)) == NULL) {
945                 procmime_mimeinfo_free_all(mimeinfo);
946                 return NULL;
947         }
948
949         partinfo = mimeinfo;
950         while (partinfo && partinfo->mime_type != MIME_TEXT)
951                 partinfo = procmime_mimeinfo_next(partinfo);
952         if (!partinfo) {
953                 partinfo = mimeinfo;
954                 while (partinfo && partinfo->mime_type != MIME_TEXT_HTML &&
955                                 partinfo->mime_type != MIME_TEXT_ENRICHED)
956                         partinfo = procmime_mimeinfo_next(partinfo);
957         }
958         
959
960         if (partinfo)
961                 outfp = procmime_get_text_content(partinfo, infp);
962
963         fclose(infp);
964         procmime_mimeinfo_free_all(mimeinfo);
965
966         return outfp;
967 }
968
969 gboolean procmime_find_string_part(MimeInfo *mimeinfo, const gchar *filename,
970                                    const gchar *str, gboolean case_sens)
971 {
972
973         FILE *infp, *outfp;
974         gchar buf[BUFFSIZE];
975         gchar *(* StrFindFunc) (const gchar *haystack, const gchar *needle);
976
977         g_return_val_if_fail(mimeinfo != NULL, FALSE);
978         g_return_val_if_fail(mimeinfo->mime_type == MIME_TEXT ||
979                              mimeinfo->mime_type == MIME_TEXT_HTML ||
980                              mimeinfo->mime_type == MIME_TEXT_ENRICHED, FALSE);
981         g_return_val_if_fail(str != NULL, FALSE);
982
983         if ((infp = fopen(filename, "rb")) == NULL) {
984                 FILE_OP_ERROR(filename, "fopen");
985                 return FALSE;
986         }
987
988         outfp = procmime_get_text_content(mimeinfo, infp);
989         fclose(infp);
990
991         if (!outfp)
992                 return FALSE;
993
994         if (case_sens)
995                 StrFindFunc = strstr;
996         else
997                 StrFindFunc = strcasestr;
998
999         while (fgets(buf, sizeof(buf), outfp) != NULL) {
1000                 if (StrFindFunc(buf, str) != NULL) {
1001                         fclose(outfp);
1002                         return TRUE;
1003                 }
1004         }
1005
1006         fclose(outfp);
1007
1008         return FALSE;
1009 }
1010
1011 gboolean procmime_find_string(MsgInfo *msginfo, const gchar *str,
1012                               gboolean case_sens)
1013 {
1014         MimeInfo *mimeinfo;
1015         MimeInfo *partinfo;
1016         gchar *filename;
1017         gboolean found = FALSE;
1018
1019         g_return_val_if_fail(msginfo != NULL, FALSE);
1020         g_return_val_if_fail(str != NULL, FALSE);
1021
1022         filename = procmsg_get_message_file(msginfo);
1023         if (!filename) return FALSE;
1024         mimeinfo = procmime_scan_message(msginfo);
1025
1026         for (partinfo = mimeinfo; partinfo != NULL;
1027              partinfo = procmime_mimeinfo_next(partinfo)) {
1028                 if (partinfo->mime_type == MIME_TEXT ||
1029                     partinfo->mime_type == MIME_TEXT_HTML ||
1030                     partinfo->mime_type == MIME_TEXT_ENRICHED) {
1031                         if (procmime_find_string_part
1032                                 (partinfo, filename, str, case_sens) == TRUE) {
1033                                 found = TRUE;
1034                                 break;
1035                         }
1036                 }
1037         }
1038
1039         procmime_mimeinfo_free_all(mimeinfo);
1040         g_free(filename);
1041
1042         return found;
1043 }
1044
1045 gchar *procmime_get_tmp_file_name(MimeInfo *mimeinfo)
1046 {
1047         static guint32 id = 0;
1048         gchar *base;
1049         gchar *filename;
1050         gchar f_prefix[10];
1051
1052         g_return_val_if_fail(mimeinfo != NULL, NULL);
1053
1054         g_snprintf(f_prefix, sizeof(f_prefix), "%08x.", id++);
1055
1056         if (MIME_TEXT_HTML == mimeinfo->mime_type)
1057                 base = "mimetmp.html";
1058         else {
1059                 base = mimeinfo->filename ? mimeinfo->filename
1060                         : mimeinfo->name ? mimeinfo->name : "mimetmp";
1061                 base = g_basename(base);
1062                 if (*base == '\0') base = "mimetmp";
1063                 Xstrdup_a(base, base, return NULL);
1064                 subst_for_filename(base);
1065         }
1066
1067         filename = g_strconcat(get_mime_tmp_dir(), G_DIR_SEPARATOR_S,
1068                                f_prefix, base, NULL);
1069
1070         return filename;
1071 }
1072
1073 ContentType procmime_scan_mime_type(const gchar *mime_type)
1074 {
1075         ContentType type;
1076
1077         if (!strncasecmp(mime_type, "text/html", 9))
1078                 type = MIME_TEXT_HTML;
1079         else if (!strncasecmp(mime_type, "text/enriched", 13))
1080                 type = MIME_TEXT_ENRICHED;
1081         else if (!strncasecmp(mime_type, "text/", 5))
1082                 type = MIME_TEXT;
1083         else if (!strncasecmp(mime_type, "message/rfc822", 14))
1084                 type = MIME_MESSAGE_RFC822;
1085         else if (!strncasecmp(mime_type, "message/", 8))
1086                 type = MIME_TEXT;
1087         else if (!strncasecmp(mime_type, "application/octet-stream", 24))
1088                 type = MIME_APPLICATION_OCTET_STREAM;
1089         else if (!strncasecmp(mime_type, "application/", 12))
1090                 type = MIME_APPLICATION;
1091         else if (!strncasecmp(mime_type, "multipart/", 10))
1092                 type = MIME_MULTIPART;
1093         else if (!strncasecmp(mime_type, "image/", 6))
1094                 type = MIME_IMAGE;
1095         else if (!strncasecmp(mime_type, "audio/", 6))
1096                 type = MIME_AUDIO;
1097         else if (!strcasecmp(mime_type, "text"))
1098                 type = MIME_TEXT;
1099         else
1100                 type = MIME_UNKNOWN;
1101
1102         return type;
1103 }
1104
1105 static GList *mime_type_list = NULL;
1106
1107 gchar *procmime_get_mime_type(const gchar *filename)
1108 {
1109         static GHashTable *mime_type_table = NULL;
1110         MimeType *mime_type;
1111         const gchar *p;
1112         gchar *ext;
1113
1114         if (!mime_type_table) {
1115                 mime_type_table = procmime_get_mime_type_table();
1116                 if (!mime_type_table) return NULL;
1117         }
1118
1119         filename = g_basename(filename);
1120         p = strrchr(filename, '.');
1121         if (!p) return NULL;
1122
1123         Xstrdup_a(ext, p + 1, return NULL);
1124         g_strdown(ext);
1125         mime_type = g_hash_table_lookup(mime_type_table, ext);
1126         if (mime_type) {
1127                 gchar *str;
1128
1129                 str = g_strconcat(mime_type->type, "/", mime_type->sub_type,
1130                                   NULL);
1131                 return str;
1132         }
1133
1134         return NULL;
1135 }
1136
1137 static guint procmime_str_hash(gconstpointer gptr)
1138 {
1139         guint hash_result = 0;
1140         const char *str;
1141
1142         for (str = gptr; str && *str; str++) {
1143                 if (isupper(*str)) hash_result += (*str + ' ');
1144                 else hash_result += *str;
1145         }
1146
1147         return hash_result;
1148 }
1149
1150 static gint procmime_str_equal(gconstpointer gptr1, gconstpointer gptr2)
1151 {
1152         const char *str1 = gptr1;
1153         const char *str2 = gptr2;
1154
1155         return !strcasecmp(str1, str2);
1156 }
1157
1158 static GHashTable *procmime_get_mime_type_table(void)
1159 {
1160         GHashTable *table = NULL;
1161         GList *cur;
1162         MimeType *mime_type;
1163         gchar **exts;
1164
1165         if (!mime_type_list) {
1166                 mime_type_list = procmime_get_mime_type_list();
1167                 if (!mime_type_list) return NULL;
1168         }
1169
1170         table = g_hash_table_new(procmime_str_hash, procmime_str_equal);
1171
1172         for (cur = mime_type_list; cur != NULL; cur = cur->next) {
1173                 gint i;
1174                 gchar *key;
1175
1176                 mime_type = (MimeType *)cur->data;
1177
1178                 if (!mime_type->extension) continue;
1179
1180                 exts = g_strsplit(mime_type->extension, " ", 16);
1181                 for (i = 0; exts[i] != NULL; i++) {
1182                         /* make the key case insensitive */
1183                         g_strdown(exts[i]);
1184                         /* use previously dup'd key on overwriting */
1185                         if (g_hash_table_lookup(table, exts[i]))
1186                                 key = exts[i];
1187                         else
1188                                 key = g_strdup(exts[i]);
1189                         g_hash_table_insert(table, key, mime_type);
1190                 }
1191                 g_strfreev(exts);
1192         }
1193
1194         return table;
1195 }
1196
1197 GList *procmime_get_mime_type_list(void)
1198 {
1199         GList *list = NULL;
1200         FILE *fp;
1201         gchar buf[BUFFSIZE];
1202         gchar *p, *delim;
1203         MimeType *mime_type;
1204
1205         if (mime_type_list) 
1206                 return mime_type_list;
1207
1208         if ((fp = fopen("/etc/mime.types", "rb")) == NULL) {
1209                 if ((fp = fopen(SYSCONFDIR "/mime.types", "rb")) == NULL) {
1210                         FILE_OP_ERROR(SYSCONFDIR "/mime.types", "fopen");
1211                         return NULL;
1212                 }
1213         }
1214
1215         while (fgets(buf, sizeof(buf), fp) != NULL) {
1216                 p = strchr(buf, '#');
1217                 if (p) *p = '\0';
1218                 g_strstrip(buf);
1219
1220                 p = buf;
1221                 while (*p && !isspace(*p)) p++;
1222                 if (*p) {
1223                         *p = '\0';
1224                         p++;
1225                 }
1226                 delim = strchr(buf, '/');
1227                 if (delim == NULL) continue;
1228                 *delim = '\0';
1229
1230                 mime_type = g_new(MimeType, 1);
1231                 mime_type->type = g_strdup(buf);
1232                 mime_type->sub_type = g_strdup(delim + 1);
1233
1234                 while (*p && isspace(*p)) p++;
1235                 if (*p)
1236                         mime_type->extension = g_strdup(p);
1237                 else
1238                         mime_type->extension = NULL;
1239
1240                 list = g_list_append(list, mime_type);
1241         }
1242
1243         fclose(fp);
1244
1245         if (!list)
1246                 g_warning("Can't read mime.types\n");
1247
1248         return list;
1249 }
1250
1251 EncodingType procmime_get_encoding_for_charset(const gchar *charset)
1252 {
1253         if (!charset)
1254                 return ENC_8BIT;
1255         else if (!strncasecmp(charset, "ISO-2022-", 9) ||
1256                  !strcasecmp(charset, "US-ASCII"))
1257                 return ENC_7BIT;
1258         else
1259                 return ENC_8BIT;
1260                 /* return ENC_BASE64; */
1261                 /* return ENC_QUOTED_PRINTABLE; */
1262 }
1263
1264 EncodingType procmime_get_encoding_for_file(const gchar *file)
1265 {
1266         FILE *fp;
1267         guchar buf[BUFSIZ];
1268         size_t len;
1269
1270         if ((fp = fopen(file, "rb")) == NULL) {
1271                 FILE_OP_ERROR(file, "fopen");
1272                 return ENC_UNKNOWN;
1273         }
1274
1275         while ((len = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
1276                 guchar *p;
1277                 gint i;
1278
1279                 for (p = buf, i = 0; i < len; p++, i++) {
1280                         if (*p & 0x80) {
1281                                 fclose(fp);
1282                                 return ENC_BASE64;
1283                         }
1284                 }
1285         }
1286
1287         fclose(fp);
1288         return ENC_7BIT;
1289 }
1290
1291 struct EncodingTable 
1292 {
1293         gchar *str;
1294         EncodingType enc_type;
1295 };
1296
1297 struct EncodingTable encoding_table[] = {
1298         {"7bit", ENC_7BIT},
1299         {"8bit", ENC_8BIT},
1300         {"binary", ENC_BINARY},
1301         {"quoted-printable", ENC_QUOTED_PRINTABLE},
1302         {"base64", ENC_BASE64},
1303         {"x-uuencode", ENC_UNKNOWN},
1304         {NULL, ENC_UNKNOWN},
1305 };
1306
1307 const gchar *procmime_get_encoding_str(EncodingType encoding)
1308 {
1309         struct EncodingTable *enc_table;
1310         
1311         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1312                 if (enc_table->enc_type == encoding)
1313                         return enc_table->str;
1314         }
1315         return NULL;
1316 }