2005-02-14 [colin] 1.0.1cvs6
[claws.git] / src / procmime.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2004 Hiroyuki Yamamoto & The Sylpheed-Claws Team
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 <stdio.h>
27 #include <glib.h>
28 #include <stdio.h>
29 #include <string.h>
30 #include <locale.h>
31 #include <ctype.h>
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <unistd.h>
35
36 #include "intl.h"
37 #include "procmime.h"
38 #include "procheader.h"
39 #include "base64.h"
40 #include "quoted-printable.h"
41 #include "uuencode.h"
42 #include "unmime.h"
43 #include "html.h"
44 #include "enriched.h"
45 #include "codeconv.h"
46 #include "utils.h"
47 #include "prefs_common.h"
48 #include "prefs_gtk.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->content        = MIMECONTENT_EMPTY;
58         mimeinfo->data.filename  = NULL;
59
60         mimeinfo->type           = MIMETYPE_UNKNOWN;
61         mimeinfo->encoding_type  = ENC_UNKNOWN;
62         mimeinfo->typeparameters = g_hash_table_new(g_str_hash, g_str_equal);
63
64         mimeinfo->disposition    = DISPOSITIONTYPE_UNKNOWN;
65         mimeinfo->dispositionparameters 
66                                  = g_hash_table_new(g_str_hash, g_str_equal);
67
68         mimeinfo->node           = g_node_new(mimeinfo);
69         
70         return mimeinfo;
71 }
72
73 static gboolean procmime_mimeinfo_parameters_destroy(gpointer key, gpointer value, gpointer user_data)
74 {
75         g_free(key);
76         g_free(value);
77         
78         return TRUE;
79 }
80
81 static gchar *forced_charset = NULL;
82
83 void procmime_force_charset(const gchar *str)
84 {
85         g_free(forced_charset);
86         forced_charset = NULL;
87         if (str)
88                 forced_charset = g_strdup(str);
89 }
90
91 static EncodingType forced_encoding = 0;
92
93 void procmime_force_encoding(EncodingType encoding)
94 {
95         forced_encoding = encoding;
96 }
97
98 static gboolean free_func(GNode *node, gpointer data)
99 {
100         MimeInfo *mimeinfo = (MimeInfo *) node->data;
101
102         switch (mimeinfo->content) {
103         case MIMECONTENT_FILE:
104                 if (mimeinfo->tmp)
105                         unlink(mimeinfo->data.filename);
106                 g_free(mimeinfo->data.filename);
107                 break;
108
109         case MIMECONTENT_MEM:
110                 if (mimeinfo->tmp)
111                         g_free(mimeinfo->data.mem);
112         default:
113                 break;
114         }
115
116         g_free(mimeinfo->subtype);
117         g_free(mimeinfo->description);
118         g_free(mimeinfo->id);
119
120         g_hash_table_foreach_remove(mimeinfo->typeparameters,
121                 procmime_mimeinfo_parameters_destroy, NULL);
122         g_hash_table_destroy(mimeinfo->typeparameters);
123         g_hash_table_foreach_remove(mimeinfo->dispositionparameters,
124                 procmime_mimeinfo_parameters_destroy, NULL);
125         g_hash_table_destroy(mimeinfo->dispositionparameters);
126
127         if (mimeinfo->privacy)
128                 privacy_free_privacydata(mimeinfo->privacy);
129
130         g_free(mimeinfo);
131
132         return FALSE;
133 }
134
135 void procmime_mimeinfo_free_all(MimeInfo *mimeinfo)
136 {
137         GNode *node;
138
139         g_return_if_fail(mimeinfo);
140
141         node = mimeinfo->node;
142         g_node_traverse(node, G_IN_ORDER, G_TRAVERSE_ALL, -1, free_func, NULL);
143
144         g_node_destroy(node);
145 }
146
147 #if 0 /* UNUSED */
148 MimeInfo *procmime_mimeinfo_insert(MimeInfo *parent, MimeInfo *mimeinfo)
149 {
150         MimeInfo *child = parent->children;
151
152         if (!child)
153                 parent->children = mimeinfo;
154         else {
155                 while (child->next != NULL)
156                         child = child->next;
157
158                 child->next = mimeinfo;
159         }
160
161         mimeinfo->parent = parent;
162         mimeinfo->level = parent->level + 1;
163
164         return mimeinfo;
165 }
166
167 void procmime_mimeinfo_replace(MimeInfo *old, MimeInfo *new)
168 {
169         MimeInfo *parent = old->parent;
170         MimeInfo *child;
171
172         g_return_if_fail(parent != NULL);
173         g_return_if_fail(new->next == NULL);
174
175         for (child = parent->children; child && child != old;
176              child = child->next)
177                 ;
178         if (!child) {
179                 g_warning("oops: parent can't find it's own child");
180                 return;
181         }
182         procmime_mimeinfo_free_all(old);
183
184         if (child == parent->children) {
185                 new->next = parent->children->next;
186                 parent->children = new;
187         } else {
188                 new->next = child->next;
189                 child = new;
190         }
191 }
192 #endif
193
194 MimeInfo *procmime_mimeinfo_parent(MimeInfo *mimeinfo)
195 {
196         g_return_val_if_fail(mimeinfo != NULL, NULL);
197         g_return_val_if_fail(mimeinfo->node != NULL, NULL);
198
199         if (mimeinfo->node->parent == NULL)
200                 return NULL;
201         return (MimeInfo *) mimeinfo->node->parent->data;
202 }
203
204 MimeInfo *procmime_mimeinfo_next(MimeInfo *mimeinfo)
205 {
206         g_return_val_if_fail(mimeinfo != NULL, NULL);
207         g_return_val_if_fail(mimeinfo->node != NULL, NULL);
208
209         if (mimeinfo->node->children)
210                 return (MimeInfo *) mimeinfo->node->children->data;
211         if (mimeinfo->node->next)
212                 return (MimeInfo *) mimeinfo->node->next->data;
213
214         if (mimeinfo->node->parent == NULL)
215                 return NULL;
216
217         while (mimeinfo->node->parent != NULL) {
218                 mimeinfo = (MimeInfo *) mimeinfo->node->parent->data;
219                 if (mimeinfo->node->next)
220                         return (MimeInfo *) mimeinfo->node->next->data;
221         }
222
223         return NULL;
224 }
225
226 MimeInfo *procmime_scan_message(MsgInfo *msginfo)
227 {
228         gchar *filename;
229         MimeInfo *mimeinfo;
230
231         filename = procmsg_get_message_file_path(msginfo);
232         if (!filename || !is_file_exist(filename)) {
233                 g_free(filename);
234                 filename = procmsg_get_message_file(msginfo);
235         }
236         if (!filename || !is_file_exist(filename)) 
237                 return NULL;
238
239         if (msginfo->folder->stype != F_QUEUE && 
240             msginfo->folder->stype != F_DRAFT)
241                 mimeinfo = procmime_scan_file(filename);
242         else
243                 mimeinfo = procmime_scan_queue_file(filename);
244         g_free(filename);
245
246         return mimeinfo;
247 }
248
249 enum
250 {
251         H_CONTENT_TRANSFER_ENCODING = 0,
252         H_CONTENT_TYPE              = 1,
253         H_CONTENT_DISPOSITION       = 2,
254         H_CONTENT_DESCRIPTION       = 3,
255         H_SUBJECT                   = 4
256 };
257
258 const gchar *procmime_mimeinfo_get_parameter(MimeInfo *mimeinfo, const gchar *name)
259 {
260         const gchar *value;
261
262         g_return_val_if_fail(mimeinfo != NULL, NULL);
263         g_return_val_if_fail(name != NULL, NULL);
264
265         value = g_hash_table_lookup(mimeinfo->dispositionparameters, name);
266         if (value == NULL)
267                 value = g_hash_table_lookup(mimeinfo->typeparameters, name);
268         
269         return value;
270 }
271
272 gboolean procmime_decode_content(MimeInfo *mimeinfo)
273 {
274         gchar buf[BUFFSIZE];
275         gint readend;
276         gchar *tmpfilename;
277         gchar *mimetmpdir;
278         FILE *outfp, *infp;
279         struct stat statbuf;
280         gboolean tmp_file = FALSE;
281
282         EncodingType encoding = forced_encoding 
283                                 ? forced_encoding
284                                 : mimeinfo->encoding_type;
285                    
286         g_return_val_if_fail(mimeinfo != NULL, FALSE);
287
288         if (encoding == ENC_UNKNOWN ||
289             encoding == ENC_BINARY)
290                 return TRUE;
291
292         infp = fopen(mimeinfo->data.filename, "rb");
293         if (!infp) {
294                 perror("fopen");
295                 return FALSE;
296         }
297         fseek(infp, mimeinfo->offset, SEEK_SET);
298
299         mimetmpdir = get_mime_tmp_dir();
300         outfp = get_tmpfile_in_dir(mimetmpdir, &tmpfilename);
301         if (!outfp) {
302                 perror("tmpfile");
303                 return FALSE;
304         }
305         tmp_file = TRUE;
306         readend = mimeinfo->offset + mimeinfo->length;
307
308         if (encoding == ENC_QUOTED_PRINTABLE) {
309                 while ((ftell(infp) < readend) && (fgets(buf, sizeof(buf), infp) != NULL)) {
310                         gint len;
311                         len = qp_decode_line(buf);
312                         fwrite(buf, len, 1, outfp);
313                 }
314         } else if (encoding == ENC_BASE64) {
315                 gchar outbuf[BUFFSIZE];
316                 gint len;
317                 Base64Decoder *decoder;
318                 gboolean uncanonicalize = FALSE;
319                 FILE *tmpfp = outfp;
320
321                 if (mimeinfo->type == MIMETYPE_TEXT ||
322                     mimeinfo->type == MIMETYPE_MESSAGE) {
323                         uncanonicalize = TRUE;
324                         tmpfp = my_tmpfile();
325                         if (!tmpfp) {
326                                 perror("tmpfile");
327                                 if (tmp_file) fclose(outfp);
328                                 return FALSE;
329                         }
330                 }
331
332                 decoder = base64_decoder_new();
333                 while ((ftell(infp) < readend) && (fgets(buf, sizeof(buf), infp) != NULL)) {
334                         len = base64_decoder_decode(decoder, buf, outbuf);
335                         if (len < 0) {
336                                 g_warning("Bad BASE64 content\n");
337                                 break;
338                         }
339                         fwrite(outbuf, sizeof(gchar), len, tmpfp);
340                 }
341                 base64_decoder_free(decoder);
342
343                 if (uncanonicalize) {
344                         rewind(tmpfp);
345                         while (fgets(buf, sizeof(buf), tmpfp) != NULL) {
346                                 strcrchomp(buf);
347                                 fputs(buf, outfp);
348                         }
349                         fclose(tmpfp);
350                 }
351         } else if (encoding == ENC_X_UUENCODE) {
352                 gchar outbuf[BUFFSIZE];
353                 gint len;
354                 gboolean flag = FALSE;
355
356                 while ((ftell(infp) < readend) && (fgets(buf, sizeof(buf), infp) != NULL)) {
357                         if (!flag && strncmp(buf,"begin ", 6)) continue;
358
359                         if (flag) {
360                                 len = fromuutobits(outbuf, buf);
361                                 if (len <= 0) {
362                                         if (len < 0) 
363                                                 g_warning("Bad UUENCODE content(%d)\n", len);
364                                         break;
365                                 }
366                                 fwrite(outbuf, sizeof(gchar), len, outfp);
367                         } else
368                                 flag = TRUE;
369                 }
370         } else {
371                 while ((ftell(infp) < readend) && (fgets(buf, sizeof(buf), infp) != NULL)) {
372                         fputs(buf, outfp);
373                 }
374         }
375
376         fclose(outfp);
377         fclose(infp);
378
379         stat(tmpfilename, &statbuf);
380         if (mimeinfo->tmp && (mimeinfo->data.filename != NULL))
381                 unlink(mimeinfo->data.filename);
382         if (mimeinfo->data.filename != NULL)
383                 g_free(mimeinfo->data.filename);
384         mimeinfo->data.filename = tmpfilename;
385         mimeinfo->tmp = TRUE;
386         mimeinfo->offset = 0;
387         mimeinfo->length = statbuf.st_size;
388         mimeinfo->encoding_type = ENC_BINARY;
389
390         return TRUE;
391 }
392
393 #define B64_LINE_SIZE           57
394 #define B64_BUFFSIZE            77
395
396 gboolean procmime_encode_content(MimeInfo *mimeinfo, EncodingType encoding)
397 {
398         FILE *infp, *outfp;
399         gint len;
400         gchar *tmpfilename;
401         gchar *mimetmpdir;
402         struct stat statbuf;
403
404         if (mimeinfo->encoding_type != ENC_UNKNOWN &&
405             mimeinfo->encoding_type != ENC_BINARY &&
406             mimeinfo->encoding_type != ENC_7BIT &&
407             mimeinfo->encoding_type != ENC_8BIT)
408                 if(!procmime_decode_content(mimeinfo))
409                         return FALSE;
410
411         mimetmpdir = get_mime_tmp_dir();
412         outfp = get_tmpfile_in_dir(mimetmpdir, &tmpfilename);
413         if (!outfp) {
414                 perror("tmpfile");
415                 return FALSE;
416         }
417
418         if (mimeinfo->content == MIMECONTENT_FILE) {
419                 if ((infp = fopen(mimeinfo->data.filename, "rb")) == NULL) {
420                         g_warning("Can't open file %s\n", mimeinfo->data.filename);
421                         return FALSE;
422                 }
423         } else if (mimeinfo->content == MIMECONTENT_MEM) {
424                 infp = str_open_as_stream(mimeinfo->data.mem);
425                 if (infp == NULL)
426                         return FALSE;
427         }
428
429         if (encoding == ENC_BASE64) {
430                 gchar inbuf[B64_LINE_SIZE], outbuf[B64_BUFFSIZE];
431                 FILE *tmp_fp = infp;
432                 gchar *tmp_file = NULL;
433
434                 if (mimeinfo->type == MIMETYPE_TEXT ||
435                     mimeinfo->type == MIMETYPE_MESSAGE) {
436                         if (mimeinfo->content == MIMECONTENT_FILE) {
437                                 tmp_file = get_tmp_file();
438                                 if (canonicalize_file(mimeinfo->data.filename, tmp_file) < 0) {
439                                         g_free(tmp_file);
440                                         fclose(infp);
441                                         return FALSE;
442                                 }
443                                 if ((tmp_fp = fopen(tmp_file, "rb")) == NULL) {
444                                         FILE_OP_ERROR(tmp_file, "fopen");
445                                         unlink(tmp_file);
446                                         g_free(tmp_file);
447                                         fclose(infp);
448                                         return FALSE;
449                                 }
450                         } else {
451                                 gchar *out = canonicalize_str(mimeinfo->data.mem);
452                                 fclose(infp);
453                                 tmp_fp = infp = str_open_as_stream(out);
454                                 g_free(out);
455                                 if (infp == NULL)
456                                         return FALSE;
457                         }
458                 }
459
460                 while ((len = fread(inbuf, sizeof(gchar),
461                                     B64_LINE_SIZE, tmp_fp))
462                        == B64_LINE_SIZE) {
463                         base64_encode(outbuf, inbuf, B64_LINE_SIZE);
464                         fputs(outbuf, outfp);
465                         fputc('\n', outfp);
466                 }
467                 if (len > 0 && feof(tmp_fp)) {
468                         base64_encode(outbuf, inbuf, len);
469                         fputs(outbuf, outfp);
470                         fputc('\n', outfp);
471                 }
472
473                 if (tmp_file) {
474                         fclose(tmp_fp);
475                         unlink(tmp_file);
476                         g_free(tmp_file);
477                 } 
478         } else if (encoding == ENC_QUOTED_PRINTABLE) {
479                 gchar inbuf[BUFFSIZE], outbuf[BUFFSIZE * 4];
480
481                 while (fgets(inbuf, sizeof(inbuf), infp) != NULL) {
482                         qp_encode_line(outbuf, inbuf);
483
484                         if (!strncmp("From ", outbuf, strlen("From "))) {
485                                 gchar *tmpbuf = outbuf;
486                                 
487                                 tmpbuf += strlen("From ");
488                                 
489                                 fputs("=46rom ", outfp);
490                                 fputs(tmpbuf, outfp);
491                         } else 
492                                 fputs(outbuf, outfp);
493                 }
494         } else {
495                 gchar buf[BUFFSIZE];
496
497                 while (fgets(buf, sizeof(buf), infp) != NULL) {
498                         strcrchomp(buf);
499                         fputs(buf, outfp);
500                 }
501         }
502
503         fclose(outfp);
504         fclose(infp);
505
506         if (mimeinfo->content == MIMECONTENT_FILE) {
507                 if (mimeinfo->tmp && (mimeinfo->data.filename != NULL))
508                         unlink(mimeinfo->data.filename);
509                 g_free(mimeinfo->data.filename);
510         } else if (mimeinfo->content == MIMECONTENT_MEM) {
511                 if (mimeinfo->tmp && (mimeinfo->data.mem != NULL))
512                         g_free(mimeinfo->data.mem);
513         }
514
515         stat(tmpfilename, &statbuf);
516         mimeinfo->content = MIMECONTENT_FILE;
517         mimeinfo->data.filename = tmpfilename;
518         mimeinfo->tmp = TRUE;
519         mimeinfo->offset = 0;
520         mimeinfo->length = statbuf.st_size;
521         mimeinfo->encoding_type = encoding;
522
523         return TRUE;
524 }
525
526 gint procmime_get_part(const gchar *outfile, MimeInfo *mimeinfo)
527 {
528         FILE *infp, *outfp;
529         gchar buf[BUFFSIZE];
530         gint restlength, readlength;
531
532         g_return_val_if_fail(outfile != NULL, -1);
533         g_return_val_if_fail(mimeinfo != NULL, -1);
534
535         if (mimeinfo->encoding_type != ENC_BINARY && !procmime_decode_content(mimeinfo))
536                 return -1;
537
538         if ((infp = fopen(mimeinfo->data.filename, "rb")) == NULL) {
539                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
540                 return -1;
541         }
542         if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
543                 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
544                 fclose(infp);
545                 return -1;
546         }
547         if ((outfp = fopen(outfile, "wb")) == NULL) {
548                 FILE_OP_ERROR(outfile, "fopen");
549                 fclose(infp);
550                 return -1;
551         }
552
553         restlength = mimeinfo->length;
554
555         while ((restlength > 0) && ((readlength = fread(buf, 1, restlength > BUFFSIZE ? BUFFSIZE : restlength, infp)) > 0)) {
556                 fwrite(buf, 1, readlength, outfp);
557                 restlength -= readlength;
558         }
559
560         fclose(infp);
561         if (fclose(outfp) == EOF) {
562                 FILE_OP_ERROR(outfile, "fclose");
563                 unlink(outfile);
564                 return -1;
565         }
566
567         return 0;
568 }
569
570 struct ContentRenderer {
571         char * content_type;
572         char * renderer;
573 };
574
575 static GList * renderer_list = NULL;
576
577 static struct ContentRenderer *
578 content_renderer_new(char * content_type, char * renderer)
579 {
580         struct ContentRenderer * cr;
581
582         cr = g_new(struct ContentRenderer, 1);
583         if (cr == NULL)
584                 return NULL;
585
586         cr->content_type = g_strdup(content_type);
587         cr->renderer = g_strdup(renderer);
588
589         return cr;
590 }
591
592 static void content_renderer_free(struct ContentRenderer * cr)
593 {
594         g_free(cr->content_type);
595         g_free(cr->renderer);
596         g_free(cr);
597 }
598
599 void renderer_read_config(void)
600 {
601         gchar buf[BUFFSIZE];
602         FILE * f;
603         gchar * rcpath;
604
605         g_list_foreach(renderer_list, (GFunc) content_renderer_free, NULL);
606         renderer_list = NULL;
607
608         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, RENDERER_RC, NULL);
609         f = fopen(rcpath, "rb");
610         g_free(rcpath);
611         
612         if (f == NULL)
613                 return;
614
615         while (fgets(buf, BUFFSIZE, f)) {
616                 char * p;
617                 struct ContentRenderer * cr;
618
619                 strretchomp(buf);
620                 p = strchr(buf, ' ');
621                 if (p == NULL)
622                         continue;
623                 * p = 0;
624
625                 cr = content_renderer_new(buf, p + 1);
626                 if (cr == NULL)
627                         continue;
628
629                 renderer_list = g_list_append(renderer_list, cr);
630         }
631
632         fclose(f);
633 }
634
635 void renderer_write_config(void)
636 {
637         gchar * rcpath;
638         PrefFile *pfile;
639         GList * cur;
640
641         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, RENDERER_RC, NULL);
642         
643         if ((pfile = prefs_write_open(rcpath)) == NULL) {
644                 g_warning("failed to write configuration to file\n");
645                 g_free(rcpath);
646                 return;
647         }
648
649         g_free(rcpath);
650
651         for (cur = renderer_list ; cur != NULL ; cur = cur->next) {
652                 struct ContentRenderer * renderer;
653                 renderer = cur->data;
654                 fprintf(pfile->fp, "%s %s\n", renderer->content_type,
655                         renderer->renderer);
656         }
657
658         if (prefs_file_close(pfile) < 0) {
659                 g_warning("failed to write configuration to file\n");
660                 return;
661         }
662 }
663
664 FILE *procmime_get_text_content(MimeInfo *mimeinfo)
665 {
666         FILE *tmpfp, *outfp;
667         const gchar *src_codeset;
668         gboolean conv_fail = FALSE;
669         gchar buf[BUFFSIZE];
670         gchar *str;
671         struct ContentRenderer * renderer;
672         GList * cur;
673         gchar *tmpfile, *content_type;
674     
675         g_return_val_if_fail(mimeinfo != NULL, NULL);
676
677         if (!procmime_decode_content(mimeinfo))
678                 return NULL;
679
680         tmpfile = procmime_get_tmp_file_name(mimeinfo);
681         if (tmpfile == NULL)
682                 return NULL;
683
684         if (procmime_get_part(tmpfile, mimeinfo) < 0) {
685                 g_free(tmpfile);
686                 return NULL;
687         }
688
689         tmpfp = fopen(tmpfile, "rb");
690         if (tmpfp == NULL) {
691                 g_free(tmpfile);
692                 return NULL;
693         }
694
695         if ((outfp = my_tmpfile()) == NULL) {
696                 perror("tmpfile");
697                 fclose(tmpfp);
698                 g_free(tmpfile);
699                 return NULL;
700         }
701
702         src_codeset = forced_charset
703                       ? forced_charset : 
704                       procmime_mimeinfo_get_parameter(mimeinfo, "charset");
705
706         renderer = NULL;
707
708         content_type = procmime_get_content_type_str(mimeinfo->type,
709                                                      mimeinfo->subtype);
710         for (cur = renderer_list ; cur != NULL ; cur = cur->next) {
711                 struct ContentRenderer * cr;
712
713                 cr = cur->data;
714                 if (g_strcasecmp(cr->content_type, content_type) == 0) {
715                         renderer = cr;
716                         break;
717                 }
718         }
719         g_free(content_type);
720
721         if (renderer != NULL) {
722                 FILE * p;
723                 int oldout;
724                 
725                 oldout = dup(1);
726                 
727                 dup2(fileno(outfp), 1);
728                 
729                 p = popen(renderer->renderer, "w");
730                 if (p != NULL) {
731                         size_t count;
732                         
733                         while ((count =
734                                 fread(buf, sizeof(char), sizeof(buf),
735                                       tmpfp)) > 0)
736                                 fwrite(buf, sizeof(char), count, p);
737                         pclose(p);
738                 }
739                 
740                 dup2(oldout, 1);
741         } else if (mimeinfo->type == MIMETYPE_TEXT && !g_strcasecmp(mimeinfo->subtype, "html")) {
742                 HTMLParser *parser;
743                 CodeConverter *conv;
744
745                 conv = conv_code_converter_new(src_codeset);
746                 parser = html_parser_new(tmpfp, conv);
747                 while ((str = html_parse(parser)) != NULL) {
748                         fputs(str, outfp);
749                 }
750                 html_parser_destroy(parser);
751                 conv_code_converter_destroy(conv);
752         } else if (mimeinfo->type == MIMETYPE_TEXT && !g_strcasecmp(mimeinfo->subtype, "enriched")) {
753                 ERTFParser *parser;
754                 CodeConverter *conv;
755
756                 conv = conv_code_converter_new(src_codeset);
757                 parser = ertf_parser_new(tmpfp, conv);
758                 while ((str = ertf_parse(parser)) != NULL) {
759                         fputs(str, outfp);
760                 }
761                 ertf_parser_destroy(parser);
762                 conv_code_converter_destroy(conv);
763         } else if (mimeinfo->type == MIMETYPE_TEXT) {
764                 while (fgets(buf, sizeof(buf), tmpfp) != NULL) {
765                         str = conv_codeset_strdup(buf, src_codeset, NULL);
766                         if (str) {
767                                 fputs(str, outfp);
768                                 g_free(str);
769                         } else {
770                                 conv_fail = TRUE;
771                                 fputs(buf, outfp);
772                         }
773                 }
774         }
775
776         if (conv_fail)
777                 g_warning("procmime_get_text_content(): Code conversion failed.\n");
778
779         fclose(tmpfp);
780         rewind(outfp);
781         unlink(tmpfile);
782         g_free(tmpfile);
783
784         return outfp;
785 }
786
787 /* search the first text part of (multipart) MIME message,
788    decode, convert it and output to outfp. */
789 FILE *procmime_get_first_text_content(MsgInfo *msginfo)
790 {
791         FILE *outfp = NULL;
792         MimeInfo *mimeinfo, *partinfo;
793
794         g_return_val_if_fail(msginfo != NULL, NULL);
795
796         mimeinfo = procmime_scan_message(msginfo);
797         if (!mimeinfo) return NULL;
798
799         partinfo = mimeinfo;
800         while (partinfo && partinfo->type != MIMETYPE_TEXT)
801                 partinfo = procmime_mimeinfo_next(partinfo);
802
803         if (partinfo)
804                 outfp = procmime_get_text_content(partinfo);
805
806         procmime_mimeinfo_free_all(mimeinfo);
807
808         return outfp;
809 }
810
811 gboolean procmime_find_string_part(MimeInfo *mimeinfo, const gchar *filename,
812                                    const gchar *str, StrFindFunc find_func)
813 {
814         FILE *outfp;
815         gchar buf[BUFFSIZE];
816
817         g_return_val_if_fail(mimeinfo != NULL, FALSE);
818         g_return_val_if_fail(mimeinfo->type == MIMETYPE_TEXT, FALSE);
819         g_return_val_if_fail(str != NULL, FALSE);
820         g_return_val_if_fail(find_func != NULL, FALSE);
821
822         outfp = procmime_get_text_content(mimeinfo);
823
824         if (!outfp)
825                 return FALSE;
826
827         while (fgets(buf, sizeof(buf), outfp) != NULL) {
828                 strretchomp(buf);
829                 if (find_func(buf, str)) {
830                         fclose(outfp);
831                         return TRUE;
832                 }
833         }
834
835         fclose(outfp);
836
837         return FALSE;
838 }
839
840 gboolean procmime_find_string(MsgInfo *msginfo, const gchar *str,
841                               StrFindFunc find_func)
842 {
843         MimeInfo *mimeinfo;
844         MimeInfo *partinfo;
845         gchar *filename;
846         gboolean found = FALSE;
847
848         g_return_val_if_fail(msginfo != NULL, FALSE);
849         g_return_val_if_fail(str != NULL, FALSE);
850         g_return_val_if_fail(find_func != NULL, FALSE);
851
852         filename = procmsg_get_message_file(msginfo);
853         if (!filename) return FALSE;
854         mimeinfo = procmime_scan_message(msginfo);
855
856         for (partinfo = mimeinfo; partinfo != NULL;
857              partinfo = procmime_mimeinfo_next(partinfo)) {
858                 if (partinfo->type == MIMETYPE_TEXT) {
859                         if (procmime_find_string_part
860                                 (partinfo, filename, str, find_func) == TRUE) {
861                                 found = TRUE;
862                                 break;
863                         }
864                 }
865         }
866
867         procmime_mimeinfo_free_all(mimeinfo);
868         g_free(filename);
869
870         return found;
871 }
872
873 gchar *procmime_get_tmp_file_name(MimeInfo *mimeinfo)
874 {
875         static guint32 id = 0;
876         gchar *base;
877         gchar *filename;
878         gchar f_prefix[10];
879
880         g_return_val_if_fail(mimeinfo != NULL, NULL);
881
882         g_snprintf(f_prefix, sizeof(f_prefix), "%08x.", id++);
883
884         if ((mimeinfo->type == MIMETYPE_TEXT) && !g_strcasecmp(mimeinfo->subtype, "html"))
885                 base = "mimetmp.html";
886         else {
887                 const gchar *basetmp;
888
889                 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
890                 if (basetmp == NULL)
891                         basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
892                 if (basetmp == NULL)
893                         basetmp = "mimetmp";
894                 base = g_basename(basetmp);
895                 if (*base == '\0') base = "mimetmp";
896                 Xstrdup_a(base, base, return NULL);
897                 subst_for_shellsafe_filename(base);
898         }
899
900         filename = g_strconcat(get_mime_tmp_dir(), G_DIR_SEPARATOR_S,
901                                f_prefix, base, NULL);
902
903         return filename;
904 }
905
906 static GList *mime_type_list = NULL;
907
908 gchar *procmime_get_mime_type(const gchar *filename)
909 {
910         static GHashTable *mime_type_table = NULL;
911         MimeType *mime_type;
912         const gchar *p;
913         gchar *ext;
914
915         if (!mime_type_table) {
916                 mime_type_table = procmime_get_mime_type_table();
917                 if (!mime_type_table) return NULL;
918         }
919
920         filename = g_basename(filename);
921         p = strrchr(filename, '.');
922         if (!p) return NULL;
923
924         Xstrdup_a(ext, p + 1, return NULL);
925         g_strdown(ext);
926         mime_type = g_hash_table_lookup(mime_type_table, ext);
927         if (mime_type) {
928                 gchar *str;
929
930                 str = g_strconcat(mime_type->type, "/", mime_type->sub_type,
931                                   NULL);
932                 return str;
933         }
934
935         return NULL;
936 }
937
938 static guint procmime_str_hash(gconstpointer gptr)
939 {
940         guint hash_result = 0;
941         const char *str;
942
943         for (str = gptr; str && *str; str++) {
944                 if (isupper(*str)) hash_result += (*str + ' ');
945                 else hash_result += *str;
946         }
947
948         return hash_result;
949 }
950
951 static gint procmime_str_equal(gconstpointer gptr1, gconstpointer gptr2)
952 {
953         const char *str1 = gptr1;
954         const char *str2 = gptr2;
955
956         return !g_strcasecmp(str1, str2);
957 }
958
959 static GHashTable *procmime_get_mime_type_table(void)
960 {
961         GHashTable *table = NULL;
962         GList *cur;
963         MimeType *mime_type;
964         gchar **exts;
965
966         if (!mime_type_list) {
967                 mime_type_list = procmime_get_mime_type_list();
968                 if (!mime_type_list) return NULL;
969         }
970
971         table = g_hash_table_new(procmime_str_hash, procmime_str_equal);
972
973         for (cur = mime_type_list; cur != NULL; cur = cur->next) {
974                 gint i;
975                 gchar *key;
976
977                 mime_type = (MimeType *)cur->data;
978
979                 if (!mime_type->extension) continue;
980
981                 exts = g_strsplit(mime_type->extension, " ", 16);
982                 for (i = 0; exts[i] != NULL; i++) {
983                         /* make the key case insensitive */
984                         g_strdown(exts[i]);
985                         /* use previously dup'd key on overwriting */
986                         if (g_hash_table_lookup(table, exts[i]))
987                                 key = exts[i];
988                         else
989                                 key = g_strdup(exts[i]);
990                         g_hash_table_insert(table, key, mime_type);
991                 }
992                 g_strfreev(exts);
993         }
994
995         return table;
996 }
997
998 GList *procmime_get_mime_type_list(void)
999 {
1000         GList *list = NULL;
1001         FILE *fp;
1002         gchar buf[BUFFSIZE];
1003         guchar *p;
1004         gchar *delim;
1005         MimeType *mime_type;
1006
1007         if (mime_type_list) 
1008                 return mime_type_list;
1009
1010         if ((fp = fopen("/etc/mime.types", "rb")) == NULL) {
1011                 if ((fp = fopen(SYSCONFDIR "/mime.types", "rb")) == NULL) {
1012                         FILE_OP_ERROR(SYSCONFDIR "/mime.types", "fopen");
1013                         return NULL;
1014                 }
1015         }
1016
1017         while (fgets(buf, sizeof(buf), fp) != NULL) {
1018                 p = strchr(buf, '#');
1019                 if (p) *p = '\0';
1020                 g_strstrip(buf);
1021
1022                 p = buf;
1023                 while (*p && !isspace(*p)) p++;
1024                 if (*p) {
1025                         *p = '\0';
1026                         p++;
1027                 }
1028                 delim = strchr(buf, '/');
1029                 if (delim == NULL) continue;
1030                 *delim = '\0';
1031
1032                 mime_type = g_new(MimeType, 1);
1033                 mime_type->type = g_strdup(buf);
1034                 mime_type->sub_type = g_strdup(delim + 1);
1035
1036                 while (*p && isspace(*p)) p++;
1037                 if (*p)
1038                         mime_type->extension = g_strdup(p);
1039                 else
1040                         mime_type->extension = NULL;
1041
1042                 list = g_list_append(list, mime_type);
1043         }
1044
1045         fclose(fp);
1046
1047         if (!list)
1048                 g_warning("Can't read mime.types\n");
1049
1050         return list;
1051 }
1052
1053 EncodingType procmime_get_encoding_for_charset(const gchar *charset)
1054 {
1055         if (!charset)
1056                 return ENC_8BIT;
1057         else if (!g_strncasecmp(charset, "ISO-2022-", 9) ||
1058                  !g_strcasecmp(charset, "US-ASCII"))
1059                 return ENC_7BIT;
1060         else if (!g_strcasecmp(charset, "ISO-8859-5") ||
1061                  !g_strncasecmp(charset, "KOI8-", 5) ||
1062                  !g_strcasecmp(charset, "Windows-1251"))
1063                 return ENC_8BIT;
1064         else if (!g_strncasecmp(charset, "ISO-8859-", 9))
1065                 return ENC_QUOTED_PRINTABLE;
1066         else
1067                 return ENC_8BIT;
1068 }
1069
1070 EncodingType procmime_get_encoding_for_text_file(const gchar *file)
1071 {
1072         FILE *fp;
1073         guchar buf[BUFFSIZE];
1074         size_t len;
1075         size_t octet_chars = 0;
1076         size_t total_len = 0;
1077         gfloat octet_percentage;
1078
1079         if ((fp = fopen(file, "rb")) == NULL) {
1080                 FILE_OP_ERROR(file, "fopen");
1081                 return ENC_UNKNOWN;
1082         }
1083
1084         while ((len = fread(buf, sizeof(guchar), sizeof(buf), fp)) > 0) {
1085                 guchar *p;
1086                 gint i;
1087
1088                 for (p = buf, i = 0; i < len; ++p, ++i) {
1089                         if (*p & 0x80)
1090                                 ++octet_chars;
1091                 }
1092                 total_len += len;
1093         }
1094
1095         fclose(fp);
1096         
1097         if (total_len > 0)
1098                 octet_percentage = (gfloat)octet_chars / (gfloat)total_len;
1099         else
1100                 octet_percentage = 0.0;
1101
1102         debug_print("procmime_get_encoding_for_text_file(): "
1103                     "8bit chars: %d / %d (%f%%)\n", octet_chars, total_len,
1104                     100.0 * octet_percentage);
1105
1106         if (octet_percentage > 0.20) {
1107                 debug_print("using BASE64\n");
1108                 return ENC_BASE64;
1109         } else if (octet_chars > 0) {
1110                 debug_print("using quoted-printable\n");
1111                 return ENC_QUOTED_PRINTABLE;
1112         } else {
1113                 debug_print("using 7bit\n");
1114                 return ENC_7BIT;
1115         }
1116 }
1117
1118 struct EncodingTable 
1119 {
1120         gchar *str;
1121         EncodingType enc_type;
1122 };
1123
1124 struct EncodingTable encoding_table[] = {
1125         {"7bit", ENC_7BIT},
1126         {"8bit", ENC_8BIT},
1127         {"binary", ENC_BINARY},
1128         {"quoted-printable", ENC_QUOTED_PRINTABLE},
1129         {"base64", ENC_BASE64},
1130         {"x-uuencode", ENC_UNKNOWN},
1131         {NULL, ENC_UNKNOWN},
1132 };
1133
1134 const gchar *procmime_get_encoding_str(EncodingType encoding)
1135 {
1136         struct EncodingTable *enc_table;
1137         
1138         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1139                 if (enc_table->enc_type == encoding)
1140                         return enc_table->str;
1141         }
1142         return NULL;
1143 }
1144
1145 /* --- NEW MIME STUFF --- */
1146 struct TypeTable
1147 {
1148         gchar *str;
1149         MimeMediaType type;
1150 };
1151
1152 static struct TypeTable mime_type_table[] = {
1153         {"text", MIMETYPE_TEXT},
1154         {"image", MIMETYPE_IMAGE},
1155         {"audio", MIMETYPE_AUDIO},
1156         {"video", MIMETYPE_VIDEO},
1157         {"application", MIMETYPE_APPLICATION},
1158         {"message", MIMETYPE_MESSAGE},
1159         {"multipart", MIMETYPE_MULTIPART},
1160         {NULL, 0},
1161 };
1162
1163 const gchar *procmime_get_media_type_str(MimeMediaType type)
1164 {
1165         struct TypeTable *type_table;
1166         
1167         for (type_table = mime_type_table; type_table->str != NULL; type_table++) {
1168                 if (type_table->type == type)
1169                         return type_table->str;
1170         }
1171         return NULL;
1172 }
1173
1174 MimeMediaType procmime_get_media_type(const gchar *str)
1175 {
1176         struct TypeTable *typetablearray;
1177
1178         for (typetablearray = mime_type_table; typetablearray->str != NULL; typetablearray++)
1179                 if (g_strncasecmp(str, typetablearray->str, strlen(typetablearray->str)) == 0)
1180                         return typetablearray->type;
1181
1182         return MIMETYPE_UNKNOWN;
1183 }
1184
1185 /*!
1186  *\brief        Safe wrapper for content type string.
1187  *
1188  *\return       const gchar * Pointer to content type string. 
1189  */
1190 gchar *procmime_get_content_type_str(MimeMediaType type,
1191                                            const char *subtype)
1192 {
1193         const gchar *type_str = NULL;
1194
1195         if (subtype == NULL || !(type_str = procmime_get_media_type_str(type)))
1196                 return g_strdup("unknown");
1197         return g_strdup_printf("%s/%s", type_str, subtype);
1198 }
1199
1200 void procmime_parse_mimepart(MimeInfo *parent,
1201                              gchar *content_type,
1202                              gchar *content_encoding,
1203                              gchar *content_description,
1204                              gchar *content_id,
1205                              gchar *content_disposition,
1206                              const gchar *filename,
1207                              guint offset,
1208                              guint length);
1209
1210 void procmime_parse_message_rfc822(MimeInfo *mimeinfo)
1211 {
1212         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1213                                 {"Content-Transfer-Encoding:",
1214                                                    NULL, FALSE},
1215                                 {"Content-Description:",
1216                                                    NULL, TRUE},
1217                                 {"Content-ID:",
1218                                                    NULL, TRUE},
1219                                 {"Content-Disposition:",
1220                                                    NULL, TRUE},
1221                                 {"MIME-Version:",
1222                                                    NULL, TRUE},
1223                                 {NULL,             NULL, FALSE}};
1224         guint content_start, i;
1225         FILE *fp;
1226         gint mime_major, mime_minor;
1227
1228         procmime_decode_content(mimeinfo);
1229
1230         fp = fopen(mimeinfo->data.filename, "rb");
1231         if (fp == NULL) {
1232                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1233                 return;
1234         }
1235         fseek(fp, mimeinfo->offset, SEEK_SET);
1236         procheader_get_header_fields(fp, hentry);
1237         if (hentry[0].body != NULL)
1238                 conv_unmime_header_overwrite(hentry[0].body);
1239         if (hentry[2].body != NULL)
1240                 conv_unmime_header_overwrite(hentry[2].body);
1241         if (hentry[4].body != NULL)
1242                 conv_unmime_header_overwrite(hentry[4].body);
1243         content_start = ftell(fp);
1244         fclose(fp);
1245
1246         if ((hentry[5].body != NULL) &&
1247             (sscanf(hentry[5].body, "%d.%d", &mime_major, &mime_minor) == 2) &&
1248             (mime_major == 1) && (mime_minor == 0)) {
1249                 procmime_parse_mimepart(mimeinfo,
1250                                         hentry[0].body, hentry[1].body,
1251                                         hentry[2].body, hentry[3].body, 
1252                                         hentry[4].body, 
1253                                         mimeinfo->data.filename, content_start,
1254                                         mimeinfo->length - (content_start - mimeinfo->offset));
1255         } else {
1256                 MimeInfo *subinfo;
1257
1258                 subinfo = procmime_mimeinfo_new();
1259                 subinfo->content = MIMECONTENT_FILE;
1260                 subinfo->encoding_type = ENC_UNKNOWN;
1261                 subinfo->type = MIMETYPE_TEXT;
1262                 subinfo->subtype = g_strdup("plain");
1263                 subinfo->data.filename = g_strdup(mimeinfo->data.filename);
1264                 subinfo->offset = content_start;
1265                 subinfo->length = mimeinfo->length - (content_start - mimeinfo->offset);
1266
1267                 g_node_append(mimeinfo->node, subinfo->node);
1268         }
1269         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1270                 g_free(hentry[i].body);
1271                 hentry[i].body = NULL;
1272         }
1273 }
1274
1275 void procmime_parse_multipart(MimeInfo *mimeinfo)
1276 {
1277         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1278                                 {"Content-Transfer-Encoding:",
1279                                                    NULL, FALSE},
1280                                 {"Content-Description:",
1281                                                    NULL, TRUE},
1282                                 {"Content-ID:",
1283                                                    NULL, TRUE},
1284                                 {"Content-Disposition:",
1285                                                    NULL, TRUE},
1286                                 {NULL,             NULL, FALSE}};
1287         gchar *p;
1288         gchar *boundary;
1289         gint boundary_len = 0, lastoffset = -1, i;
1290         gchar buf[BUFFSIZE];
1291         FILE *fp;
1292
1293         boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
1294         if (!boundary)
1295                 return;
1296         boundary_len = strlen(boundary);
1297
1298         procmime_decode_content(mimeinfo);
1299
1300         fp = fopen(mimeinfo->data.filename, "rb");
1301         if (fp == NULL) {
1302                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1303                 return;
1304         }
1305         fseek(fp, mimeinfo->offset, SEEK_SET);
1306         while ((p = fgets(buf, sizeof(buf), fp)) != NULL) {
1307                 if (ftell(fp) > (mimeinfo->offset + mimeinfo->length))
1308                         break;
1309
1310                 if (IS_BOUNDARY(buf, boundary, boundary_len)) {
1311                         if (lastoffset != -1) {
1312                                 procmime_parse_mimepart(mimeinfo,
1313                                                         hentry[0].body, hentry[1].body,
1314                                                         hentry[2].body, hentry[3].body, 
1315                                                         hentry[4].body, 
1316                                                         mimeinfo->data.filename, lastoffset,
1317                                                         (ftell(fp) - strlen(buf)) - lastoffset - 1);
1318                         }
1319                         
1320                         if (buf[2 + boundary_len]     == '-' &&
1321                             buf[2 + boundary_len + 1] == '-')
1322                                 break;
1323
1324                         for (i = 0; i < (sizeof hentry / sizeof hentry[0]) ; i++) {
1325                                 g_free(hentry[i].body);
1326                                 hentry[i].body = NULL;
1327                         }
1328                         procheader_get_header_fields(fp, hentry);
1329                         if (hentry[0].body != NULL)
1330                                 conv_unmime_header_overwrite(hentry[0].body);
1331                         if (hentry[2].body != NULL)
1332                                 conv_unmime_header_overwrite(hentry[2].body);
1333                         if (hentry[4].body != NULL)
1334                                 conv_unmime_header_overwrite(hentry[4].body);
1335                         lastoffset = ftell(fp);
1336                 }
1337         }
1338         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1339                 g_free(hentry[i].body);
1340                 hentry[i].body = NULL;
1341         }
1342         fclose(fp);
1343 }
1344
1345 static void parse_parameters(const gchar *parameters, GHashTable *table)
1346 {
1347         gchar *params, *param, *next;
1348         GSList *convlist = NULL, *concatlist = NULL, *cur;
1349
1350         params = g_strdup(parameters);
1351         param = params;
1352         next = params;
1353         for (; next != NULL; param = next) {
1354                 gchar *attribute, *value, *tmp;
1355                 gint len;
1356                 gboolean convert = FALSE;
1357
1358                 next = strchr_with_skip_quote(param, '"', ';');
1359                 if (next != NULL) {
1360                         next[0] = '\0';
1361                         next++;
1362                 }
1363
1364                 g_strstrip(param);
1365
1366                 attribute = param;
1367                 value = strchr(attribute, '=');
1368                 if (value == NULL)
1369                         continue;
1370
1371                 value[0] = '\0';
1372                 value++;
1373
1374                 g_strdown(attribute);
1375
1376                 len = strlen(attribute);
1377                 if (attribute[len - 1] == '*') {
1378                         gchar *srcpos, *dstpos, *endpos;
1379
1380                         convert = TRUE;
1381                         attribute[len - 1] = '\0';
1382
1383                         srcpos = value;
1384                         dstpos = value;
1385                         endpos = value + strlen(value);
1386                         while (srcpos < endpos) {
1387                                 if (*srcpos != '%')
1388                                         *dstpos = *srcpos;
1389                                 else {
1390                                         guchar dstvalue;
1391
1392                                         if (!get_hex_value(&dstvalue, srcpos[1], srcpos[2]))
1393                                                 *dstpos = '?';
1394                                         else
1395                                                 *dstpos = dstvalue;
1396                                         srcpos += 2;
1397                                 }
1398                                 srcpos++;
1399                                 dstpos++;
1400                         }
1401                         *dstpos = '\0';
1402                 } else {
1403                         if (value[0] == '"')
1404                                 extract_quote(value, '"');
1405                         else if ((tmp = strchr(value, ' ')) != NULL)
1406                                 *tmp = '\0';
1407                 }
1408
1409                 if (strrchr(attribute, '*') != NULL) {
1410                         gchar *tmpattr;
1411
1412                         tmpattr = g_strdup(attribute);
1413                         tmp = strrchr(tmpattr, '*');
1414                         tmp[0] = '\0';
1415
1416                         if ((tmp[1] == '0') && (tmp[2] == '\0') && 
1417                             (g_slist_find_custom(concatlist, attribute, g_str_equal) == NULL))
1418                                 concatlist = g_slist_prepend(concatlist, g_strdup(tmpattr));
1419
1420                         if (convert && (g_slist_find_custom(convlist, attribute, g_str_equal) == NULL))
1421                                 convlist = g_slist_prepend(convlist, g_strdup(tmpattr));
1422
1423                         g_free(tmpattr);
1424                 } else if (convert) {
1425                         if (g_slist_find_custom(convlist, attribute, g_str_equal) == NULL)
1426                                 convlist = g_slist_prepend(convlist, g_strdup(attribute));
1427                 }
1428
1429                 if (g_hash_table_lookup(table, attribute) == NULL)
1430                         g_hash_table_insert(table, g_strdup(attribute), g_strdup(value));
1431         }
1432
1433         for (cur = concatlist; cur != NULL; cur = g_slist_next(cur)) {
1434                 gchar *attribute, *attrwnum, *partvalue;
1435                 gint n = 0;
1436                 GString *value;
1437
1438                 attribute = (gchar *) cur->data;
1439                 value = g_string_sized_new(64);
1440
1441                 attrwnum = g_strdup_printf("%s*%d", attribute, n);
1442                 while ((partvalue = g_hash_table_lookup(table, attrwnum)) != NULL) {
1443                         g_string_append(value, partvalue);
1444
1445                         g_free(attrwnum);
1446                         n++;
1447                         attrwnum = g_strdup_printf("%s*%d", attribute, n);
1448                 }
1449                 g_free(attrwnum);
1450
1451                 g_hash_table_insert(table, g_strdup(attribute), g_strdup(value->str));
1452                 g_string_free(value, TRUE);
1453         }
1454         slist_free_strings(concatlist);
1455         g_slist_free(concatlist);
1456
1457         for (cur = convlist; cur != NULL; cur = g_slist_next(cur)) {
1458                 gchar *attribute, *key, *value;
1459                 gchar *charset, *lang, *oldvalue, *newvalue;
1460
1461                 attribute = (gchar *) cur->data;
1462                 if (!g_hash_table_lookup_extended(table, attribute, (gpointer *) &key, (gpointer *) &value))
1463                         continue;
1464
1465                 charset = value;
1466                 lang = strchr(charset, '\'');
1467                 if (lang == NULL)
1468                         continue;
1469                 lang[0] = '\0';
1470                 lang++;
1471                 oldvalue = strchr(lang, '\'');
1472                 if (oldvalue == NULL)
1473                         continue;
1474                 oldvalue[0] = '\0';
1475                 oldvalue++;
1476
1477                 newvalue = conv_codeset_strdup(oldvalue, charset, conv_get_current_charset_str());
1478
1479                 g_hash_table_remove(table, attribute);
1480                 g_free(key);
1481                 g_free(value);
1482
1483                 g_hash_table_insert(table, g_strdup(attribute), newvalue);
1484         }
1485         slist_free_strings(convlist);
1486         g_slist_free(convlist);
1487
1488         g_free(params);
1489 }       
1490
1491 static void procmime_parse_content_type(const gchar *content_type, MimeInfo *mimeinfo)
1492 {
1493         g_return_if_fail(content_type != NULL);
1494         g_return_if_fail(mimeinfo != NULL);
1495
1496         /* RFC 2045, page 13 says that the mime subtype is MANDATORY;
1497          * if it's not available we use the default Content-Type */
1498         if ((content_type[0] == '\0') || (strchr(content_type, '/') == NULL)) {
1499                 mimeinfo->type = MIMETYPE_TEXT;
1500                 mimeinfo->subtype = g_strdup("plain");
1501                 if (g_hash_table_lookup(mimeinfo->typeparameters,
1502                                        "charset") == NULL)
1503                         g_hash_table_insert(mimeinfo->typeparameters,
1504                                             g_strdup("charset"),
1505                                             g_strdup("us-ascii"));
1506         } else {
1507                 gchar *type, *subtype, *params;
1508
1509                 type = g_strdup(content_type);
1510                 subtype = strchr(type, '/') + 1;
1511                 *(subtype - 1) = '\0';
1512                 if ((params = strchr(subtype, ';')) != NULL) {
1513                         params[0] = '\0';
1514                         params++;
1515                 }
1516
1517                 mimeinfo->type = procmime_get_media_type(type);
1518                 mimeinfo->subtype = g_strdup(subtype);
1519
1520                 /* Get mimeinfo->typeparameters */
1521                 if (params != NULL)
1522                         parse_parameters(params, mimeinfo->typeparameters);
1523
1524                 g_free(type);
1525         }
1526 }
1527
1528 static void procmime_parse_content_disposition(const gchar *content_disposition, MimeInfo *mimeinfo)
1529 {
1530         gchar *tmp, *params;
1531
1532         g_return_if_fail(content_disposition != NULL);
1533         g_return_if_fail(mimeinfo != NULL);
1534
1535         tmp = g_strdup(content_disposition);
1536         if ((params = strchr(tmp, ';')) != NULL) {
1537                 params[0] = '\0';
1538                 params++;
1539         }       
1540         g_strstrip(tmp);
1541
1542         if (!g_strcasecmp(tmp, "inline")) 
1543                 mimeinfo->disposition = DISPOSITIONTYPE_INLINE;
1544         else if (!g_strcasecmp(tmp, "attachment"))
1545                 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1546         else
1547                 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1548         
1549         if (params != NULL)
1550                 parse_parameters(params, mimeinfo->dispositionparameters);
1551
1552         g_free(tmp);
1553 }
1554
1555
1556 static void procmime_parse_content_encoding(const gchar *content_encoding, MimeInfo *mimeinfo)
1557 {
1558         struct EncodingTable *enc_table;
1559         
1560         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1561                 if (g_strcasecmp(enc_table->str, content_encoding) == 0) {
1562                         mimeinfo->encoding_type = enc_table->enc_type;
1563                         return;
1564                 }
1565         }
1566         mimeinfo->encoding_type = ENC_UNKNOWN;
1567         return;
1568 }
1569
1570 void procmime_parse_mimepart(MimeInfo *parent,
1571                              gchar *content_type,
1572                              gchar *content_encoding,
1573                              gchar *content_description,
1574                              gchar *content_id,
1575                              gchar *content_disposition,
1576                              const gchar *filename,
1577                              guint offset,
1578                              guint length)
1579 {
1580         MimeInfo *mimeinfo;
1581
1582         /* Create MimeInfo */
1583         mimeinfo = procmime_mimeinfo_new();
1584         mimeinfo->content = MIMECONTENT_FILE;
1585         if (parent != NULL)
1586                 g_node_append(parent->node, mimeinfo->node);
1587         mimeinfo->data.filename = g_strdup(filename);
1588         mimeinfo->offset = offset;
1589         mimeinfo->length = length;
1590
1591         if (content_type != NULL) {
1592                 procmime_parse_content_type(content_type, mimeinfo);
1593         } else {
1594                 mimeinfo->type = MIMETYPE_TEXT;
1595                 mimeinfo->subtype = g_strdup("plain");
1596                 if (g_hash_table_lookup(mimeinfo->typeparameters,
1597                                        "charset") == NULL)
1598                         g_hash_table_insert(mimeinfo->typeparameters, g_strdup("charset"), g_strdup("us-ascii"));
1599         }
1600
1601         if (content_encoding != NULL) {
1602                 procmime_parse_content_encoding(content_encoding, mimeinfo);
1603         } else {
1604                 mimeinfo->encoding_type = ENC_UNKNOWN;
1605         }
1606
1607         if (content_description != NULL)
1608                 mimeinfo->description = g_strdup(content_description);
1609         else
1610                 mimeinfo->description = NULL;
1611
1612         if (content_id != NULL)
1613                 mimeinfo->id = g_strdup(content_id);
1614         else
1615                 mimeinfo->id = NULL;
1616
1617         if (content_disposition != NULL) 
1618                 procmime_parse_content_disposition(content_disposition, mimeinfo);
1619         else
1620                 mimeinfo->disposition = DISPOSITIONTYPE_UNKNOWN;
1621
1622         /* Call parser for mime type */
1623         switch (mimeinfo->type) {
1624                 case MIMETYPE_MESSAGE:
1625                         if (g_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
1626                                 procmime_parse_message_rfc822(mimeinfo);
1627                         }
1628                         break;
1629                         
1630                 case MIMETYPE_MULTIPART:
1631                         procmime_parse_multipart(mimeinfo);
1632                         break;
1633                         
1634                 default:
1635                         break;
1636         }
1637 }
1638
1639 static gchar *typenames[] = {
1640     "text",
1641     "image",
1642     "audio",
1643     "video",
1644     "application",
1645     "message",
1646     "multipart",
1647     "unknown",
1648 };
1649
1650 static gboolean output_func(GNode *node, gpointer data)
1651 {
1652         guint i, depth;
1653         MimeInfo *mimeinfo = (MimeInfo *) node->data;
1654
1655         depth = g_node_depth(node);
1656         for (i = 0; i < depth; i++)
1657                 printf("    ");
1658         printf("%s/%s (offset:%d length:%d encoding: %d)\n", typenames[mimeinfo->type], mimeinfo->subtype, mimeinfo->offset, mimeinfo->length, mimeinfo->encoding_type);
1659
1660         return FALSE;
1661 }
1662
1663 static void output_mime_structure(MimeInfo *mimeinfo, int indent)
1664 {
1665         g_node_traverse(mimeinfo->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1, output_func, NULL);
1666 }
1667
1668 MimeInfo *procmime_scan_file_with_offset(const gchar *filename, int offset)
1669 {
1670         MimeInfo *mimeinfo;
1671         struct stat buf;
1672
1673         stat(filename, &buf);
1674
1675         mimeinfo = procmime_mimeinfo_new();
1676         mimeinfo->content = MIMECONTENT_FILE;
1677         mimeinfo->encoding_type = ENC_UNKNOWN;
1678         mimeinfo->type = MIMETYPE_MESSAGE;
1679         mimeinfo->subtype = g_strdup("rfc822");
1680         mimeinfo->data.filename = g_strdup(filename);
1681         mimeinfo->offset = offset;
1682         mimeinfo->length = buf.st_size - offset;
1683
1684         procmime_parse_message_rfc822(mimeinfo);
1685         if (debug_get_mode())
1686                 output_mime_structure(mimeinfo, 0);
1687
1688         return mimeinfo;
1689 }
1690
1691 MimeInfo *procmime_scan_file(const gchar *filename)
1692 {
1693         MimeInfo *mimeinfo;
1694
1695         g_return_val_if_fail(filename != NULL, NULL);
1696
1697         mimeinfo = procmime_scan_file_with_offset(filename, 0);
1698
1699         return mimeinfo;
1700 }
1701
1702 MimeInfo *procmime_scan_queue_file(const gchar *filename)
1703 {
1704         FILE *fp;
1705         MimeInfo *mimeinfo;
1706         gchar buf[BUFFSIZE];
1707         gint offset = 0;
1708
1709         g_return_val_if_fail(filename != NULL, NULL);
1710
1711         /* Open file */
1712         if ((fp = fopen(filename, "rb")) == NULL)
1713                 return NULL;
1714         /* Skip queue header */
1715         while (fgets(buf, sizeof(buf), fp) != NULL)
1716                 if (buf[0] == '\r' || buf[0] == '\n') break;
1717         offset = ftell(fp);
1718         fclose(fp);
1719
1720         mimeinfo = procmime_scan_file_with_offset(filename, offset);
1721
1722         return mimeinfo;
1723 }
1724
1725 typedef enum {
1726     ENC_AS_TOKEN,
1727     ENC_AS_QUOTED_STRING,
1728     ENC_AS_EXTENDED,
1729 } EncodeAs;
1730
1731 typedef struct _ParametersData {
1732         FILE *fp;
1733         guint len;
1734 } ParametersData;
1735
1736 static void write_parameters(gpointer key, gpointer value, gpointer user_data)
1737 {
1738         gchar *param = key;
1739         gchar *val = value, *valpos;
1740         ParametersData *pdata = (ParametersData *)user_data;
1741         GString *buf = g_string_new("");
1742
1743         EncodeAs encas = ENC_AS_TOKEN;
1744
1745         for (valpos = val; *valpos != 0; valpos++) {
1746                 if (!IS_ASCII(*valpos)) {
1747                         encas = ENC_AS_EXTENDED;
1748                         break;
1749                 }
1750             
1751                 /* CTLs */
1752                 if (((*valpos >= 0) && (*valpos < 037)) || (*valpos == 0177)) {
1753                         encas = ENC_AS_QUOTED_STRING;
1754                         continue;
1755                 }
1756
1757                 /* tspecials + SPACE */
1758                 switch (*valpos) {
1759                 case ' ':
1760                 case '(': 
1761                 case ')':
1762                 case '<':
1763                 case '>':
1764                 case '@':
1765                 case ',':
1766                 case ';':
1767                 case ':':
1768                 case '\\':
1769                 case '"':
1770                 case '/':
1771                 case '[':
1772                 case ']':
1773                 case '?':
1774                 case '=':
1775                         encas = ENC_AS_QUOTED_STRING;
1776                         continue;
1777                 }
1778         }
1779
1780         switch (encas) {
1781         case ENC_AS_TOKEN:
1782                 g_string_sprintfa(buf, "%s=%s", param, val);
1783                 break;
1784
1785         case ENC_AS_QUOTED_STRING:
1786                 g_string_sprintfa(buf, "%s=\"%s\"", param, val);
1787                 break;
1788
1789         case ENC_AS_EXTENDED:
1790                 g_string_sprintfa(buf, "%s*=%s''", param,
1791                         conv_get_current_charset_str());
1792                 for (valpos = val; *valpos != '\0'; valpos++) {
1793                         if (IS_ASCII(*valpos) && isalnum(*valpos)) {
1794                                 g_string_sprintfa(buf, "%c", *valpos);
1795                         } else {
1796                                 gchar hexstr[3] = "XX";
1797                                 get_hex_str(hexstr, *valpos);
1798                                 g_string_sprintfa(buf, "%%%s", hexstr);
1799                         }
1800                 }
1801                 break;
1802         }
1803         
1804         if (buf->str && strlen(buf->str)) {
1805                 if (pdata->len + strlen(buf->str) + 2 > 76) {
1806                         fprintf(pdata->fp, ";\n %s", buf->str);
1807                         pdata->len = strlen(buf->str) + 1;
1808                 } else {
1809                         fprintf(pdata->fp, "; %s", buf->str);
1810                         pdata->len += strlen(buf->str) + 2;
1811                 }
1812         }
1813         g_string_free(buf, TRUE);
1814 }
1815
1816 void procmime_write_mime_header(MimeInfo *mimeinfo, FILE *fp)
1817 {
1818         struct TypeTable *type_table;
1819         ParametersData *pdata = g_new0(ParametersData, 1);
1820         debug_print("procmime_write_mime_header\n");
1821         
1822         pdata->fp = fp;
1823
1824         for (type_table = mime_type_table; type_table->str != NULL; type_table++)
1825                 if (mimeinfo->type == type_table->type) {
1826                         gchar *buf = g_strdup_printf(
1827                                 "Content-Type: %s/%s", type_table->str, mimeinfo->subtype);
1828                         fprintf(fp, "%s", buf);
1829                         pdata->len = strlen(buf);
1830                         g_free(buf);
1831                         break;
1832                 }
1833         g_hash_table_foreach(mimeinfo->typeparameters, write_parameters, pdata);
1834         g_free(pdata);
1835
1836         fprintf(fp, "\n");
1837
1838         if (mimeinfo->encoding_type != ENC_UNKNOWN)
1839                 fprintf(fp, "Content-Transfer-Encoding: %s\n", procmime_get_encoding_str(mimeinfo->encoding_type));
1840
1841         if (mimeinfo->description != NULL)
1842                 fprintf(fp, "Content-Description: %s\n", mimeinfo->description);
1843
1844         if (mimeinfo->id != NULL)
1845                 fprintf(fp, "Content-ID: %s\n", mimeinfo->id);
1846
1847         if (mimeinfo->disposition != DISPOSITIONTYPE_UNKNOWN) {
1848                 ParametersData *pdata = g_new0(ParametersData, 1);
1849                 gchar *buf = NULL;
1850                 if (mimeinfo->disposition == DISPOSITIONTYPE_INLINE)
1851                         buf = g_strdup("Content-Disposition: inline");
1852                 else if (mimeinfo->disposition == DISPOSITIONTYPE_ATTACHMENT)
1853                         buf = g_strdup("Content-Disposition: attachment");
1854                 else
1855                         buf = g_strdup("Content-Disposition: unknown");
1856
1857                 fprintf(fp, "%s", buf);
1858                 pdata->len = strlen(buf);
1859                 g_free(buf);
1860
1861                 pdata->fp = fp;
1862                 g_hash_table_foreach(mimeinfo->dispositionparameters, write_parameters, pdata);
1863                 g_free(pdata);
1864                 fprintf(fp, "\n");
1865         }
1866
1867         fprintf(fp, "\n");
1868 }
1869
1870 gint procmime_write_message_rfc822(MimeInfo *mimeinfo, FILE *fp)
1871 {
1872         FILE *infp;
1873         GNode *childnode;
1874         MimeInfo *child;
1875         gchar buf[BUFFSIZE];
1876         gboolean skip = FALSE;;
1877
1878         debug_print("procmime_write_message_rfc822\n");
1879
1880         /* write header */
1881         switch (mimeinfo->content) {
1882         case MIMECONTENT_FILE:
1883                 if ((infp = fopen(mimeinfo->data.filename, "rb")) == NULL) {
1884                         FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1885                         return -1;
1886                 }
1887                 fseek(infp, mimeinfo->offset, SEEK_SET);
1888                 while (fgets(buf, sizeof(buf), infp) == buf) {
1889                         if (buf[0] == '\n' && buf[1] == '\0')
1890                                 break;
1891                         if (skip && (buf[0] == ' ' || buf[0] == '\t'))
1892                                 continue;
1893                         if (g_strncasecmp(buf, "Mime-Version:", 13) == 0 ||
1894                             g_strncasecmp(buf, "Content-Type:", 13) == 0 ||
1895                             g_strncasecmp(buf, "Content-Transfer-Encoding:", 26) == 0 ||
1896                             g_strncasecmp(buf, "Content-Description:", 20) == 0 ||
1897                             g_strncasecmp(buf, "Content-ID:", 11) == 0 ||
1898                             g_strncasecmp(buf, "Content-Disposition:", 20) == 0) {
1899                                 skip = TRUE;
1900                                 continue;
1901                         }
1902                         fwrite(buf, sizeof(gchar), strlen(buf), fp);
1903                         skip = FALSE;
1904                 }
1905                 fclose(infp);
1906                 break;
1907
1908         case MIMECONTENT_MEM:
1909                 fwrite(mimeinfo->data.mem, strlen(mimeinfo->data.mem), sizeof(gchar), fp);
1910                 break;
1911
1912         default:
1913                 break;
1914         }
1915
1916         childnode = mimeinfo->node->children;
1917         if (childnode == NULL)
1918                 return -1;
1919
1920         child = (MimeInfo *) childnode->data;
1921         fprintf(fp, "Mime-Version: 1.0\n");
1922         procmime_write_mime_header(child, fp);
1923         return procmime_write_mimeinfo(child, fp);
1924 }
1925
1926 gint procmime_write_multipart(MimeInfo *mimeinfo, FILE *fp)
1927 {
1928         FILE *infp;
1929         GNode *childnode;
1930         gchar *boundary, *str, *str2;
1931         gchar buf[BUFFSIZE];
1932         gboolean firstboundary;
1933
1934         debug_print("procmime_write_multipart\n");
1935
1936         boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
1937
1938         switch (mimeinfo->content) {
1939         case MIMECONTENT_FILE:
1940                 if ((infp = fopen(mimeinfo->data.filename, "rb")) == NULL) {
1941                         FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1942                         return -1;
1943                 }
1944                 fseek(infp, mimeinfo->offset, SEEK_SET);
1945                 while (fgets(buf, sizeof(buf), infp) == buf) {
1946                         if (IS_BOUNDARY(buf, boundary, strlen(boundary)))
1947                                 break;
1948                         fwrite(buf, sizeof(gchar), strlen(buf), fp);
1949                 }
1950                 fclose(infp);
1951                 break;
1952
1953         case MIMECONTENT_MEM:
1954                 str = g_strdup(mimeinfo->data.mem);
1955                 if (((str2 = strstr(str, boundary)) != NULL) && ((str2 - str) >= 2) &&
1956                     (*(str2 - 1) == '-') && (*(str2 - 2) == '-'))
1957                         *(str2 - 2) = '\0';
1958                 fwrite(str, strlen(str), sizeof(gchar), fp);
1959                 g_free(str);
1960                 break;
1961
1962         default:
1963                 break;
1964         }
1965
1966         childnode = mimeinfo->node->children;
1967         firstboundary = TRUE;
1968         while (childnode != NULL) {
1969                 MimeInfo *child = childnode->data;
1970
1971                 if (firstboundary)
1972                         firstboundary = FALSE;
1973                 else
1974                         fprintf(fp, "\n");
1975                 fprintf(fp, "--%s\n", boundary);
1976
1977                 procmime_write_mime_header(child, fp);
1978                 if (procmime_write_mimeinfo(child, fp) < 0)
1979                         return -1;
1980
1981                 childnode = g_node_next_sibling(childnode);
1982         }       
1983         fprintf(fp, "\n--%s--\n", boundary);
1984
1985         return 0;
1986 }
1987
1988 gint procmime_write_mimeinfo(MimeInfo *mimeinfo, FILE *fp)
1989 {
1990         FILE *infp;
1991
1992         debug_print("procmime_write_mimeinfo\n");
1993
1994         if (G_NODE_IS_LEAF(mimeinfo->node)) {
1995                 switch (mimeinfo->content) {
1996                 case MIMECONTENT_FILE:
1997                         if ((infp = fopen(mimeinfo->data.filename, "rb")) == NULL) {
1998                                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1999                                 return -1;
2000                         }
2001                         copy_file_part_to_fp(infp, mimeinfo->offset, mimeinfo->length, fp);
2002                         fclose(infp);
2003                         return 0;
2004
2005                 case MIMECONTENT_MEM:
2006                         fwrite(mimeinfo->data.mem, strlen(mimeinfo->data.mem), sizeof(gchar), fp);
2007                         return 0;
2008
2009                 default:
2010                         return 0;
2011                 }
2012         } else {
2013                 /* Call writer for mime type */
2014                 switch (mimeinfo->type) {
2015                 case MIMETYPE_MESSAGE:
2016                         if (g_strcasecmp(mimeinfo->subtype, "rfc822") == 0)
2017                                 return procmime_write_message_rfc822(mimeinfo, fp);
2018                         break;
2019                         
2020                 case MIMETYPE_MULTIPART:
2021                         return procmime_write_multipart(mimeinfo, fp);
2022                         
2023                 default:
2024                         break;
2025                 }
2026
2027                 return -1;
2028         }
2029
2030         return 0;
2031 }