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