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