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