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