2006-09-26 [colin] 2.5.1cvs5
[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 if (!g_ascii_strncasecmp(charset, "UTF-8", 5))
1141                 return ENC_QUOTED_PRINTABLE;
1142         else 
1143                 return ENC_8BIT;
1144 }
1145
1146 EncodingType procmime_get_encoding_for_text_file(const gchar *file, gboolean *has_binary)
1147 {
1148         FILE *fp;
1149         guchar buf[BUFFSIZE];
1150         size_t len;
1151         size_t octet_chars = 0;
1152         size_t total_len = 0;
1153         gfloat octet_percentage;
1154         gboolean force_b64 = FALSE;
1155
1156         if ((fp = g_fopen(file, "rb")) == NULL) {
1157                 FILE_OP_ERROR(file, "fopen");
1158                 return ENC_UNKNOWN;
1159         }
1160
1161         while ((len = fread(buf, sizeof(guchar), sizeof(buf), fp)) > 0) {
1162                 guchar *p;
1163                 gint i;
1164
1165                 for (p = buf, i = 0; i < len; ++p, ++i) {
1166                         if (*p & 0x80)
1167                                 ++octet_chars;
1168                         if (*p == '\0') {
1169                                 force_b64 = TRUE;
1170                                 *has_binary = TRUE;
1171                         }
1172                 }
1173                 total_len += len;
1174         }
1175
1176         fclose(fp);
1177         
1178         if (total_len > 0)
1179                 octet_percentage = (gfloat)octet_chars / (gfloat)total_len;
1180         else
1181                 octet_percentage = 0.0;
1182
1183         debug_print("procmime_get_encoding_for_text_file(): "
1184                     "8bit chars: %d / %d (%f%%)\n", octet_chars, total_len,
1185                     100.0 * octet_percentage);
1186
1187         if (octet_percentage > 0.20 || force_b64) {
1188                 debug_print("using BASE64\n");
1189                 return ENC_BASE64;
1190         } else if (octet_chars > 0) {
1191                 debug_print("using quoted-printable\n");
1192                 return ENC_QUOTED_PRINTABLE;
1193         } else {
1194                 debug_print("using 7bit\n");
1195                 return ENC_7BIT;
1196         }
1197 }
1198
1199 struct EncodingTable 
1200 {
1201         gchar *str;
1202         EncodingType enc_type;
1203 };
1204
1205 struct EncodingTable encoding_table[] = {
1206         {"7bit", ENC_7BIT},
1207         {"8bit", ENC_8BIT},
1208         {"binary", ENC_BINARY},
1209         {"quoted-printable", ENC_QUOTED_PRINTABLE},
1210         {"base64", ENC_BASE64},
1211         {"x-uuencode", ENC_UNKNOWN},
1212         {NULL, ENC_UNKNOWN},
1213 };
1214
1215 const gchar *procmime_get_encoding_str(EncodingType encoding)
1216 {
1217         struct EncodingTable *enc_table;
1218         
1219         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1220                 if (enc_table->enc_type == encoding)
1221                         return enc_table->str;
1222         }
1223         return NULL;
1224 }
1225
1226 /* --- NEW MIME STUFF --- */
1227 struct TypeTable
1228 {
1229         gchar *str;
1230         MimeMediaType type;
1231 };
1232
1233 static struct TypeTable mime_type_table[] = {
1234         {"text", MIMETYPE_TEXT},
1235         {"image", MIMETYPE_IMAGE},
1236         {"audio", MIMETYPE_AUDIO},
1237         {"video", MIMETYPE_VIDEO},
1238         {"application", MIMETYPE_APPLICATION},
1239         {"message", MIMETYPE_MESSAGE},
1240         {"multipart", MIMETYPE_MULTIPART},
1241         {NULL, 0},
1242 };
1243
1244 const gchar *procmime_get_media_type_str(MimeMediaType type)
1245 {
1246         struct TypeTable *type_table;
1247         
1248         for (type_table = mime_type_table; type_table->str != NULL; type_table++) {
1249                 if (type_table->type == type)
1250                         return type_table->str;
1251         }
1252         return NULL;
1253 }
1254
1255 MimeMediaType procmime_get_media_type(const gchar *str)
1256 {
1257         struct TypeTable *typetablearray;
1258
1259         for (typetablearray = mime_type_table; typetablearray->str != NULL; typetablearray++)
1260                 if (g_ascii_strncasecmp(str, typetablearray->str, strlen(typetablearray->str)) == 0)
1261                         return typetablearray->type;
1262
1263         return MIMETYPE_UNKNOWN;
1264 }
1265
1266 /*!
1267  *\brief        Safe wrapper for content type string.
1268  *
1269  *\return       const gchar * Pointer to content type string. 
1270  */
1271 gchar *procmime_get_content_type_str(MimeMediaType type,
1272                                            const char *subtype)
1273 {
1274         const gchar *type_str = NULL;
1275
1276         if (subtype == NULL || !(type_str = procmime_get_media_type_str(type)))
1277                 return g_strdup("unknown");
1278         return g_strdup_printf("%s/%s", type_str, subtype);
1279 }
1280
1281 static int procmime_parse_mimepart(MimeInfo *parent,
1282                              gchar *content_type,
1283                              gchar *content_encoding,
1284                              gchar *content_description,
1285                              gchar *content_id,
1286                              gchar *content_disposition,
1287                              gchar *content_location,
1288                              const gchar *filename,
1289                              guint offset,
1290                              guint length);
1291
1292 void procmime_parse_message_rfc822(MimeInfo *mimeinfo)
1293 {
1294         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1295                                 {"Content-Transfer-Encoding:",
1296                                                    NULL, FALSE},
1297                                 {"Content-Description:",
1298                                                    NULL, TRUE},
1299                                 {"Content-ID:",
1300                                                    NULL, TRUE},
1301                                 {"Content-Disposition:",
1302                                                    NULL, TRUE},
1303                                 {"Content-Location:",
1304                                                    NULL, TRUE},
1305                                 {"MIME-Version:",
1306                                                    NULL, TRUE},
1307                                 {NULL,             NULL, FALSE}};
1308         guint content_start, i;
1309         FILE *fp;
1310         gchar *tmp;
1311
1312         procmime_decode_content(mimeinfo);
1313
1314         fp = g_fopen(mimeinfo->data.filename, "rb");
1315         if (fp == NULL) {
1316                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1317                 return;
1318         }
1319         fseek(fp, mimeinfo->offset, SEEK_SET);
1320         procheader_get_header_fields(fp, hentry);
1321         if (hentry[0].body != NULL) {
1322                 tmp = conv_unmime_header(hentry[0].body, NULL);
1323                 g_free(hentry[0].body);
1324                 hentry[0].body = tmp;
1325         }                
1326         if (hentry[2].body != NULL) {
1327                 tmp = conv_unmime_header(hentry[2].body, NULL);
1328                 g_free(hentry[2].body);
1329                 hentry[2].body = tmp;
1330         }                
1331         if (hentry[4].body != NULL) {
1332                 tmp = conv_unmime_header(hentry[4].body, NULL);
1333                 g_free(hentry[4].body);
1334                 hentry[4].body = tmp;
1335         }                
1336         if (hentry[5].body != NULL) {
1337                 tmp = conv_unmime_header(hentry[5].body, NULL);
1338                 g_free(hentry[5].body);
1339                 hentry[5].body = tmp;
1340         }                
1341         content_start = ftell(fp);
1342         fclose(fp);
1343         
1344         procmime_parse_mimepart(mimeinfo,
1345                                 hentry[0].body, hentry[1].body,
1346                                 hentry[2].body, hentry[3].body,
1347                                 hentry[4].body, hentry[5].body,
1348                                 mimeinfo->data.filename, content_start,
1349                                 mimeinfo->length - (content_start - mimeinfo->offset));
1350         
1351         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1352                 g_free(hentry[i].body);
1353                 hentry[i].body = NULL;
1354         }
1355 }
1356
1357 void procmime_parse_multipart(MimeInfo *mimeinfo)
1358 {
1359         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1360                                 {"Content-Transfer-Encoding:",
1361                                                    NULL, FALSE},
1362                                 {"Content-Description:",
1363                                                    NULL, TRUE},
1364                                 {"Content-ID:",
1365                                                    NULL, TRUE},
1366                                 {"Content-Disposition:",
1367                                                    NULL, TRUE},
1368                                 {"Content-Location:",
1369                                                    NULL, TRUE},
1370                                 {NULL,             NULL, FALSE}};
1371         gchar *p, *tmp;
1372         gchar *boundary;
1373         gint boundary_len = 0, lastoffset = -1, i;
1374         gchar buf[BUFFSIZE];
1375         FILE *fp;
1376         int result = 0;
1377
1378         boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
1379         if (!boundary)
1380                 return;
1381         boundary_len = strlen(boundary);
1382
1383         procmime_decode_content(mimeinfo);
1384
1385         fp = g_fopen(mimeinfo->data.filename, "rb");
1386         if (fp == NULL) {
1387                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1388                 return;
1389         }
1390         fseek(fp, mimeinfo->offset, SEEK_SET);
1391         while ((p = fgets(buf, sizeof(buf), fp)) != NULL && result == 0) {
1392                 if (ftell(fp) - 1 > (mimeinfo->offset + mimeinfo->length))
1393                         break;
1394
1395                 if (IS_BOUNDARY(buf, boundary, boundary_len)) {
1396                         if (lastoffset != -1) {
1397                                 result = procmime_parse_mimepart(mimeinfo,
1398                                                         hentry[0].body, hentry[1].body,
1399                                                         hentry[2].body, hentry[3].body, 
1400                                                         hentry[4].body, hentry[5].body,
1401                                                         mimeinfo->data.filename, lastoffset,
1402                                                         (ftell(fp) - strlen(buf)) - lastoffset - 1);
1403                         }
1404                         
1405                         if (buf[2 + boundary_len]     == '-' &&
1406                             buf[2 + boundary_len + 1] == '-')
1407                                 break;
1408
1409                         for (i = 0; i < (sizeof hentry / sizeof hentry[0]) ; i++) {
1410                                 g_free(hentry[i].body);
1411                                 hentry[i].body = NULL;
1412                         }
1413                         procheader_get_header_fields(fp, hentry);
1414                         if (hentry[0].body != NULL) {
1415                                 tmp = conv_unmime_header(hentry[0].body, NULL);
1416                                 g_free(hentry[0].body);
1417                                 hentry[0].body = tmp;
1418                         }                
1419                         if (hentry[2].body != NULL) {
1420                                 tmp = conv_unmime_header(hentry[2].body, NULL);
1421                                 g_free(hentry[2].body);
1422                                 hentry[2].body = tmp;
1423                         }                
1424                         if (hentry[4].body != NULL) {
1425                                 tmp = conv_unmime_header(hentry[4].body, NULL);
1426                                 g_free(hentry[4].body);
1427                                 hentry[4].body = tmp;
1428                         }                
1429                         if (hentry[5].body != NULL) {
1430                                 tmp = conv_unmime_header(hentry[5].body, NULL);
1431                                 g_free(hentry[5].body);
1432                                 hentry[5].body = tmp;
1433                         }                
1434                         lastoffset = ftell(fp);
1435                 }
1436         }
1437         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1438                 g_free(hentry[i].body);
1439                 hentry[i].body = NULL;
1440         }
1441         fclose(fp);
1442 }
1443
1444 static void parse_parameters(const gchar *parameters, GHashTable *table)
1445 {
1446         gchar *params, *param, *next;
1447         GSList *convlist = NULL, *concatlist = NULL, *cur;
1448
1449         params = g_strdup(parameters);
1450         param = params;
1451         next = params;
1452         for (; next != NULL; param = next) {
1453                 gchar *attribute, *value, *tmp;
1454                 gint len;
1455                 gboolean convert = FALSE;
1456
1457                 next = strchr_with_skip_quote(param, '"', ';');
1458                 if (next != NULL) {
1459                         next[0] = '\0';
1460                         next++;
1461                 }
1462
1463                 g_strstrip(param);
1464
1465                 attribute = param;
1466                 value = strchr(attribute, '=');
1467                 if (value == NULL)
1468                         continue;
1469
1470                 value[0] = '\0';
1471                 value++;
1472                 while (value[0] == ' ')
1473                         value++;
1474
1475                 g_strdown(attribute);
1476
1477                 len = strlen(attribute);
1478                 if (attribute[len - 1] == '*') {
1479                         gchar *srcpos, *dstpos, *endpos;
1480
1481                         convert = TRUE;
1482                         attribute[len - 1] = '\0';
1483
1484                         srcpos = value;
1485                         dstpos = value;
1486                         endpos = value + strlen(value);
1487                         while (srcpos < endpos) {
1488                                 if (*srcpos != '%')
1489                                         *dstpos = *srcpos;
1490                                 else {
1491                                         guchar dstvalue;
1492
1493                                         if (!get_hex_value(&dstvalue, srcpos[1], srcpos[2]))
1494                                                 *dstpos = '?';
1495                                         else
1496                                                 *dstpos = dstvalue;
1497                                         srcpos += 2;
1498                                 }
1499                                 srcpos++;
1500                                 dstpos++;
1501                         }
1502                         *dstpos = '\0';
1503                 } else {
1504                         if (value[0] == '"')
1505                                 extract_quote(value, '"');
1506                         else if ((tmp = strchr(value, ' ')) != NULL)
1507                                 *tmp = '\0';
1508                 }
1509
1510                 if (attribute) {
1511                         while (attribute[0] == ' ')
1512                                 attribute++;
1513                         while (attribute[strlen(attribute)-1] == ' ') 
1514                                 attribute[strlen(attribute)-1] = '\0';
1515                 } 
1516                 if (value) {
1517                         while (value[0] == ' ')
1518                                 value++;
1519                         while (value[strlen(value)-1] == ' ') 
1520                                 value[strlen(value)-1] = '\0';
1521                 }               
1522                 if (strrchr(attribute, '*') != NULL) {
1523                         gchar *tmpattr;
1524
1525                         tmpattr = g_strdup(attribute);
1526                         tmp = strrchr(tmpattr, '*');
1527                         tmp[0] = '\0';
1528
1529                         if ((tmp[1] == '0') && (tmp[2] == '\0') && 
1530                             (g_slist_find_custom(concatlist, attribute, g_str_equal) == NULL))
1531                                 concatlist = g_slist_prepend(concatlist, g_strdup(tmpattr));
1532
1533                         if (convert && (g_slist_find_custom(convlist, attribute, g_str_equal) == NULL))
1534                                 convlist = g_slist_prepend(convlist, g_strdup(tmpattr));
1535
1536                         g_free(tmpattr);
1537                 } else if (convert) {
1538                         if (g_slist_find_custom(convlist, attribute, g_str_equal) == NULL)
1539                                 convlist = g_slist_prepend(convlist, g_strdup(attribute));
1540                 }
1541
1542                 if (g_hash_table_lookup(table, attribute) == NULL)
1543                         g_hash_table_insert(table, g_strdup(attribute), g_strdup(value));
1544         }
1545
1546         for (cur = concatlist; cur != NULL; cur = g_slist_next(cur)) {
1547                 gchar *attribute, *attrwnum, *partvalue;
1548                 gint n = 0;
1549                 GString *value;
1550
1551                 attribute = (gchar *) cur->data;
1552                 value = g_string_sized_new(64);
1553
1554                 attrwnum = g_strdup_printf("%s*%d", attribute, n);
1555                 while ((partvalue = g_hash_table_lookup(table, attrwnum)) != NULL) {
1556                         g_string_append(value, partvalue);
1557
1558                         g_free(attrwnum);
1559                         n++;
1560                         attrwnum = g_strdup_printf("%s*%d", attribute, n);
1561                 }
1562                 g_free(attrwnum);
1563
1564                 g_hash_table_insert(table, g_strdup(attribute), g_strdup(value->str));
1565                 g_string_free(value, TRUE);
1566         }
1567         slist_free_strings(concatlist);
1568         g_slist_free(concatlist);
1569
1570         for (cur = convlist; cur != NULL; cur = g_slist_next(cur)) {
1571                 gchar *attribute, *key, *value;
1572                 gchar *charset, *lang, *oldvalue, *newvalue;
1573
1574                 attribute = (gchar *) cur->data;
1575                 if (!g_hash_table_lookup_extended(
1576                         table, attribute, (gpointer *)(gchar *) &key, (gpointer *)(gchar *) &value))
1577                         continue;
1578
1579                 charset = value;
1580                 lang = strchr(charset, '\'');
1581                 if (lang == NULL)
1582                         continue;
1583                 lang[0] = '\0';
1584                 lang++;
1585                 oldvalue = strchr(lang, '\'');
1586                 if (oldvalue == NULL)
1587                         continue;
1588                 oldvalue[0] = '\0';
1589                 oldvalue++;
1590
1591                 newvalue = conv_codeset_strdup(oldvalue, charset, CS_UTF_8);
1592
1593                 g_hash_table_remove(table, attribute);
1594                 g_free(key);
1595                 g_free(value);
1596
1597                 g_hash_table_insert(table, g_strdup(attribute), newvalue);
1598         }
1599         slist_free_strings(convlist);
1600         g_slist_free(convlist);
1601
1602         g_free(params);
1603 }       
1604
1605 static void procmime_parse_content_type(const gchar *content_type, MimeInfo *mimeinfo)
1606 {
1607         g_return_if_fail(content_type != NULL);
1608         g_return_if_fail(mimeinfo != NULL);
1609
1610         /* RFC 2045, page 13 says that the mime subtype is MANDATORY;
1611          * if it's not available we use the default Content-Type */
1612         if ((content_type[0] == '\0') || (strchr(content_type, '/') == NULL)) {
1613                 mimeinfo->type = MIMETYPE_TEXT;
1614                 mimeinfo->subtype = g_strdup("plain");
1615                 if (g_hash_table_lookup(mimeinfo->typeparameters,
1616                                        "charset") == NULL) {
1617                         g_hash_table_insert(mimeinfo->typeparameters,
1618                                     g_strdup("charset"),
1619                                     g_strdup(
1620                                         conv_get_locale_charset_str_no_utf8()));
1621                 }
1622         } else {
1623                 gchar *type, *subtype, *params;
1624
1625                 type = g_strdup(content_type);
1626                 subtype = strchr(type, '/') + 1;
1627                 *(subtype - 1) = '\0';
1628                 if ((params = strchr(subtype, ';')) != NULL) {
1629                         params[0] = '\0';
1630                         params++;
1631                 }
1632
1633                 mimeinfo->type = procmime_get_media_type(type);
1634                 mimeinfo->subtype = g_strdup(subtype);
1635
1636                 /* Get mimeinfo->typeparameters */
1637                 if (params != NULL)
1638                         parse_parameters(params, mimeinfo->typeparameters);
1639
1640                 g_free(type);
1641         }
1642 }
1643
1644 static void procmime_parse_content_disposition(const gchar *content_disposition, MimeInfo *mimeinfo)
1645 {
1646         gchar *tmp, *params;
1647
1648         g_return_if_fail(content_disposition != NULL);
1649         g_return_if_fail(mimeinfo != NULL);
1650
1651         tmp = g_strdup(content_disposition);
1652         if ((params = strchr(tmp, ';')) != NULL) {
1653                 params[0] = '\0';
1654                 params++;
1655         }       
1656         g_strstrip(tmp);
1657
1658         if (!g_ascii_strcasecmp(tmp, "inline")) 
1659                 mimeinfo->disposition = DISPOSITIONTYPE_INLINE;
1660         else if (!g_ascii_strcasecmp(tmp, "attachment"))
1661                 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1662         else
1663                 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1664         
1665         if (params != NULL)
1666                 parse_parameters(params, mimeinfo->dispositionparameters);
1667
1668         g_free(tmp);
1669 }
1670
1671
1672 static void procmime_parse_content_encoding(const gchar *content_encoding, MimeInfo *mimeinfo)
1673 {
1674         struct EncodingTable *enc_table;
1675         
1676         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1677                 if (g_ascii_strcasecmp(enc_table->str, content_encoding) == 0) {
1678                         mimeinfo->encoding_type = enc_table->enc_type;
1679                         return;
1680                 }
1681         }
1682         mimeinfo->encoding_type = ENC_UNKNOWN;
1683         return;
1684 }
1685
1686 static int procmime_parse_mimepart(MimeInfo *parent,
1687                              gchar *content_type,
1688                              gchar *content_encoding,
1689                              gchar *content_description,
1690                              gchar *content_id,
1691                              gchar *content_disposition,
1692                              gchar *content_location,
1693                              const gchar *filename,
1694                              guint offset,
1695                              guint length)
1696 {
1697         MimeInfo *mimeinfo;
1698
1699         /* Create MimeInfo */
1700         mimeinfo = procmime_mimeinfo_new();
1701         mimeinfo->content = MIMECONTENT_FILE;
1702         if (parent != NULL) {
1703                 if (g_node_depth(parent->node) > 32) {
1704                         /* 32 is an arbitrary value
1705                          * this avoids DOSsing ourselves 
1706                          * with enormous messages
1707                          */
1708                         procmime_mimeinfo_free_all(mimeinfo);
1709                         return -1;                      
1710                 }
1711                 g_node_append(parent->node, mimeinfo->node);
1712         }
1713         mimeinfo->data.filename = g_strdup(filename);
1714         mimeinfo->offset = offset;
1715         mimeinfo->length = length;
1716
1717         if (content_type != NULL) {
1718                 procmime_parse_content_type(content_type, mimeinfo);
1719         } else {
1720                 mimeinfo->type = MIMETYPE_TEXT;
1721                 mimeinfo->subtype = g_strdup("plain");
1722                 if (g_hash_table_lookup(mimeinfo->typeparameters,
1723                                        "charset") == NULL) {
1724                         g_hash_table_insert(mimeinfo->typeparameters,
1725                                     g_strdup("charset"),
1726                                     g_strdup(
1727                                         conv_get_locale_charset_str_no_utf8()));
1728                 }
1729         }
1730
1731         if (content_encoding != NULL) {
1732                 procmime_parse_content_encoding(content_encoding, mimeinfo);
1733         } else {
1734                 mimeinfo->encoding_type = ENC_UNKNOWN;
1735         }
1736
1737         if (content_description != NULL)
1738                 mimeinfo->description = g_strdup(content_description);
1739         else
1740                 mimeinfo->description = NULL;
1741
1742         if (content_id != NULL)
1743                 mimeinfo->id = g_strdup(content_id);
1744         else
1745                 mimeinfo->id = NULL;
1746
1747         if (content_location != NULL)
1748                 mimeinfo->location = g_strdup(content_location);
1749         else
1750                 mimeinfo->location = NULL;
1751
1752         if (content_disposition != NULL) 
1753                 procmime_parse_content_disposition(content_disposition, mimeinfo);
1754         else
1755                 mimeinfo->disposition = DISPOSITIONTYPE_UNKNOWN;
1756
1757         /* Call parser for mime type */
1758         switch (mimeinfo->type) {
1759                 case MIMETYPE_MESSAGE:
1760                         if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
1761                                 procmime_parse_message_rfc822(mimeinfo);
1762                         }
1763                         break;
1764                         
1765                 case MIMETYPE_MULTIPART:
1766                         procmime_parse_multipart(mimeinfo);
1767                         break;
1768                         
1769                 default:
1770                         break;
1771         }
1772
1773         return 0;
1774 }
1775
1776 static gchar *typenames[] = {
1777     "text",
1778     "image",
1779     "audio",
1780     "video",
1781     "application",
1782     "message",
1783     "multipart",
1784     "unknown",
1785 };
1786
1787 static gboolean output_func(GNode *node, gpointer data)
1788 {
1789         guint i, depth;
1790         MimeInfo *mimeinfo = (MimeInfo *) node->data;
1791
1792         depth = g_node_depth(node);
1793         for (i = 0; i < depth; i++)
1794                 printf("    ");
1795         printf("%s/%s (offset:%d length:%d encoding: %d)\n", typenames[mimeinfo->type], mimeinfo->subtype, mimeinfo->offset, mimeinfo->length, mimeinfo->encoding_type);
1796
1797         return FALSE;
1798 }
1799
1800 static void output_mime_structure(MimeInfo *mimeinfo, int indent)
1801 {
1802         g_node_traverse(mimeinfo->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1, output_func, NULL);
1803 }
1804
1805 MimeInfo *procmime_scan_file_with_offset(const gchar *filename, int offset)
1806 {
1807         MimeInfo *mimeinfo;
1808         struct stat buf;
1809
1810         stat(filename, &buf);
1811
1812         mimeinfo = procmime_mimeinfo_new();
1813         mimeinfo->content = MIMECONTENT_FILE;
1814         mimeinfo->encoding_type = ENC_UNKNOWN;
1815         mimeinfo->type = MIMETYPE_MESSAGE;
1816         mimeinfo->subtype = g_strdup("rfc822");
1817         mimeinfo->data.filename = g_strdup(filename);
1818         mimeinfo->offset = offset;
1819         mimeinfo->length = buf.st_size - offset;
1820
1821         procmime_parse_message_rfc822(mimeinfo);
1822         if (debug_get_mode())
1823                 output_mime_structure(mimeinfo, 0);
1824
1825         return mimeinfo;
1826 }
1827
1828 MimeInfo *procmime_scan_file(const gchar *filename)
1829 {
1830         MimeInfo *mimeinfo;
1831
1832         g_return_val_if_fail(filename != NULL, NULL);
1833
1834         mimeinfo = procmime_scan_file_with_offset(filename, 0);
1835
1836         return mimeinfo;
1837 }
1838
1839 MimeInfo *procmime_scan_queue_file(const gchar *filename)
1840 {
1841         FILE *fp;
1842         MimeInfo *mimeinfo;
1843         gchar buf[BUFFSIZE];
1844         gint offset = 0;
1845
1846         g_return_val_if_fail(filename != NULL, NULL);
1847
1848         /* Open file */
1849         if ((fp = g_fopen(filename, "rb")) == NULL)
1850                 return NULL;
1851         /* Skip queue header */
1852         while (fgets(buf, sizeof(buf), fp) != NULL) {
1853                 /* new way */
1854                 if (!strncmp(buf, "X-Sylpheed-End-Special-Headers: 1",
1855                         strlen("X-Sylpheed-End-Special-Headers:")))
1856                         break;
1857                 /* old way */
1858                 if (buf[0] == '\r' || buf[0] == '\n') break;
1859                 /* from other mailers */
1860                 if (!strncmp(buf, "Date: ", 6)
1861                 ||  !strncmp(buf, "To: ", 4)
1862                 ||  !strncmp(buf, "From: ", 6)
1863                 ||  !strncmp(buf, "Subject: ", 9)) {
1864                         rewind(fp);
1865                         break;
1866                 }
1867         }
1868         offset = ftell(fp);
1869         fclose(fp);
1870
1871         mimeinfo = procmime_scan_file_with_offset(filename, offset);
1872
1873         return mimeinfo;
1874 }
1875
1876 typedef enum {
1877     ENC_AS_TOKEN,
1878     ENC_AS_QUOTED_STRING,
1879     ENC_AS_EXTENDED,
1880     ENC_TO_ASCII,
1881 } EncodeAs;
1882
1883 typedef struct _ParametersData {
1884         FILE *fp;
1885         guint len;
1886         guint ascii_only;
1887 } ParametersData;
1888
1889 static void write_parameters(gpointer key, gpointer value, gpointer user_data)
1890 {
1891         gchar *param = key;
1892         gchar *val = value, *valpos, *tmp;
1893         ParametersData *pdata = (ParametersData *)user_data;
1894         GString *buf = g_string_new("");
1895
1896         EncodeAs encas = ENC_AS_TOKEN;
1897
1898         for (valpos = val; *valpos != 0; valpos++) {
1899                 if (!IS_ASCII(*valpos) || *valpos == '"') {
1900                         encas = ENC_AS_EXTENDED;
1901                         break;
1902                 }
1903             
1904                 /* CTLs */
1905                 if (((*valpos >= 0) && (*valpos < 037)) || (*valpos == 0177)) {
1906                         encas = ENC_AS_QUOTED_STRING;
1907                         continue;
1908                 }
1909
1910                 /* tspecials + SPACE */
1911                 switch (*valpos) {
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                 case '?':
1927                 case '=':
1928                         encas = ENC_AS_QUOTED_STRING;
1929                         continue;
1930                 }
1931         }
1932         
1933         if (encas == ENC_AS_EXTENDED && pdata->ascii_only == TRUE) 
1934                 encas = ENC_TO_ASCII;
1935
1936         switch (encas) {
1937         case ENC_AS_TOKEN:
1938                 g_string_append_printf(buf, "%s=%s", param, val);
1939                 break;
1940
1941         case ENC_TO_ASCII:
1942                 tmp = g_strdup(val);
1943                 g_strcanon(tmp, 
1944                         " ()<>@,';:\\/[]?=.0123456789"
1945                         "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1946                         "abcdefghijklmnopqrstuvwxyz",
1947                         '_');
1948                 g_string_append_printf(buf, "%s=\"%s\"", param, tmp);
1949                 g_free(tmp);
1950                 break;
1951
1952         case ENC_AS_QUOTED_STRING:
1953                 g_string_append_printf(buf, "%s=\"%s\"", param, val);
1954                 break;
1955
1956         case ENC_AS_EXTENDED:
1957                 if (!g_utf8_validate(val, -1, NULL))
1958                         g_string_append_printf(buf, "%s*=%s''", param,
1959                                 conv_get_locale_charset_str());
1960                 else
1961                         g_string_append_printf(buf, "%s*=%s''", param,
1962                                 CS_INTERNAL);
1963                 for (valpos = val; *valpos != '\0'; valpos++) {
1964                         if (IS_ASCII(*valpos) && isalnum(*valpos)) {
1965                                 g_string_append_printf(buf, "%c", *valpos);
1966                         } else {
1967                                 gchar hexstr[3] = "XX";
1968                                 get_hex_str(hexstr, *valpos);
1969                                 g_string_append_printf(buf, "%%%s", hexstr);
1970                         }
1971                 }
1972                 break;          
1973         }
1974         
1975         if (buf->str && strlen(buf->str)) {
1976                 if (pdata->len + strlen(buf->str) + 2 > 76) {
1977                         fprintf(pdata->fp, ";\n %s", buf->str);
1978                         pdata->len = strlen(buf->str) + 1;
1979                 } else {
1980                         fprintf(pdata->fp, "; %s", buf->str);
1981                         pdata->len += strlen(buf->str) + 2;
1982                 }
1983         }
1984         g_string_free(buf, TRUE);
1985 }
1986
1987 void procmime_write_mime_header(MimeInfo *mimeinfo, FILE *fp)
1988 {
1989         struct TypeTable *type_table;
1990         ParametersData *pdata = g_new0(ParametersData, 1);
1991         debug_print("procmime_write_mime_header\n");
1992         
1993         pdata->fp = fp;
1994         pdata->ascii_only = FALSE;
1995
1996         for (type_table = mime_type_table; type_table->str != NULL; type_table++)
1997                 if (mimeinfo->type == type_table->type) {
1998                         gchar *buf = g_strdup_printf(
1999                                 "Content-Type: %s/%s", type_table->str, mimeinfo->subtype);
2000                         fprintf(fp, "%s", buf);
2001                         pdata->len = strlen(buf);
2002                         pdata->ascii_only = TRUE;
2003                         g_free(buf);
2004                         break;
2005                 }
2006         g_hash_table_foreach(mimeinfo->typeparameters, write_parameters, pdata);
2007         g_free(pdata);
2008
2009         fprintf(fp, "\n");
2010
2011         if (mimeinfo->encoding_type != ENC_UNKNOWN)
2012                 fprintf(fp, "Content-Transfer-Encoding: %s\n", procmime_get_encoding_str(mimeinfo->encoding_type));
2013
2014         if (mimeinfo->description != NULL)
2015                 fprintf(fp, "Content-Description: %s\n", mimeinfo->description);
2016
2017         if (mimeinfo->id != NULL)
2018                 fprintf(fp, "Content-ID: %s\n", mimeinfo->id);
2019
2020         if (mimeinfo->location != NULL)
2021                 fprintf(fp, "Content-Location: %s\n", mimeinfo->location);
2022
2023         if (mimeinfo->disposition != DISPOSITIONTYPE_UNKNOWN) {
2024                 ParametersData *pdata = g_new0(ParametersData, 1);
2025                 gchar *buf = NULL;
2026                 if (mimeinfo->disposition == DISPOSITIONTYPE_INLINE)
2027                         buf = g_strdup("Content-Disposition: inline");
2028                 else if (mimeinfo->disposition == DISPOSITIONTYPE_ATTACHMENT)
2029                         buf = g_strdup("Content-Disposition: attachment");
2030                 else
2031                         buf = g_strdup("Content-Disposition: unknown");
2032
2033                 fprintf(fp, "%s", buf);
2034                 pdata->len = strlen(buf);
2035                 g_free(buf);
2036
2037                 pdata->fp = fp;
2038                 pdata->ascii_only = FALSE;
2039
2040                 g_hash_table_foreach(mimeinfo->dispositionparameters, write_parameters, pdata);
2041                 g_free(pdata);
2042                 fprintf(fp, "\n");
2043         }
2044
2045         fprintf(fp, "\n");
2046 }
2047
2048 gint procmime_write_message_rfc822(MimeInfo *mimeinfo, FILE *fp)
2049 {
2050         FILE *infp;
2051         GNode *childnode;
2052         MimeInfo *child;
2053         gchar buf[BUFFSIZE];
2054         gboolean skip = FALSE;;
2055
2056         debug_print("procmime_write_message_rfc822\n");
2057
2058         /* write header */
2059         switch (mimeinfo->content) {
2060         case MIMECONTENT_FILE:
2061                 if ((infp = g_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2062                         FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2063                         return -1;
2064                 }
2065                 fseek(infp, mimeinfo->offset, SEEK_SET);
2066                 while (fgets(buf, sizeof(buf), infp) == buf) {
2067                         if (buf[0] == '\n' && buf[1] == '\0')
2068                                 break;
2069                         if (skip && (buf[0] == ' ' || buf[0] == '\t'))
2070                                 continue;
2071                         if (g_ascii_strncasecmp(buf, "Mime-Version:", 13) == 0 ||
2072                             g_ascii_strncasecmp(buf, "Content-Type:", 13) == 0 ||
2073                             g_ascii_strncasecmp(buf, "Content-Transfer-Encoding:", 26) == 0 ||
2074                             g_ascii_strncasecmp(buf, "Content-Description:", 20) == 0 ||
2075                             g_ascii_strncasecmp(buf, "Content-ID:", 11) == 0 ||
2076                             g_ascii_strncasecmp(buf, "Content-Location:", 17) == 0 ||
2077                             g_ascii_strncasecmp(buf, "Content-Disposition:", 20) == 0) {
2078                                 skip = TRUE;
2079                                 continue;
2080                         }
2081                         fwrite(buf, sizeof(gchar), strlen(buf), fp);
2082                         skip = FALSE;
2083                 }
2084                 fclose(infp);
2085                 break;
2086
2087         case MIMECONTENT_MEM:
2088                 fwrite(mimeinfo->data.mem, 
2089                                 sizeof(gchar), 
2090                                 strlen(mimeinfo->data.mem), 
2091                                 fp);
2092                 break;
2093
2094         default:
2095                 break;
2096         }
2097
2098         childnode = mimeinfo->node->children;
2099         if (childnode == NULL)
2100                 return -1;
2101
2102         child = (MimeInfo *) childnode->data;
2103         fprintf(fp, "Mime-Version: 1.0\n");
2104         procmime_write_mime_header(child, fp);
2105         return procmime_write_mimeinfo(child, fp);
2106 }
2107
2108 gint procmime_write_multipart(MimeInfo *mimeinfo, FILE *fp)
2109 {
2110         FILE *infp;
2111         GNode *childnode;
2112         gchar *boundary, *str, *str2;
2113         gchar buf[BUFFSIZE];
2114         gboolean firstboundary;
2115
2116         debug_print("procmime_write_multipart\n");
2117
2118         boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
2119
2120         switch (mimeinfo->content) {
2121         case MIMECONTENT_FILE:
2122                 if ((infp = g_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2123                         FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2124                         return -1;
2125                 }
2126                 fseek(infp, mimeinfo->offset, SEEK_SET);
2127                 while (fgets(buf, sizeof(buf), infp) == buf) {
2128                         if (IS_BOUNDARY(buf, boundary, strlen(boundary)))
2129                                 break;
2130                         fwrite(buf, sizeof(gchar), strlen(buf), fp);
2131                 }
2132                 fclose(infp);
2133                 break;
2134
2135         case MIMECONTENT_MEM:
2136                 str = g_strdup(mimeinfo->data.mem);
2137                 if (((str2 = strstr(str, boundary)) != NULL) && ((str2 - str) >= 2) &&
2138                     (*(str2 - 1) == '-') && (*(str2 - 2) == '-'))
2139                         *(str2 - 2) = '\0';
2140                 fwrite(str, sizeof(gchar), strlen(str), fp);
2141                 g_free(str);
2142                 break;
2143
2144         default:
2145                 break;
2146         }
2147
2148         childnode = mimeinfo->node->children;
2149         firstboundary = TRUE;
2150         while (childnode != NULL) {
2151                 MimeInfo *child = childnode->data;
2152
2153                 if (firstboundary)
2154                         firstboundary = FALSE;
2155                 else
2156                         fprintf(fp, "\n");
2157                 fprintf(fp, "--%s\n", boundary);
2158
2159                 procmime_write_mime_header(child, fp);
2160                 if (procmime_write_mimeinfo(child, fp) < 0)
2161                         return -1;
2162
2163                 childnode = g_node_next_sibling(childnode);
2164         }       
2165         fprintf(fp, "\n--%s--\n", boundary);
2166
2167         return 0;
2168 }
2169
2170 gint procmime_write_mimeinfo(MimeInfo *mimeinfo, FILE *fp)
2171 {
2172         FILE *infp;
2173
2174         debug_print("procmime_write_mimeinfo\n");
2175
2176         if (G_NODE_IS_LEAF(mimeinfo->node)) {
2177                 switch (mimeinfo->content) {
2178                 case MIMECONTENT_FILE:
2179                         if ((infp = g_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2180                                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2181                                 return -1;
2182                         }
2183                         copy_file_part_to_fp(infp, mimeinfo->offset, mimeinfo->length, fp);
2184                         fclose(infp);
2185                         return 0;
2186
2187                 case MIMECONTENT_MEM:
2188                         fwrite(mimeinfo->data.mem, 
2189                                         sizeof(gchar), 
2190                                         strlen(mimeinfo->data.mem), 
2191                                         fp);
2192                         return 0;
2193
2194                 default:
2195                         return 0;
2196                 }
2197         } else {
2198                 /* Call writer for mime type */
2199                 switch (mimeinfo->type) {
2200                 case MIMETYPE_MESSAGE:
2201                         if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
2202                                 return procmime_write_message_rfc822(mimeinfo, fp);
2203                         }
2204                         break;
2205                         
2206                 case MIMETYPE_MULTIPART:
2207                         return procmime_write_multipart(mimeinfo, fp);
2208                         
2209                 default:
2210                         break;
2211                 }
2212
2213                 return -1;
2214         }
2215
2216         return 0;
2217 }
2218
2219 gchar *procmime_get_part_file_name(MimeInfo *mimeinfo)
2220 {
2221         gchar *base;
2222
2223         if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
2224                 base = g_strdup("mimetmp.html");
2225         else {
2226                 const gchar *basetmp;
2227                 gchar *basename;
2228
2229                 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
2230                 if (basetmp == NULL)
2231                         basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
2232                 if (basetmp == NULL)
2233                         basetmp = "mimetmp";
2234                 basename = g_path_get_basename(basetmp);
2235                 if (*basename == '\0') {
2236                         g_free(basename);
2237                         basename = g_strdup("mimetmp");
2238                 }
2239                 base = conv_filename_from_utf8(basename);
2240                 g_free(basename);
2241                 subst_for_shellsafe_filename(base);
2242         }
2243         
2244         return base;
2245 }
2246