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