2006-11-18 [paul] 2.6.0cvs55
[claws.git] / src / procmime.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2006 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
551         g_return_val_if_fail(outfile != NULL, -1);
552         g_return_val_if_fail(mimeinfo != NULL, -1);
553
554         if (mimeinfo->encoding_type != ENC_BINARY && !procmime_decode_content(mimeinfo))
555                 return -1;
556
557         if ((infp = g_fopen(mimeinfo->data.filename, "rb")) == NULL) {
558                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
559                 return -1;
560         }
561         if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
562                 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
563                 fclose(infp);
564                 return -1;
565         }
566         if ((outfp = g_fopen(outfile, "wb")) == NULL) {
567                 FILE_OP_ERROR(outfile, "fopen");
568                 fclose(infp);
569                 return -1;
570         }
571
572         restlength = mimeinfo->length;
573
574         while ((restlength > 0) && ((readlength = fread(buf, 1, restlength > BUFFSIZE ? BUFFSIZE : restlength, infp)) > 0)) {
575                 fwrite(buf, 1, readlength, outfp);
576                 restlength -= readlength;
577         }
578
579         fclose(infp);
580         if (fclose(outfp) == EOF) {
581                 FILE_OP_ERROR(outfile, "fclose");
582                 g_unlink(outfile);
583                 return -1;
584         }
585
586         return 0;
587 }
588
589 struct ContentRenderer {
590         char * content_type;
591         char * renderer;
592 };
593
594 static GList * renderer_list = NULL;
595
596 static struct ContentRenderer *
597 content_renderer_new(char * content_type, char * renderer)
598 {
599         struct ContentRenderer * cr;
600
601         cr = g_new(struct ContentRenderer, 1);
602         if (cr == NULL)
603                 return NULL;
604
605         cr->content_type = g_strdup(content_type);
606         cr->renderer = g_strdup(renderer);
607
608         return cr;
609 }
610
611 static void content_renderer_free(struct ContentRenderer * cr)
612 {
613         g_free(cr->content_type);
614         g_free(cr->renderer);
615         g_free(cr);
616 }
617
618 void renderer_read_config(void)
619 {
620         gchar buf[BUFFSIZE];
621         FILE * f;
622         gchar * rcpath;
623
624         g_list_foreach(renderer_list, (GFunc) content_renderer_free, NULL);
625         renderer_list = NULL;
626
627         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, RENDERER_RC, NULL);
628         f = g_fopen(rcpath, "rb");
629         g_free(rcpath);
630         
631         if (f == NULL)
632                 return;
633
634         while (fgets(buf, BUFFSIZE, f)) {
635                 char * p;
636                 struct ContentRenderer * cr;
637
638                 strretchomp(buf);
639                 p = strchr(buf, ' ');
640                 if (p == NULL)
641                         continue;
642                 * p = 0;
643
644                 cr = content_renderer_new(buf, p + 1);
645                 if (cr == NULL)
646                         continue;
647
648                 renderer_list = g_list_append(renderer_list, cr);
649         }
650
651         fclose(f);
652 }
653
654 void renderer_write_config(void)
655 {
656         gchar * rcpath;
657         PrefFile *pfile;
658         GList * cur;
659
660         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, RENDERER_RC, NULL);
661         
662         if ((pfile = prefs_write_open(rcpath)) == NULL) {
663                 g_warning("failed to write configuration to file\n");
664                 g_free(rcpath);
665                 return;
666         }
667
668         g_free(rcpath);
669
670         for (cur = renderer_list ; cur != NULL ; cur = cur->next) {
671                 struct ContentRenderer * renderer;
672                 renderer = cur->data;
673                 fprintf(pfile->fp, "%s %s\n", renderer->content_type,
674                         renderer->renderer);
675         }
676
677         if (prefs_file_close(pfile) < 0) {
678                 g_warning("failed to write configuration to file\n");
679                 return;
680         }
681 }
682
683 FILE *procmime_get_text_content(MimeInfo *mimeinfo)
684 {
685         FILE *tmpfp, *outfp;
686         const gchar *src_codeset;
687         gboolean conv_fail = FALSE;
688         gchar buf[BUFFSIZE];
689         gchar *str;
690         struct ContentRenderer * renderer;
691         GList * cur;
692         gchar *tmpfile, *content_type;
693     
694         g_return_val_if_fail(mimeinfo != NULL, NULL);
695
696         if (!procmime_decode_content(mimeinfo))
697                 return NULL;
698
699         tmpfile = procmime_get_tmp_file_name(mimeinfo);
700         if (tmpfile == NULL)
701                 return NULL;
702
703         if (procmime_get_part(tmpfile, mimeinfo) < 0) {
704                 g_free(tmpfile);
705                 return NULL;
706         }
707
708         tmpfp = g_fopen(tmpfile, "rb");
709         if (tmpfp == NULL) {
710                 g_free(tmpfile);
711                 return NULL;
712         }
713
714         if ((outfp = my_tmpfile()) == NULL) {
715                 perror("tmpfile");
716                 fclose(tmpfp);
717                 g_free(tmpfile);
718                 return NULL;
719         }
720
721         src_codeset = forced_charset
722                       ? forced_charset : 
723                       procmime_mimeinfo_get_parameter(mimeinfo, "charset");
724
725         renderer = NULL;
726
727         content_type = procmime_get_content_type_str(mimeinfo->type,
728                                                      mimeinfo->subtype);
729         for (cur = renderer_list ; cur != NULL ; cur = cur->next) {
730                 struct ContentRenderer * cr;
731
732                 cr = cur->data;
733                 if (g_ascii_strcasecmp(cr->content_type, content_type) == 0) {
734                         renderer = cr;
735                         break;
736                 }
737         }
738         g_free(content_type);
739
740         if (renderer != NULL) {
741                 FILE * p;
742                 int oldout;
743                 
744                 oldout = dup(1);
745                 
746                 dup2(fileno(outfp), 1);
747
748                 p = popen(renderer->renderer, "w");
749                 if (p != NULL) {
750                         size_t count;
751                         
752                         while ((count =
753                                 fread(buf, sizeof(char), sizeof(buf),
754                                       tmpfp)) > 0)
755                                 fwrite(buf, sizeof(char), count, p);
756                         pclose(p);
757                 }
758                 
759                 dup2(oldout, 1);
760 /* CodeConverter seems to have no effect here */
761         } else if (mimeinfo->type == MIMETYPE_TEXT && !g_ascii_strcasecmp(mimeinfo->subtype, "html")) {
762                 SC_HTMLParser *parser;
763                 CodeConverter *conv;
764
765                 conv = conv_code_converter_new(src_codeset);
766                 parser = sc_html_parser_new(tmpfp, conv);
767                 while ((str = sc_html_parse(parser)) != NULL) {
768                         fputs(str, outfp);
769                 }
770                 sc_html_parser_destroy(parser);
771                 conv_code_converter_destroy(conv);
772         } else if (mimeinfo->type == MIMETYPE_TEXT && !g_ascii_strcasecmp(mimeinfo->subtype, "enriched")) {
773                 ERTFParser *parser;
774                 CodeConverter *conv;
775
776                 conv = conv_code_converter_new(src_codeset);
777                 parser = ertf_parser_new(tmpfp, conv);
778                 while ((str = ertf_parse(parser)) != NULL) {
779                         fputs(str, outfp);
780                 }
781                 ertf_parser_destroy(parser);
782                 conv_code_converter_destroy(conv);
783         } else if (mimeinfo->type == MIMETYPE_TEXT) {
784                 while (fgets(buf, sizeof(buf), tmpfp) != NULL) {
785                         str = conv_codeset_strdup(buf, src_codeset, CS_UTF_8);
786                         if (str) {
787                                 fputs(str, outfp);
788                                 g_free(str);
789                         } else {
790                                 conv_fail = TRUE;
791                                 fputs(buf, outfp);
792                         }
793                 }
794         }
795
796         if (conv_fail)
797                 g_warning("procmime_get_text_content(): Code conversion failed.\n");
798
799         fclose(tmpfp);
800         rewind(outfp);
801         g_unlink(tmpfile);
802         g_free(tmpfile);
803
804         return outfp;
805 }
806
807 /* search the first text part of (multipart) MIME message,
808    decode, convert it and output to outfp. */
809 FILE *procmime_get_first_text_content(MsgInfo *msginfo)
810 {
811         FILE *outfp = NULL;
812         MimeInfo *mimeinfo, *partinfo;
813
814         g_return_val_if_fail(msginfo != NULL, NULL);
815
816         mimeinfo = procmime_scan_message(msginfo);
817         if (!mimeinfo) return NULL;
818
819         partinfo = mimeinfo;
820         while (partinfo && partinfo->type != MIMETYPE_TEXT) {
821                 partinfo = procmime_mimeinfo_next(partinfo);
822         }
823         if (partinfo)
824                 outfp = procmime_get_text_content(partinfo);
825
826         procmime_mimeinfo_free_all(mimeinfo);
827
828         return outfp;
829 }
830
831
832 static gboolean find_encrypted_func(GNode *node, gpointer data)
833 {
834         MimeInfo *mimeinfo = (MimeInfo *) node->data;
835         MimeInfo **encinfo = (MimeInfo **) data;
836         
837         if (privacy_mimeinfo_is_encrypted(mimeinfo)) {
838                 *encinfo = mimeinfo;
839                 return TRUE;
840         }
841         
842         return FALSE;
843 }
844
845 static MimeInfo *find_encrypted_part(MimeInfo *rootinfo)
846 {
847         MimeInfo *encinfo = NULL;
848
849         g_node_traverse(rootinfo->node, G_IN_ORDER, G_TRAVERSE_ALL, -1,
850                 find_encrypted_func, &encinfo);
851         
852         return encinfo;
853 }
854
855 /* search the first encrypted text part of (multipart) MIME message,
856    decode, convert it and output to outfp. */
857 FILE *procmime_get_first_encrypted_text_content(MsgInfo *msginfo)
858 {
859         FILE *outfp = NULL;
860         MimeInfo *mimeinfo, *partinfo, *encinfo;
861
862         g_return_val_if_fail(msginfo != NULL, NULL);
863
864         mimeinfo = procmime_scan_message(msginfo);
865         if (!mimeinfo) {
866                 return NULL;
867         }
868
869         partinfo = mimeinfo;
870         if ((encinfo = find_encrypted_part(partinfo)) != NULL) {
871                 debug_print("decrypting message part\n");
872                 if (privacy_mimeinfo_decrypt(encinfo) < 0) {
873                         alertpanel_error(_("Couldn't decrypt: %s"),
874                                 privacy_get_error());
875                         return NULL;
876                 }
877         }
878         partinfo = mimeinfo;
879         while (partinfo && partinfo->type != MIMETYPE_TEXT) {
880                 partinfo = procmime_mimeinfo_next(partinfo);
881         }
882
883         if (partinfo)
884                 outfp = procmime_get_text_content(partinfo);
885
886         procmime_mimeinfo_free_all(mimeinfo);
887
888         return outfp;
889 }
890
891 gboolean procmime_msginfo_is_encrypted(MsgInfo *msginfo)
892 {
893         MimeInfo *mimeinfo, *partinfo;
894         gboolean result = FALSE;
895
896         g_return_val_if_fail(msginfo != NULL, FALSE);
897
898         mimeinfo = procmime_scan_message(msginfo);
899         if (!mimeinfo) {
900                 return FALSE;
901         }
902
903         partinfo = mimeinfo;
904         result = (find_encrypted_part(partinfo) != NULL);
905         procmime_mimeinfo_free_all(mimeinfo);
906
907         return result;
908 }
909
910 gboolean procmime_find_string_part(MimeInfo *mimeinfo, const gchar *filename,
911                                    const gchar *str, StrFindFunc find_func)
912 {
913         FILE *outfp;
914         gchar buf[BUFFSIZE];
915
916         g_return_val_if_fail(mimeinfo != NULL, FALSE);
917         g_return_val_if_fail(mimeinfo->type == MIMETYPE_TEXT, FALSE);
918         g_return_val_if_fail(str != NULL, FALSE);
919         g_return_val_if_fail(find_func != NULL, FALSE);
920
921         outfp = procmime_get_text_content(mimeinfo);
922
923         if (!outfp)
924                 return FALSE;
925
926         while (fgets(buf, sizeof(buf), outfp) != NULL) {
927                 strretchomp(buf);
928                 if (find_func(buf, str)) {
929                         fclose(outfp);
930                         return TRUE;
931                 }
932         }
933
934         fclose(outfp);
935
936         return FALSE;
937 }
938
939 gboolean procmime_find_string(MsgInfo *msginfo, const gchar *str,
940                               StrFindFunc find_func)
941 {
942         MimeInfo *mimeinfo;
943         MimeInfo *partinfo;
944         gchar *filename;
945         gboolean found = FALSE;
946
947         g_return_val_if_fail(msginfo != NULL, FALSE);
948         g_return_val_if_fail(str != NULL, FALSE);
949         g_return_val_if_fail(find_func != NULL, FALSE);
950
951         filename = procmsg_get_message_file(msginfo);
952         if (!filename) return FALSE;
953         mimeinfo = procmime_scan_message(msginfo);
954
955         for (partinfo = mimeinfo; partinfo != NULL;
956              partinfo = procmime_mimeinfo_next(partinfo)) {
957                 if (partinfo->type == MIMETYPE_TEXT) {
958                         if (procmime_find_string_part
959                                 (partinfo, filename, str, find_func) == TRUE) {
960                                 found = TRUE;
961                                 break;
962                         }
963                 }
964         }
965
966         procmime_mimeinfo_free_all(mimeinfo);
967         g_free(filename);
968
969         return found;
970 }
971
972 gchar *procmime_get_tmp_file_name(MimeInfo *mimeinfo)
973 {
974         static guint32 id = 0;
975         gchar *base;
976         gchar *filename;
977         gchar f_prefix[10];
978
979         g_return_val_if_fail(mimeinfo != NULL, NULL);
980
981         g_snprintf(f_prefix, sizeof(f_prefix), "%08x.", id++);
982
983         if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
984                 base = g_strdup("mimetmp.html");
985         else {
986                 const gchar *basetmp;
987
988                 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
989                 if (basetmp == NULL)
990                         basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
991                 if (basetmp == NULL)
992                         basetmp = "mimetmp";
993                 basetmp = g_path_get_basename(basetmp);
994                 if (*basetmp == '\0') 
995                         basetmp = g_strdup("mimetmp");
996                 base = conv_filename_from_utf8(basetmp);
997                 g_free((gchar*)basetmp);
998                 subst_for_shellsafe_filename(base);
999         }
1000
1001         filename = g_strconcat(get_mime_tmp_dir(), G_DIR_SEPARATOR_S,
1002                                f_prefix, base, NULL);
1003
1004         g_free(base);
1005         
1006         return filename;
1007 }
1008
1009 static GList *mime_type_list = NULL;
1010
1011 gchar *procmime_get_mime_type(const gchar *filename)
1012 {
1013         static GHashTable *mime_type_table = NULL;
1014         MimeType *mime_type;
1015         const gchar *p;
1016         gchar *ext = NULL;
1017         gchar *base;
1018
1019         if (!mime_type_table) {
1020                 mime_type_table = procmime_get_mime_type_table();
1021                 if (!mime_type_table) return NULL;
1022         }
1023
1024         base = g_path_get_basename(filename);
1025         if ((p = strrchr(base, '.')) != NULL)
1026                 Xstrdup_a(ext, p + 1, p = NULL );
1027         g_free(base);
1028         if (!p) return NULL;
1029
1030         g_strdown(ext);
1031         mime_type = g_hash_table_lookup(mime_type_table, ext);
1032         if (mime_type) {
1033                 gchar *str;
1034
1035                 str = g_strconcat(mime_type->type, "/", mime_type->sub_type,
1036                                   NULL);
1037                 return str;
1038         }
1039
1040         return NULL;
1041 }
1042
1043 static guint procmime_str_hash(gconstpointer gptr)
1044 {
1045         guint hash_result = 0;
1046         const char *str;
1047
1048         for (str = gptr; str && *str; str++) {
1049                 if (isupper(*str)) hash_result += (*str + ' ');
1050                 else hash_result += *str;
1051         }
1052
1053         return hash_result;
1054 }
1055
1056 static gint procmime_str_equal(gconstpointer gptr1, gconstpointer gptr2)
1057 {
1058         const char *str1 = gptr1;
1059         const char *str2 = gptr2;
1060
1061         return !g_utf8_collate(str1, str2);
1062 }
1063
1064 static GHashTable *procmime_get_mime_type_table(void)
1065 {
1066         GHashTable *table = NULL;
1067         GList *cur;
1068         MimeType *mime_type;
1069         gchar **exts;
1070
1071         if (!mime_type_list) {
1072                 mime_type_list = procmime_get_mime_type_list();
1073                 if (!mime_type_list) return NULL;
1074         }
1075
1076         table = g_hash_table_new(procmime_str_hash, procmime_str_equal);
1077
1078         for (cur = mime_type_list; cur != NULL; cur = cur->next) {
1079                 gint i;
1080                 gchar *key;
1081
1082                 mime_type = (MimeType *)cur->data;
1083
1084                 if (!mime_type->extension) continue;
1085
1086                 exts = g_strsplit(mime_type->extension, " ", 16);
1087                 for (i = 0; exts[i] != NULL; i++) {
1088                         /* make the key case insensitive */
1089                         g_strdown(exts[i]);
1090                         /* use previously dup'd key on overwriting */
1091                         if (g_hash_table_lookup(table, exts[i]))
1092                                 key = exts[i];
1093                         else
1094                                 key = g_strdup(exts[i]);
1095                         g_hash_table_insert(table, key, mime_type);
1096                 }
1097                 g_strfreev(exts);
1098         }
1099
1100         return table;
1101 }
1102
1103 GList *procmime_get_mime_type_list(void)
1104 {
1105         GList *list = NULL;
1106         FILE *fp;
1107         gchar buf[BUFFSIZE];
1108         gchar *p;
1109         gchar *delim;
1110         MimeType *mime_type;
1111         gboolean fp_is_glob_file = TRUE;
1112
1113         if (mime_type_list) 
1114                 return mime_type_list;
1115         
1116         if ((fp = g_fopen("/usr/share/mime/globs", "rb")) == NULL) {
1117                 fp_is_glob_file = FALSE;
1118                 if ((fp = g_fopen("/etc/mime.types", "rb")) == NULL) {
1119                         if ((fp = g_fopen(SYSCONFDIR "/mime.types", "rb")) 
1120                                 == NULL) {
1121                                 FILE_OP_ERROR(SYSCONFDIR "/mime.types", 
1122                                         "fopen");
1123                                 return NULL;
1124                         }
1125                 }
1126         }
1127
1128         while (fgets(buf, sizeof(buf), fp) != NULL) {
1129                 p = strchr(buf, '#');
1130                 if (p) *p = '\0';
1131                 g_strstrip(buf);
1132
1133                 p = buf;
1134                 
1135                 if (fp_is_glob_file) {
1136                         while (*p && !g_ascii_isspace(*p) && (*p!=':')) p++;
1137                 } else {
1138                         while (*p && !g_ascii_isspace(*p)) p++;
1139                 }
1140
1141                 if (*p) {
1142                         *p = '\0';
1143                         p++;
1144                 }
1145                 delim = strchr(buf, '/');
1146                 if (delim == NULL) continue;
1147                 *delim = '\0';
1148
1149                 mime_type = g_new(MimeType, 1);
1150                 mime_type->type = g_strdup(buf);
1151                 mime_type->sub_type = g_strdup(delim + 1);
1152
1153                 if (fp_is_glob_file) {
1154                         while (*p && (g_ascii_isspace(*p)||(*p=='*')||(*p=='.'))) p++;
1155                 } else {
1156                         while (*p && g_ascii_isspace(*p)) p++;
1157                 }
1158
1159                 if (*p)
1160                         mime_type->extension = g_strdup(p);
1161                 else
1162                         mime_type->extension = NULL;
1163
1164                 list = g_list_append(list, mime_type);
1165         }
1166
1167         fclose(fp);
1168
1169         if (!list)
1170                 g_warning("Can't read mime.types\n");
1171
1172         return list;
1173 }
1174
1175 EncodingType procmime_get_encoding_for_charset(const gchar *charset)
1176 {
1177         if (!charset)
1178                 return ENC_8BIT;
1179         else if (!g_ascii_strncasecmp(charset, "ISO-2022-", 9) ||
1180                  !g_ascii_strcasecmp(charset, "US-ASCII"))
1181                 return ENC_7BIT;
1182         else if (!g_ascii_strcasecmp(charset, "ISO-8859-5") ||
1183                  !g_ascii_strncasecmp(charset, "KOI8-", 5) ||
1184                  !g_ascii_strcasecmp(charset, "Windows-1251"))
1185                 return ENC_8BIT;
1186         else if (!g_ascii_strncasecmp(charset, "ISO-8859-", 9))
1187                 return ENC_QUOTED_PRINTABLE;
1188         else if (!g_ascii_strncasecmp(charset, "UTF-8", 5))
1189                 return ENC_QUOTED_PRINTABLE;
1190         else 
1191                 return ENC_8BIT;
1192 }
1193
1194 EncodingType procmime_get_encoding_for_text_file(const gchar *file, gboolean *has_binary)
1195 {
1196         FILE *fp;
1197         guchar buf[BUFFSIZE];
1198         size_t len;
1199         size_t octet_chars = 0;
1200         size_t total_len = 0;
1201         gfloat octet_percentage;
1202         gboolean force_b64 = FALSE;
1203
1204         if ((fp = g_fopen(file, "rb")) == NULL) {
1205                 FILE_OP_ERROR(file, "fopen");
1206                 return ENC_UNKNOWN;
1207         }
1208
1209         while ((len = fread(buf, sizeof(guchar), sizeof(buf), fp)) > 0) {
1210                 guchar *p;
1211                 gint i;
1212
1213                 for (p = buf, i = 0; i < len; ++p, ++i) {
1214                         if (*p & 0x80)
1215                                 ++octet_chars;
1216                         if (*p == '\0') {
1217                                 force_b64 = TRUE;
1218                                 *has_binary = TRUE;
1219                         }
1220                 }
1221                 total_len += len;
1222         }
1223
1224         fclose(fp);
1225         
1226         if (total_len > 0)
1227                 octet_percentage = (gfloat)octet_chars / (gfloat)total_len;
1228         else
1229                 octet_percentage = 0.0;
1230
1231         debug_print("procmime_get_encoding_for_text_file(): "
1232                     "8bit chars: %d / %d (%f%%)\n", octet_chars, total_len,
1233                     100.0 * octet_percentage);
1234
1235         if (octet_percentage > 0.20 || force_b64) {
1236                 debug_print("using BASE64\n");
1237                 return ENC_BASE64;
1238         } else if (octet_chars > 0) {
1239                 debug_print("using quoted-printable\n");
1240                 return ENC_QUOTED_PRINTABLE;
1241         } else {
1242                 debug_print("using 7bit\n");
1243                 return ENC_7BIT;
1244         }
1245 }
1246
1247 struct EncodingTable 
1248 {
1249         gchar *str;
1250         EncodingType enc_type;
1251 };
1252
1253 struct EncodingTable encoding_table[] = {
1254         {"7bit", ENC_7BIT},
1255         {"8bit", ENC_8BIT},
1256         {"binary", ENC_BINARY},
1257         {"quoted-printable", ENC_QUOTED_PRINTABLE},
1258         {"base64", ENC_BASE64},
1259         {"x-uuencode", ENC_UNKNOWN},
1260         {NULL, ENC_UNKNOWN},
1261 };
1262
1263 const gchar *procmime_get_encoding_str(EncodingType encoding)
1264 {
1265         struct EncodingTable *enc_table;
1266         
1267         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1268                 if (enc_table->enc_type == encoding)
1269                         return enc_table->str;
1270         }
1271         return NULL;
1272 }
1273
1274 /* --- NEW MIME STUFF --- */
1275 struct TypeTable
1276 {
1277         gchar *str;
1278         MimeMediaType type;
1279 };
1280
1281 static struct TypeTable mime_type_table[] = {
1282         {"text", MIMETYPE_TEXT},
1283         {"image", MIMETYPE_IMAGE},
1284         {"audio", MIMETYPE_AUDIO},
1285         {"video", MIMETYPE_VIDEO},
1286         {"application", MIMETYPE_APPLICATION},
1287         {"message", MIMETYPE_MESSAGE},
1288         {"multipart", MIMETYPE_MULTIPART},
1289         {NULL, 0},
1290 };
1291
1292 const gchar *procmime_get_media_type_str(MimeMediaType type)
1293 {
1294         struct TypeTable *type_table;
1295         
1296         for (type_table = mime_type_table; type_table->str != NULL; type_table++) {
1297                 if (type_table->type == type)
1298                         return type_table->str;
1299         }
1300         return NULL;
1301 }
1302
1303 MimeMediaType procmime_get_media_type(const gchar *str)
1304 {
1305         struct TypeTable *typetablearray;
1306
1307         for (typetablearray = mime_type_table; typetablearray->str != NULL; typetablearray++)
1308                 if (g_ascii_strncasecmp(str, typetablearray->str, strlen(typetablearray->str)) == 0)
1309                         return typetablearray->type;
1310
1311         return MIMETYPE_UNKNOWN;
1312 }
1313
1314 /*!
1315  *\brief        Safe wrapper for content type string.
1316  *
1317  *\return       const gchar * Pointer to content type string. 
1318  */
1319 gchar *procmime_get_content_type_str(MimeMediaType type,
1320                                            const char *subtype)
1321 {
1322         const gchar *type_str = NULL;
1323
1324         if (subtype == NULL || !(type_str = procmime_get_media_type_str(type)))
1325                 return g_strdup("unknown");
1326         return g_strdup_printf("%s/%s", type_str, subtype);
1327 }
1328
1329 static int procmime_parse_mimepart(MimeInfo *parent,
1330                              gchar *content_type,
1331                              gchar *content_encoding,
1332                              gchar *content_description,
1333                              gchar *content_id,
1334                              gchar *content_disposition,
1335                              gchar *content_location,
1336                              const gchar *filename,
1337                              guint offset,
1338                              guint length);
1339
1340 void procmime_parse_message_rfc822(MimeInfo *mimeinfo)
1341 {
1342         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1343                                 {"Content-Transfer-Encoding:",
1344                                                    NULL, FALSE},
1345                                 {"Content-Description:",
1346                                                    NULL, TRUE},
1347                                 {"Content-ID:",
1348                                                    NULL, TRUE},
1349                                 {"Content-Disposition:",
1350                                                    NULL, TRUE},
1351                                 {"Content-Location:",
1352                                                    NULL, TRUE},
1353                                 {"MIME-Version:",
1354                                                    NULL, TRUE},
1355                                 {NULL,             NULL, FALSE}};
1356         guint content_start, i;
1357         FILE *fp;
1358         gchar *tmp;
1359
1360         procmime_decode_content(mimeinfo);
1361
1362         fp = g_fopen(mimeinfo->data.filename, "rb");
1363         if (fp == NULL) {
1364                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1365                 return;
1366         }
1367         fseek(fp, mimeinfo->offset, SEEK_SET);
1368         procheader_get_header_fields(fp, hentry);
1369         if (hentry[0].body != NULL) {
1370                 tmp = conv_unmime_header(hentry[0].body, NULL);
1371                 g_free(hentry[0].body);
1372                 hentry[0].body = tmp;
1373         }                
1374         if (hentry[2].body != NULL) {
1375                 tmp = conv_unmime_header(hentry[2].body, NULL);
1376                 g_free(hentry[2].body);
1377                 hentry[2].body = tmp;
1378         }                
1379         if (hentry[4].body != NULL) {
1380                 tmp = conv_unmime_header(hentry[4].body, NULL);
1381                 g_free(hentry[4].body);
1382                 hentry[4].body = tmp;
1383         }                
1384         if (hentry[5].body != NULL) {
1385                 tmp = conv_unmime_header(hentry[5].body, NULL);
1386                 g_free(hentry[5].body);
1387                 hentry[5].body = tmp;
1388         }                
1389         content_start = ftell(fp);
1390         fclose(fp);
1391         
1392         procmime_parse_mimepart(mimeinfo,
1393                                 hentry[0].body, hentry[1].body,
1394                                 hentry[2].body, hentry[3].body,
1395                                 hentry[4].body, hentry[5].body,
1396                                 mimeinfo->data.filename, content_start,
1397                                 mimeinfo->length - (content_start - mimeinfo->offset));
1398         
1399         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1400                 g_free(hentry[i].body);
1401                 hentry[i].body = NULL;
1402         }
1403 }
1404
1405 void procmime_parse_multipart(MimeInfo *mimeinfo)
1406 {
1407         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1408                                 {"Content-Transfer-Encoding:",
1409                                                    NULL, FALSE},
1410                                 {"Content-Description:",
1411                                                    NULL, TRUE},
1412                                 {"Content-ID:",
1413                                                    NULL, TRUE},
1414                                 {"Content-Disposition:",
1415                                                    NULL, TRUE},
1416                                 {"Content-Location:",
1417                                                    NULL, TRUE},
1418                                 {NULL,             NULL, FALSE}};
1419         gchar *p, *tmp;
1420         gchar *boundary;
1421         gint boundary_len = 0, lastoffset = -1, i;
1422         gchar buf[BUFFSIZE];
1423         FILE *fp;
1424         int result = 0;
1425
1426         boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
1427         if (!boundary)
1428                 return;
1429         boundary_len = strlen(boundary);
1430
1431         procmime_decode_content(mimeinfo);
1432
1433         fp = g_fopen(mimeinfo->data.filename, "rb");
1434         if (fp == NULL) {
1435                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1436                 return;
1437         }
1438         fseek(fp, mimeinfo->offset, SEEK_SET);
1439         while ((p = fgets(buf, sizeof(buf), fp)) != NULL && result == 0) {
1440                 if (ftell(fp) - 1 > (mimeinfo->offset + mimeinfo->length))
1441                         break;
1442
1443                 if (IS_BOUNDARY(buf, boundary, boundary_len)) {
1444                         if (lastoffset != -1) {
1445                                 result = procmime_parse_mimepart(mimeinfo,
1446                                                         hentry[0].body, hentry[1].body,
1447                                                         hentry[2].body, hentry[3].body, 
1448                                                         hentry[4].body, hentry[5].body,
1449                                                         mimeinfo->data.filename, lastoffset,
1450                                                         (ftell(fp) - strlen(buf)) - lastoffset - 1);
1451                         }
1452                         
1453                         if (buf[2 + boundary_len]     == '-' &&
1454                             buf[2 + boundary_len + 1] == '-')
1455                                 break;
1456
1457                         for (i = 0; i < (sizeof hentry / sizeof hentry[0]) ; i++) {
1458                                 g_free(hentry[i].body);
1459                                 hentry[i].body = NULL;
1460                         }
1461                         procheader_get_header_fields(fp, hentry);
1462                         if (hentry[0].body != NULL) {
1463                                 tmp = conv_unmime_header(hentry[0].body, NULL);
1464                                 g_free(hentry[0].body);
1465                                 hentry[0].body = tmp;
1466                         }                
1467                         if (hentry[2].body != NULL) {
1468                                 tmp = conv_unmime_header(hentry[2].body, NULL);
1469                                 g_free(hentry[2].body);
1470                                 hentry[2].body = tmp;
1471                         }                
1472                         if (hentry[4].body != NULL) {
1473                                 tmp = conv_unmime_header(hentry[4].body, NULL);
1474                                 g_free(hentry[4].body);
1475                                 hentry[4].body = tmp;
1476                         }                
1477                         if (hentry[5].body != NULL) {
1478                                 tmp = conv_unmime_header(hentry[5].body, NULL);
1479                                 g_free(hentry[5].body);
1480                                 hentry[5].body = tmp;
1481                         }                
1482                         lastoffset = ftell(fp);
1483                 }
1484         }
1485         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1486                 g_free(hentry[i].body);
1487                 hentry[i].body = NULL;
1488         }
1489         fclose(fp);
1490 }
1491
1492 static void parse_parameters(const gchar *parameters, GHashTable *table)
1493 {
1494         gchar *params, *param, *next;
1495         GSList *convlist = NULL, *concatlist = NULL, *cur;
1496
1497         params = g_strdup(parameters);
1498         param = params;
1499         next = params;
1500         for (; next != NULL; param = next) {
1501                 gchar *attribute, *value, *tmp;
1502                 gint len;
1503                 gboolean convert = FALSE;
1504
1505                 next = strchr_with_skip_quote(param, '"', ';');
1506                 if (next != NULL) {
1507                         next[0] = '\0';
1508                         next++;
1509                 }
1510
1511                 g_strstrip(param);
1512
1513                 attribute = param;
1514                 value = strchr(attribute, '=');
1515                 if (value == NULL)
1516                         continue;
1517
1518                 value[0] = '\0';
1519                 value++;
1520                 while (value[0] == ' ')
1521                         value++;
1522
1523                 g_strdown(attribute);
1524
1525                 len = strlen(attribute);
1526                 if (attribute[len - 1] == '*') {
1527                         gchar *srcpos, *dstpos, *endpos;
1528
1529                         convert = TRUE;
1530                         attribute[len - 1] = '\0';
1531
1532                         srcpos = value;
1533                         dstpos = value;
1534                         endpos = value + strlen(value);
1535                         while (srcpos < endpos) {
1536                                 if (*srcpos != '%')
1537                                         *dstpos = *srcpos;
1538                                 else {
1539                                         guchar dstvalue;
1540
1541                                         if (!get_hex_value(&dstvalue, srcpos[1], srcpos[2]))
1542                                                 *dstpos = '?';
1543                                         else
1544                                                 *dstpos = dstvalue;
1545                                         srcpos += 2;
1546                                 }
1547                                 srcpos++;
1548                                 dstpos++;
1549                         }
1550                         *dstpos = '\0';
1551                 } else {
1552                         if (value[0] == '"')
1553                                 extract_quote(value, '"');
1554                         else if ((tmp = strchr(value, ' ')) != NULL)
1555                                 *tmp = '\0';
1556                 }
1557
1558                 if (attribute) {
1559                         while (attribute[0] == ' ')
1560                                 attribute++;
1561                         while (attribute[strlen(attribute)-1] == ' ') 
1562                                 attribute[strlen(attribute)-1] = '\0';
1563                 } 
1564                 if (value) {
1565                         while (value[0] == ' ')
1566                                 value++;
1567                         while (value[strlen(value)-1] == ' ') 
1568                                 value[strlen(value)-1] = '\0';
1569                 }               
1570                 if (strrchr(attribute, '*') != NULL) {
1571                         gchar *tmpattr;
1572
1573                         tmpattr = g_strdup(attribute);
1574                         tmp = strrchr(tmpattr, '*');
1575                         tmp[0] = '\0';
1576
1577                         if ((tmp[1] == '0') && (tmp[2] == '\0') && 
1578                             (g_slist_find_custom(concatlist, attribute, g_str_equal) == NULL))
1579                                 concatlist = g_slist_prepend(concatlist, g_strdup(tmpattr));
1580
1581                         if (convert && (g_slist_find_custom(convlist, attribute, g_str_equal) == NULL))
1582                                 convlist = g_slist_prepend(convlist, g_strdup(tmpattr));
1583
1584                         g_free(tmpattr);
1585                 } else if (convert) {
1586                         if (g_slist_find_custom(convlist, attribute, g_str_equal) == NULL)
1587                                 convlist = g_slist_prepend(convlist, g_strdup(attribute));
1588                 }
1589
1590                 if (g_hash_table_lookup(table, attribute) == NULL)
1591                         g_hash_table_insert(table, g_strdup(attribute), g_strdup(value));
1592         }
1593
1594         for (cur = concatlist; cur != NULL; cur = g_slist_next(cur)) {
1595                 gchar *attribute, *attrwnum, *partvalue;
1596                 gint n = 0;
1597                 GString *value;
1598
1599                 attribute = (gchar *) cur->data;
1600                 value = g_string_sized_new(64);
1601
1602                 attrwnum = g_strdup_printf("%s*%d", attribute, n);
1603                 while ((partvalue = g_hash_table_lookup(table, attrwnum)) != NULL) {
1604                         g_string_append(value, partvalue);
1605
1606                         g_free(attrwnum);
1607                         n++;
1608                         attrwnum = g_strdup_printf("%s*%d", attribute, n);
1609                 }
1610                 g_free(attrwnum);
1611
1612                 g_hash_table_insert(table, g_strdup(attribute), g_strdup(value->str));
1613                 g_string_free(value, TRUE);
1614         }
1615         slist_free_strings(concatlist);
1616         g_slist_free(concatlist);
1617
1618         for (cur = convlist; cur != NULL; cur = g_slist_next(cur)) {
1619                 gchar *attribute, *key, *value;
1620                 gchar *charset, *lang, *oldvalue, *newvalue;
1621
1622                 attribute = (gchar *) cur->data;
1623                 if (!g_hash_table_lookup_extended(
1624                         table, attribute, (gpointer *)(gchar *) &key, (gpointer *)(gchar *) &value))
1625                         continue;
1626
1627                 charset = value;
1628                 lang = strchr(charset, '\'');
1629                 if (lang == NULL)
1630                         continue;
1631                 lang[0] = '\0';
1632                 lang++;
1633                 oldvalue = strchr(lang, '\'');
1634                 if (oldvalue == NULL)
1635                         continue;
1636                 oldvalue[0] = '\0';
1637                 oldvalue++;
1638
1639                 newvalue = conv_codeset_strdup(oldvalue, charset, CS_UTF_8);
1640
1641                 g_hash_table_remove(table, attribute);
1642                 g_free(key);
1643                 g_free(value);
1644
1645                 g_hash_table_insert(table, g_strdup(attribute), newvalue);
1646         }
1647         slist_free_strings(convlist);
1648         g_slist_free(convlist);
1649
1650         g_free(params);
1651 }       
1652
1653 static void procmime_parse_content_type(const gchar *content_type, MimeInfo *mimeinfo)
1654 {
1655         g_return_if_fail(content_type != NULL);
1656         g_return_if_fail(mimeinfo != NULL);
1657
1658         /* RFC 2045, page 13 says that the mime subtype is MANDATORY;
1659          * if it's not available we use the default Content-Type */
1660         if ((content_type[0] == '\0') || (strchr(content_type, '/') == NULL)) {
1661                 mimeinfo->type = MIMETYPE_TEXT;
1662                 mimeinfo->subtype = g_strdup("plain");
1663                 if (g_hash_table_lookup(mimeinfo->typeparameters,
1664                                        "charset") == NULL) {
1665                         g_hash_table_insert(mimeinfo->typeparameters,
1666                                     g_strdup("charset"),
1667                                     g_strdup(
1668                                         conv_get_locale_charset_str_no_utf8()));
1669                 }
1670         } else {
1671                 gchar *type, *subtype, *params;
1672
1673                 type = g_strdup(content_type);
1674                 subtype = strchr(type, '/') + 1;
1675                 *(subtype - 1) = '\0';
1676                 if ((params = strchr(subtype, ';')) != NULL) {
1677                         params[0] = '\0';
1678                         params++;
1679                 }
1680
1681                 mimeinfo->type = procmime_get_media_type(type);
1682                 mimeinfo->subtype = g_strdup(subtype);
1683
1684                 /* Get mimeinfo->typeparameters */
1685                 if (params != NULL)
1686                         parse_parameters(params, mimeinfo->typeparameters);
1687
1688                 g_free(type);
1689         }
1690 }
1691
1692 static void procmime_parse_content_disposition(const gchar *content_disposition, MimeInfo *mimeinfo)
1693 {
1694         gchar *tmp, *params;
1695
1696         g_return_if_fail(content_disposition != NULL);
1697         g_return_if_fail(mimeinfo != NULL);
1698
1699         tmp = g_strdup(content_disposition);
1700         if ((params = strchr(tmp, ';')) != NULL) {
1701                 params[0] = '\0';
1702                 params++;
1703         }       
1704         g_strstrip(tmp);
1705
1706         if (!g_ascii_strcasecmp(tmp, "inline")) 
1707                 mimeinfo->disposition = DISPOSITIONTYPE_INLINE;
1708         else if (!g_ascii_strcasecmp(tmp, "attachment"))
1709                 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1710         else
1711                 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1712         
1713         if (params != NULL)
1714                 parse_parameters(params, mimeinfo->dispositionparameters);
1715
1716         g_free(tmp);
1717 }
1718
1719
1720 static void procmime_parse_content_encoding(const gchar *content_encoding, MimeInfo *mimeinfo)
1721 {
1722         struct EncodingTable *enc_table;
1723         
1724         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1725                 if (g_ascii_strcasecmp(enc_table->str, content_encoding) == 0) {
1726                         mimeinfo->encoding_type = enc_table->enc_type;
1727                         return;
1728                 }
1729         }
1730         mimeinfo->encoding_type = ENC_UNKNOWN;
1731         return;
1732 }
1733
1734 static int procmime_parse_mimepart(MimeInfo *parent,
1735                              gchar *content_type,
1736                              gchar *content_encoding,
1737                              gchar *content_description,
1738                              gchar *content_id,
1739                              gchar *content_disposition,
1740                              gchar *content_location,
1741                              const gchar *filename,
1742                              guint offset,
1743                              guint length)
1744 {
1745         MimeInfo *mimeinfo;
1746
1747         /* Create MimeInfo */
1748         mimeinfo = procmime_mimeinfo_new();
1749         mimeinfo->content = MIMECONTENT_FILE;
1750         if (parent != NULL) {
1751                 if (g_node_depth(parent->node) > 32) {
1752                         /* 32 is an arbitrary value
1753                          * this avoids DOSsing ourselves 
1754                          * with enormous messages
1755                          */
1756                         procmime_mimeinfo_free_all(mimeinfo);
1757                         return -1;                      
1758                 }
1759                 g_node_append(parent->node, mimeinfo->node);
1760         }
1761         mimeinfo->data.filename = g_strdup(filename);
1762         mimeinfo->offset = offset;
1763         mimeinfo->length = length;
1764
1765         if (content_type != NULL) {
1766                 procmime_parse_content_type(content_type, mimeinfo);
1767         } else {
1768                 mimeinfo->type = MIMETYPE_TEXT;
1769                 mimeinfo->subtype = g_strdup("plain");
1770                 if (g_hash_table_lookup(mimeinfo->typeparameters,
1771                                        "charset") == NULL) {
1772                         g_hash_table_insert(mimeinfo->typeparameters,
1773                                     g_strdup("charset"),
1774                                     g_strdup(
1775                                         conv_get_locale_charset_str_no_utf8()));
1776                 }
1777         }
1778
1779         if (content_encoding != NULL) {
1780                 procmime_parse_content_encoding(content_encoding, mimeinfo);
1781         } else {
1782                 mimeinfo->encoding_type = ENC_UNKNOWN;
1783         }
1784
1785         if (content_description != NULL)
1786                 mimeinfo->description = g_strdup(content_description);
1787         else
1788                 mimeinfo->description = NULL;
1789
1790         if (content_id != NULL)
1791                 mimeinfo->id = g_strdup(content_id);
1792         else
1793                 mimeinfo->id = NULL;
1794
1795         if (content_location != NULL)
1796                 mimeinfo->location = g_strdup(content_location);
1797         else
1798                 mimeinfo->location = NULL;
1799
1800         if (content_disposition != NULL) 
1801                 procmime_parse_content_disposition(content_disposition, mimeinfo);
1802         else
1803                 mimeinfo->disposition = DISPOSITIONTYPE_UNKNOWN;
1804
1805         /* Call parser for mime type */
1806         switch (mimeinfo->type) {
1807                 case MIMETYPE_MESSAGE:
1808                         if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
1809                                 procmime_parse_message_rfc822(mimeinfo);
1810                         }
1811                         break;
1812                         
1813                 case MIMETYPE_MULTIPART:
1814                         procmime_parse_multipart(mimeinfo);
1815                         break;
1816                         
1817                 default:
1818                         break;
1819         }
1820
1821         return 0;
1822 }
1823
1824 static gchar *typenames[] = {
1825     "text",
1826     "image",
1827     "audio",
1828     "video",
1829     "application",
1830     "message",
1831     "multipart",
1832     "unknown",
1833 };
1834
1835 static gboolean output_func(GNode *node, gpointer data)
1836 {
1837         guint i, depth;
1838         MimeInfo *mimeinfo = (MimeInfo *) node->data;
1839
1840         depth = g_node_depth(node);
1841         for (i = 0; i < depth; i++)
1842                 printf("    ");
1843         printf("%s/%s (offset:%d length:%d encoding: %d)\n", typenames[mimeinfo->type], mimeinfo->subtype, mimeinfo->offset, mimeinfo->length, mimeinfo->encoding_type);
1844
1845         return FALSE;
1846 }
1847
1848 static void output_mime_structure(MimeInfo *mimeinfo, int indent)
1849 {
1850         g_node_traverse(mimeinfo->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1, output_func, NULL);
1851 }
1852
1853 MimeInfo *procmime_scan_file_with_offset(const gchar *filename, int offset)
1854 {
1855         MimeInfo *mimeinfo;
1856         struct stat buf;
1857
1858         stat(filename, &buf);
1859
1860         mimeinfo = procmime_mimeinfo_new();
1861         mimeinfo->content = MIMECONTENT_FILE;
1862         mimeinfo->encoding_type = ENC_UNKNOWN;
1863         mimeinfo->type = MIMETYPE_MESSAGE;
1864         mimeinfo->subtype = g_strdup("rfc822");
1865         mimeinfo->data.filename = g_strdup(filename);
1866         mimeinfo->offset = offset;
1867         mimeinfo->length = buf.st_size - offset;
1868
1869         procmime_parse_message_rfc822(mimeinfo);
1870         if (debug_get_mode())
1871                 output_mime_structure(mimeinfo, 0);
1872
1873         return mimeinfo;
1874 }
1875
1876 MimeInfo *procmime_scan_file(const gchar *filename)
1877 {
1878         MimeInfo *mimeinfo;
1879
1880         g_return_val_if_fail(filename != NULL, NULL);
1881
1882         mimeinfo = procmime_scan_file_with_offset(filename, 0);
1883
1884         return mimeinfo;
1885 }
1886
1887 MimeInfo *procmime_scan_queue_file(const gchar *filename)
1888 {
1889         FILE *fp;
1890         MimeInfo *mimeinfo;
1891         gchar buf[BUFFSIZE];
1892         gint offset = 0;
1893
1894         g_return_val_if_fail(filename != NULL, NULL);
1895
1896         /* Open file */
1897         if ((fp = g_fopen(filename, "rb")) == NULL)
1898                 return NULL;
1899         /* Skip queue header */
1900         while (fgets(buf, sizeof(buf), fp) != NULL) {
1901                 /* new way */
1902                 if (!strncmp(buf, "X-Sylpheed-End-Special-Headers: 1",
1903                         strlen("X-Sylpheed-End-Special-Headers:")))
1904                         break;
1905                 /* old way */
1906                 if (buf[0] == '\r' || buf[0] == '\n') break;
1907                 /* from other mailers */
1908                 if (!strncmp(buf, "Date: ", 6)
1909                 ||  !strncmp(buf, "To: ", 4)
1910                 ||  !strncmp(buf, "From: ", 6)
1911                 ||  !strncmp(buf, "Subject: ", 9)) {
1912                         rewind(fp);
1913                         break;
1914                 }
1915         }
1916         offset = ftell(fp);
1917         fclose(fp);
1918
1919         mimeinfo = procmime_scan_file_with_offset(filename, offset);
1920
1921         return mimeinfo;
1922 }
1923
1924 typedef enum {
1925     ENC_AS_TOKEN,
1926     ENC_AS_QUOTED_STRING,
1927     ENC_AS_EXTENDED,
1928     ENC_TO_ASCII,
1929 } EncodeAs;
1930
1931 typedef struct _ParametersData {
1932         FILE *fp;
1933         guint len;
1934         guint ascii_only;
1935 } ParametersData;
1936
1937 static void write_parameters(gpointer key, gpointer value, gpointer user_data)
1938 {
1939         gchar *param = key;
1940         gchar *val = value, *valpos, *tmp;
1941         ParametersData *pdata = (ParametersData *)user_data;
1942         GString *buf = g_string_new("");
1943
1944         EncodeAs encas = ENC_AS_TOKEN;
1945
1946         for (valpos = val; *valpos != 0; valpos++) {
1947                 if (!IS_ASCII(*valpos) || *valpos == '"') {
1948                         encas = ENC_AS_EXTENDED;
1949                         break;
1950                 }
1951             
1952                 /* CTLs */
1953                 if (((*valpos >= 0) && (*valpos < 037)) || (*valpos == 0177)) {
1954                         encas = ENC_AS_QUOTED_STRING;
1955                         continue;
1956                 }
1957
1958                 /* tspecials + SPACE */
1959                 switch (*valpos) {
1960                 case ' ':
1961                 case '(': 
1962                 case ')':
1963                 case '<':
1964                 case '>':
1965                 case '@':
1966                 case ',':
1967                 case ';':
1968                 case ':':
1969                 case '\\':
1970                 case '\'':
1971                 case '/':
1972                 case '[':
1973                 case ']':
1974                 case '?':
1975                 case '=':
1976                         encas = ENC_AS_QUOTED_STRING;
1977                         continue;
1978                 }
1979         }
1980         
1981         if (encas == ENC_AS_EXTENDED && pdata->ascii_only == TRUE) 
1982                 encas = ENC_TO_ASCII;
1983
1984         switch (encas) {
1985         case ENC_AS_TOKEN:
1986                 g_string_append_printf(buf, "%s=%s", param, val);
1987                 break;
1988
1989         case ENC_TO_ASCII:
1990                 tmp = g_strdup(val);
1991                 g_strcanon(tmp, 
1992                         " ()<>@,';:\\/[]?=.0123456789"
1993                         "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1994                         "abcdefghijklmnopqrstuvwxyz",
1995                         '_');
1996                 g_string_append_printf(buf, "%s=\"%s\"", param, tmp);
1997                 g_free(tmp);
1998                 break;
1999
2000         case ENC_AS_QUOTED_STRING:
2001                 g_string_append_printf(buf, "%s=\"%s\"", param, val);
2002                 break;
2003
2004         case ENC_AS_EXTENDED:
2005                 if (!g_utf8_validate(val, -1, NULL))
2006                         g_string_append_printf(buf, "%s*=%s''", param,
2007                                 conv_get_locale_charset_str());
2008                 else
2009                         g_string_append_printf(buf, "%s*=%s''", param,
2010                                 CS_INTERNAL);
2011                 for (valpos = val; *valpos != '\0'; valpos++) {
2012                         if (IS_ASCII(*valpos) && isalnum(*valpos)) {
2013                                 g_string_append_printf(buf, "%c", *valpos);
2014                         } else {
2015                                 gchar hexstr[3] = "XX";
2016                                 get_hex_str(hexstr, *valpos);
2017                                 g_string_append_printf(buf, "%%%s", hexstr);
2018                         }
2019                 }
2020                 break;          
2021         }
2022         
2023         if (buf->str && strlen(buf->str)) {
2024                 if (pdata->len + strlen(buf->str) + 2 > 76) {
2025                         fprintf(pdata->fp, ";\n %s", buf->str);
2026                         pdata->len = strlen(buf->str) + 1;
2027                 } else {
2028                         fprintf(pdata->fp, "; %s", buf->str);
2029                         pdata->len += strlen(buf->str) + 2;
2030                 }
2031         }
2032         g_string_free(buf, TRUE);
2033 }
2034
2035 void procmime_write_mime_header(MimeInfo *mimeinfo, FILE *fp)
2036 {
2037         struct TypeTable *type_table;
2038         ParametersData *pdata = g_new0(ParametersData, 1);
2039         debug_print("procmime_write_mime_header\n");
2040         
2041         pdata->fp = fp;
2042         pdata->ascii_only = FALSE;
2043
2044         for (type_table = mime_type_table; type_table->str != NULL; type_table++)
2045                 if (mimeinfo->type == type_table->type) {
2046                         gchar *buf = g_strdup_printf(
2047                                 "Content-Type: %s/%s", type_table->str, mimeinfo->subtype);
2048                         fprintf(fp, "%s", buf);
2049                         pdata->len = strlen(buf);
2050                         pdata->ascii_only = TRUE;
2051                         g_free(buf);
2052                         break;
2053                 }
2054         g_hash_table_foreach(mimeinfo->typeparameters, write_parameters, pdata);
2055         g_free(pdata);
2056
2057         fprintf(fp, "\n");
2058
2059         if (mimeinfo->encoding_type != ENC_UNKNOWN)
2060                 fprintf(fp, "Content-Transfer-Encoding: %s\n", procmime_get_encoding_str(mimeinfo->encoding_type));
2061
2062         if (mimeinfo->description != NULL)
2063                 fprintf(fp, "Content-Description: %s\n", mimeinfo->description);
2064
2065         if (mimeinfo->id != NULL)
2066                 fprintf(fp, "Content-ID: %s\n", mimeinfo->id);
2067
2068         if (mimeinfo->location != NULL)
2069                 fprintf(fp, "Content-Location: %s\n", mimeinfo->location);
2070
2071         if (mimeinfo->disposition != DISPOSITIONTYPE_UNKNOWN) {
2072                 ParametersData *pdata = g_new0(ParametersData, 1);
2073                 gchar *buf = NULL;
2074                 if (mimeinfo->disposition == DISPOSITIONTYPE_INLINE)
2075                         buf = g_strdup("Content-Disposition: inline");
2076                 else if (mimeinfo->disposition == DISPOSITIONTYPE_ATTACHMENT)
2077                         buf = g_strdup("Content-Disposition: attachment");
2078                 else
2079                         buf = g_strdup("Content-Disposition: unknown");
2080
2081                 fprintf(fp, "%s", buf);
2082                 pdata->len = strlen(buf);
2083                 g_free(buf);
2084
2085                 pdata->fp = fp;
2086                 pdata->ascii_only = FALSE;
2087
2088                 g_hash_table_foreach(mimeinfo->dispositionparameters, write_parameters, pdata);
2089                 g_free(pdata);
2090                 fprintf(fp, "\n");
2091         }
2092
2093         fprintf(fp, "\n");
2094 }
2095
2096 gint procmime_write_message_rfc822(MimeInfo *mimeinfo, FILE *fp)
2097 {
2098         FILE *infp;
2099         GNode *childnode;
2100         MimeInfo *child;
2101         gchar buf[BUFFSIZE];
2102         gboolean skip = FALSE;;
2103
2104         debug_print("procmime_write_message_rfc822\n");
2105
2106         /* write header */
2107         switch (mimeinfo->content) {
2108         case MIMECONTENT_FILE:
2109                 if ((infp = g_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2110                         FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2111                         return -1;
2112                 }
2113                 fseek(infp, mimeinfo->offset, SEEK_SET);
2114                 while (fgets(buf, sizeof(buf), infp) == buf) {
2115                         if (buf[0] == '\n' && buf[1] == '\0')
2116                                 break;
2117                         if (skip && (buf[0] == ' ' || buf[0] == '\t'))
2118                                 continue;
2119                         if (g_ascii_strncasecmp(buf, "Mime-Version:", 13) == 0 ||
2120                             g_ascii_strncasecmp(buf, "Content-Type:", 13) == 0 ||
2121                             g_ascii_strncasecmp(buf, "Content-Transfer-Encoding:", 26) == 0 ||
2122                             g_ascii_strncasecmp(buf, "Content-Description:", 20) == 0 ||
2123                             g_ascii_strncasecmp(buf, "Content-ID:", 11) == 0 ||
2124                             g_ascii_strncasecmp(buf, "Content-Location:", 17) == 0 ||
2125                             g_ascii_strncasecmp(buf, "Content-Disposition:", 20) == 0) {
2126                                 skip = TRUE;
2127                                 continue;
2128                         }
2129                         fwrite(buf, sizeof(gchar), strlen(buf), fp);
2130                         skip = FALSE;
2131                 }
2132                 fclose(infp);
2133                 break;
2134
2135         case MIMECONTENT_MEM:
2136                 fwrite(mimeinfo->data.mem, 
2137                                 sizeof(gchar), 
2138                                 strlen(mimeinfo->data.mem), 
2139                                 fp);
2140                 break;
2141
2142         default:
2143                 break;
2144         }
2145
2146         childnode = mimeinfo->node->children;
2147         if (childnode == NULL)
2148                 return -1;
2149
2150         child = (MimeInfo *) childnode->data;
2151         fprintf(fp, "Mime-Version: 1.0\n");
2152         procmime_write_mime_header(child, fp);
2153         return procmime_write_mimeinfo(child, fp);
2154 }
2155
2156 gint procmime_write_multipart(MimeInfo *mimeinfo, FILE *fp)
2157 {
2158         FILE *infp;
2159         GNode *childnode;
2160         gchar *boundary, *str, *str2;
2161         gchar buf[BUFFSIZE];
2162         gboolean firstboundary;
2163
2164         debug_print("procmime_write_multipart\n");
2165
2166         boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
2167
2168         switch (mimeinfo->content) {
2169         case MIMECONTENT_FILE:
2170                 if ((infp = g_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2171                         FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2172                         return -1;
2173                 }
2174                 fseek(infp, mimeinfo->offset, SEEK_SET);
2175                 while (fgets(buf, sizeof(buf), infp) == buf) {
2176                         if (IS_BOUNDARY(buf, boundary, strlen(boundary)))
2177                                 break;
2178                         fwrite(buf, sizeof(gchar), strlen(buf), fp);
2179                 }
2180                 fclose(infp);
2181                 break;
2182
2183         case MIMECONTENT_MEM:
2184                 str = g_strdup(mimeinfo->data.mem);
2185                 if (((str2 = strstr(str, boundary)) != NULL) && ((str2 - str) >= 2) &&
2186                     (*(str2 - 1) == '-') && (*(str2 - 2) == '-'))
2187                         *(str2 - 2) = '\0';
2188                 fwrite(str, sizeof(gchar), strlen(str), fp);
2189                 g_free(str);
2190                 break;
2191
2192         default:
2193                 break;
2194         }
2195
2196         childnode = mimeinfo->node->children;
2197         firstboundary = TRUE;
2198         while (childnode != NULL) {
2199                 MimeInfo *child = childnode->data;
2200
2201                 if (firstboundary)
2202                         firstboundary = FALSE;
2203                 else
2204                         fprintf(fp, "\n");
2205                 fprintf(fp, "--%s\n", boundary);
2206
2207                 procmime_write_mime_header(child, fp);
2208                 if (procmime_write_mimeinfo(child, fp) < 0)
2209                         return -1;
2210
2211                 childnode = g_node_next_sibling(childnode);
2212         }       
2213         fprintf(fp, "\n--%s--\n", boundary);
2214
2215         return 0;
2216 }
2217
2218 gint procmime_write_mimeinfo(MimeInfo *mimeinfo, FILE *fp)
2219 {
2220         FILE *infp;
2221
2222         debug_print("procmime_write_mimeinfo\n");
2223
2224         if (G_NODE_IS_LEAF(mimeinfo->node)) {
2225                 switch (mimeinfo->content) {
2226                 case MIMECONTENT_FILE:
2227                         if ((infp = g_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2228                                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2229                                 return -1;
2230                         }
2231                         copy_file_part_to_fp(infp, mimeinfo->offset, mimeinfo->length, fp);
2232                         fclose(infp);
2233                         return 0;
2234
2235                 case MIMECONTENT_MEM:
2236                         fwrite(mimeinfo->data.mem, 
2237                                         sizeof(gchar), 
2238                                         strlen(mimeinfo->data.mem), 
2239                                         fp);
2240                         return 0;
2241
2242                 default:
2243                         return 0;
2244                 }
2245         } else {
2246                 /* Call writer for mime type */
2247                 switch (mimeinfo->type) {
2248                 case MIMETYPE_MESSAGE:
2249                         if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
2250                                 return procmime_write_message_rfc822(mimeinfo, fp);
2251                         }
2252                         break;
2253                         
2254                 case MIMETYPE_MULTIPART:
2255                         return procmime_write_multipart(mimeinfo, fp);
2256                         
2257                 default:
2258                         break;
2259                 }
2260
2261                 return -1;
2262         }
2263
2264         return 0;
2265 }
2266
2267 gchar *procmime_get_part_file_name(MimeInfo *mimeinfo)
2268 {
2269         gchar *base;
2270
2271         if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
2272                 base = g_strdup("mimetmp.html");
2273         else {
2274                 const gchar *basetmp;
2275                 gchar *basename;
2276
2277                 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
2278                 if (basetmp == NULL)
2279                         basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
2280                 if (basetmp == NULL)
2281                         basetmp = "mimetmp";
2282                 basename = g_path_get_basename(basetmp);
2283                 if (*basename == '\0') {
2284                         g_free(basename);
2285                         basename = g_strdup("mimetmp");
2286                 }
2287                 base = conv_filename_from_utf8(basename);
2288                 g_free(basename);
2289                 subst_for_shellsafe_filename(base);
2290         }
2291         
2292         return base;
2293 }
2294