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