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