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