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