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