2008-08-21 [colin] 3.5.0cvs65
[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                         claws_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                 claws_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                                         claws_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                         claws_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                         claws_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                 claws_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         claws_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         gboolean empty_ok = FALSE, short_scan = TRUE;
756         START_TIMING("");
757         g_return_val_if_fail(msginfo != NULL, NULL);
758
759         /* first we try to short-scan (for speed), refusing empty parts */
760 scan_again:
761         if (short_scan)
762                 mimeinfo = procmime_scan_message_short(msginfo);
763         else
764                 mimeinfo = procmime_scan_message(msginfo);
765         if (!mimeinfo) return NULL;
766
767         partinfo = mimeinfo;
768         while (partinfo && (partinfo->type != MIMETYPE_TEXT ||
769                (partinfo->length == 0 && !empty_ok))) {
770                 partinfo = procmime_mimeinfo_next(partinfo);
771         }
772         if (partinfo)
773                 outfp = procmime_get_text_content(partinfo);
774         else if (!empty_ok && short_scan) {
775                 /* if short scan didn't find a non-empty part, rescan
776                  * fully for non-empty parts
777                  */
778                 short_scan = FALSE;
779                 procmime_mimeinfo_free_all(mimeinfo);
780                 goto scan_again;
781         } else if (!empty_ok && !short_scan) {
782                 /* if full scan didn't find a non-empty part, rescan
783                  * accepting empty parts 
784                  */
785                 empty_ok = TRUE;
786                 procmime_mimeinfo_free_all(mimeinfo);
787                 goto scan_again;
788         }
789         procmime_mimeinfo_free_all(mimeinfo);
790         END_TIMING();
791         return outfp;
792 }
793
794
795 static gboolean find_encrypted_func(GNode *node, gpointer data)
796 {
797         MimeInfo *mimeinfo = (MimeInfo *) node->data;
798         MimeInfo **encinfo = (MimeInfo **) data;
799         
800         if (privacy_mimeinfo_is_encrypted(mimeinfo)) {
801                 *encinfo = mimeinfo;
802                 return TRUE;
803         }
804         
805         return FALSE;
806 }
807
808 static MimeInfo *find_encrypted_part(MimeInfo *rootinfo)
809 {
810         MimeInfo *encinfo = NULL;
811
812         g_node_traverse(rootinfo->node, G_IN_ORDER, G_TRAVERSE_ALL, -1,
813                 find_encrypted_func, &encinfo);
814         
815         return encinfo;
816 }
817
818 /* search the first encrypted text part of (multipart) MIME message,
819    decode, convert it and output to outfp. */
820 FILE *procmime_get_first_encrypted_text_content(MsgInfo *msginfo)
821 {
822         FILE *outfp = NULL;
823         MimeInfo *mimeinfo, *partinfo, *encinfo;
824
825         g_return_val_if_fail(msginfo != NULL, NULL);
826
827         mimeinfo = procmime_scan_message(msginfo);
828         if (!mimeinfo) {
829                 return NULL;
830         }
831
832         partinfo = mimeinfo;
833         if ((encinfo = find_encrypted_part(partinfo)) != NULL) {
834                 debug_print("decrypting message part\n");
835                 if (privacy_mimeinfo_decrypt(encinfo) < 0) {
836                         alertpanel_error(_("Couldn't decrypt: %s"),
837                                 privacy_get_error());
838                         return NULL;
839                 }
840         }
841         partinfo = mimeinfo;
842         while (partinfo && partinfo->type != MIMETYPE_TEXT) {
843                 partinfo = procmime_mimeinfo_next(partinfo);
844         }
845
846         if (partinfo)
847                 outfp = procmime_get_text_content(partinfo);
848
849         procmime_mimeinfo_free_all(mimeinfo);
850
851         return outfp;
852 }
853
854 gboolean procmime_msginfo_is_encrypted(MsgInfo *msginfo)
855 {
856         MimeInfo *mimeinfo, *partinfo;
857         gboolean result = FALSE;
858
859         g_return_val_if_fail(msginfo != NULL, FALSE);
860
861         mimeinfo = procmime_scan_message(msginfo);
862         if (!mimeinfo) {
863                 return FALSE;
864         }
865
866         partinfo = mimeinfo;
867         result = (find_encrypted_part(partinfo) != NULL);
868         procmime_mimeinfo_free_all(mimeinfo);
869
870         return result;
871 }
872
873 static gboolean procmime_find_string_part(MimeInfo *mimeinfo, const gchar *filename,
874                                    const gchar *str, StrFindFunc find_func)
875 {
876         FILE *outfp;
877         gchar buf[BUFFSIZE];
878
879         g_return_val_if_fail(mimeinfo != NULL, FALSE);
880         g_return_val_if_fail(mimeinfo->type == MIMETYPE_TEXT, FALSE);
881         g_return_val_if_fail(str != NULL, FALSE);
882         g_return_val_if_fail(find_func != NULL, FALSE);
883
884         outfp = procmime_get_text_content(mimeinfo);
885
886         if (!outfp)
887                 return FALSE;
888
889         while (fgets(buf, sizeof(buf), outfp) != NULL) {
890                 strretchomp(buf);
891                 if (find_func(buf, str)) {
892                         fclose(outfp);
893                         return TRUE;
894                 }
895         }
896
897         fclose(outfp);
898
899         return FALSE;
900 }
901
902 gboolean procmime_find_string(MsgInfo *msginfo, const gchar *str,
903                               StrFindFunc find_func)
904 {
905         MimeInfo *mimeinfo;
906         MimeInfo *partinfo;
907         gchar *filename;
908         gboolean found = FALSE;
909
910         g_return_val_if_fail(msginfo != NULL, FALSE);
911         g_return_val_if_fail(str != NULL, FALSE);
912         g_return_val_if_fail(find_func != NULL, FALSE);
913
914         filename = procmsg_get_message_file(msginfo);
915         if (!filename) return FALSE;
916         mimeinfo = procmime_scan_message(msginfo);
917
918         for (partinfo = mimeinfo; partinfo != NULL;
919              partinfo = procmime_mimeinfo_next(partinfo)) {
920                 if (partinfo->type == MIMETYPE_TEXT) {
921                         if (procmime_find_string_part
922                                 (partinfo, filename, str, find_func) == TRUE) {
923                                 found = TRUE;
924                                 break;
925                         }
926                 }
927         }
928
929         procmime_mimeinfo_free_all(mimeinfo);
930         g_free(filename);
931
932         return found;
933 }
934
935 gchar *procmime_get_tmp_file_name(MimeInfo *mimeinfo)
936 {
937         static guint32 id = 0;
938         gchar *base;
939         gchar *filename;
940         gchar f_prefix[10];
941
942         g_return_val_if_fail(mimeinfo != NULL, NULL);
943
944         g_snprintf(f_prefix, sizeof(f_prefix), "%08x.", id++);
945
946         if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
947                 base = g_strdup("mimetmp.html");
948         else {
949                 const gchar *basetmp;
950
951                 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
952                 if (basetmp == NULL)
953                         basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
954                 if (basetmp == NULL)
955                         basetmp = "mimetmp";
956                 basetmp = g_path_get_basename(basetmp);
957                 if (*basetmp == '\0') 
958                         basetmp = g_strdup("mimetmp");
959                 base = conv_filename_from_utf8(basetmp);
960                 g_free((gchar*)basetmp);
961                 subst_for_shellsafe_filename(base);
962         }
963
964         filename = g_strconcat(get_mime_tmp_dir(), G_DIR_SEPARATOR_S,
965                                f_prefix, base, NULL);
966
967         g_free(base);
968         
969         return filename;
970 }
971
972 static GList *mime_type_list = NULL;
973
974 gchar *procmime_get_mime_type(const gchar *filename)
975 {
976         static GHashTable *mime_type_table = NULL;
977         MimeType *mime_type;
978         const gchar *p;
979         gchar *ext = NULL;
980         gchar *base;
981
982         if (!mime_type_table) {
983                 mime_type_table = procmime_get_mime_type_table();
984                 if (!mime_type_table) return NULL;
985         }
986
987         base = g_path_get_basename(filename);
988         if ((p = strrchr(base, '.')) != NULL)
989                 ext = g_utf8_strdown(p + 1, -1);
990         g_free(base);
991
992         mime_type = g_hash_table_lookup(mime_type_table, ext);
993         g_free(ext);
994         if (mime_type) {
995                 gchar *str;
996
997                 str = g_strconcat(mime_type->type, "/", mime_type->sub_type,
998                                   NULL);
999                 return str;
1000         }
1001
1002         return NULL;
1003 }
1004
1005 static guint procmime_str_hash(gconstpointer gptr)
1006 {
1007         guint hash_result = 0;
1008         const char *str;
1009
1010         for (str = gptr; str && *str; str++) {
1011                 if (isupper(*str)) hash_result += (*str + ' ');
1012                 else hash_result += *str;
1013         }
1014
1015         return hash_result;
1016 }
1017
1018 static gint procmime_str_equal(gconstpointer gptr1, gconstpointer gptr2)
1019 {
1020         const char *str1 = gptr1;
1021         const char *str2 = gptr2;
1022
1023         return !g_utf8_collate(str1, str2);
1024 }
1025
1026 static GHashTable *procmime_get_mime_type_table(void)
1027 {
1028         GHashTable *table = NULL;
1029         GList *cur;
1030         MimeType *mime_type;
1031         gchar **exts;
1032
1033         if (!mime_type_list) {
1034                 mime_type_list = procmime_get_mime_type_list();
1035                 if (!mime_type_list) return NULL;
1036         }
1037
1038         table = g_hash_table_new(procmime_str_hash, procmime_str_equal);
1039
1040         for (cur = mime_type_list; cur != NULL; cur = cur->next) {
1041                 gint i;
1042                 gchar *key;
1043
1044                 mime_type = (MimeType *)cur->data;
1045
1046                 if (!mime_type->extension) continue;
1047
1048                 exts = g_strsplit(mime_type->extension, " ", 16);
1049                 for (i = 0; exts[i] != NULL; i++) {
1050                         /* use previously dup'd key on overwriting */
1051                         if (g_hash_table_lookup(table, exts[i]))
1052                                 key = exts[i];
1053                         else
1054                                 key = g_strdup(exts[i]);
1055                         g_hash_table_insert(table, key, mime_type);
1056                 }
1057                 g_strfreev(exts);
1058         }
1059
1060         return table;
1061 }
1062
1063 GList *procmime_get_mime_type_list(void)
1064 {
1065         GList *list = NULL;
1066         FILE *fp;
1067         gchar buf[BUFFSIZE];
1068         gchar *p;
1069         gchar *delim;
1070         MimeType *mime_type;
1071         gboolean fp_is_glob_file = TRUE;
1072
1073         if (mime_type_list) 
1074                 return mime_type_list;
1075         
1076 #if defined(__NetBSD__) || defined(__OpenBSD__) || defined(__FreeBSD__)
1077         if ((fp = g_fopen(DATAROOTDIR "/mime/globs", "rb")) == NULL) 
1078 #else
1079         if ((fp = g_fopen("/usr/share/mime/globs", "rb")) == NULL) 
1080 #endif
1081         {
1082                 fp_is_glob_file = FALSE;
1083                 if ((fp = g_fopen("/etc/mime.types", "rb")) == NULL) {
1084                         if ((fp = g_fopen(SYSCONFDIR "/mime.types", "rb")) 
1085                                 == NULL) {
1086                                 FILE_OP_ERROR(SYSCONFDIR "/mime.types", 
1087                                         "fopen");
1088                                 return NULL;
1089                         }
1090                 }
1091         }
1092
1093         while (fgets(buf, sizeof(buf), fp) != NULL) {
1094                 p = strchr(buf, '#');
1095                 if (p) *p = '\0';
1096                 g_strstrip(buf);
1097
1098                 p = buf;
1099                 
1100                 if (fp_is_glob_file) {
1101                         while (*p && !g_ascii_isspace(*p) && (*p!=':')) p++;
1102                 } else {
1103                         while (*p && !g_ascii_isspace(*p)) p++;
1104                 }
1105
1106                 if (*p) {
1107                         *p = '\0';
1108                         p++;
1109                 }
1110                 delim = strchr(buf, '/');
1111                 if (delim == NULL) continue;
1112                 *delim = '\0';
1113
1114                 mime_type = g_new(MimeType, 1);
1115                 mime_type->type = g_strdup(buf);
1116                 mime_type->sub_type = g_strdup(delim + 1);
1117
1118                 if (fp_is_glob_file) {
1119                         while (*p && (g_ascii_isspace(*p)||(*p=='*')||(*p=='.'))) p++;
1120                 } else {
1121                         while (*p && g_ascii_isspace(*p)) p++;
1122                 }
1123
1124                 if (*p)
1125                         mime_type->extension = g_utf8_strdown(p, -1);
1126                 else
1127                         mime_type->extension = NULL;
1128
1129                 list = g_list_append(list, mime_type);
1130         }
1131
1132         fclose(fp);
1133
1134         if (!list)
1135                 g_warning("Can't read mime.types\n");
1136
1137         return list;
1138 }
1139
1140 EncodingType procmime_get_encoding_for_charset(const gchar *charset)
1141 {
1142         if (!charset)
1143                 return ENC_8BIT;
1144         else if (!g_ascii_strncasecmp(charset, "ISO-2022-", 9) ||
1145                  !g_ascii_strcasecmp(charset, "US-ASCII"))
1146                 return ENC_7BIT;
1147         else if (!g_ascii_strcasecmp(charset, "ISO-8859-5") ||
1148                  !g_ascii_strncasecmp(charset, "KOI8-", 5) ||
1149                  !g_ascii_strcasecmp(charset, "Windows-1251"))
1150                 return ENC_8BIT;
1151         else if (!g_ascii_strncasecmp(charset, "ISO-8859-", 9))
1152                 return ENC_QUOTED_PRINTABLE;
1153         else if (!g_ascii_strncasecmp(charset, "UTF-8", 5))
1154                 return ENC_QUOTED_PRINTABLE;
1155         else 
1156                 return ENC_8BIT;
1157 }
1158
1159 EncodingType procmime_get_encoding_for_text_file(const gchar *file, gboolean *has_binary)
1160 {
1161         FILE *fp;
1162         guchar buf[BUFFSIZE];
1163         size_t len;
1164         size_t octet_chars = 0;
1165         size_t total_len = 0;
1166         gfloat octet_percentage;
1167         gboolean force_b64 = FALSE;
1168
1169         if ((fp = g_fopen(file, "rb")) == NULL) {
1170                 FILE_OP_ERROR(file, "fopen");
1171                 return ENC_UNKNOWN;
1172         }
1173
1174         while ((len = fread(buf, sizeof(guchar), sizeof(buf), fp)) > 0) {
1175                 guchar *p;
1176                 gint i;
1177
1178                 for (p = buf, i = 0; i < len; ++p, ++i) {
1179                         if (*p & 0x80)
1180                                 ++octet_chars;
1181                         if (*p == '\0') {
1182                                 force_b64 = TRUE;
1183                                 *has_binary = TRUE;
1184                         }
1185                 }
1186                 total_len += len;
1187         }
1188
1189         fclose(fp);
1190         
1191         if (total_len > 0)
1192                 octet_percentage = (gfloat)octet_chars / (gfloat)total_len;
1193         else
1194                 octet_percentage = 0.0;
1195
1196         debug_print("procmime_get_encoding_for_text_file(): "
1197                     "8bit chars: %zd / %zd (%f%%)\n", octet_chars, total_len,
1198                     100.0 * octet_percentage);
1199
1200         if (octet_percentage > 0.20 || force_b64) {
1201                 debug_print("using BASE64\n");
1202                 return ENC_BASE64;
1203         } else if (octet_chars > 0) {
1204                 debug_print("using quoted-printable\n");
1205                 return ENC_QUOTED_PRINTABLE;
1206         } else {
1207                 debug_print("using 7bit\n");
1208                 return ENC_7BIT;
1209         }
1210 }
1211
1212 struct EncodingTable 
1213 {
1214         gchar *str;
1215         EncodingType enc_type;
1216 };
1217
1218 struct EncodingTable encoding_table[] = {
1219         {"7bit", ENC_7BIT},
1220         {"8bit", ENC_8BIT},
1221         {"binary", ENC_BINARY},
1222         {"quoted-printable", ENC_QUOTED_PRINTABLE},
1223         {"base64", ENC_BASE64},
1224         {"x-uuencode", ENC_UNKNOWN},
1225         {NULL, ENC_UNKNOWN},
1226 };
1227
1228 const gchar *procmime_get_encoding_str(EncodingType encoding)
1229 {
1230         struct EncodingTable *enc_table;
1231         
1232         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1233                 if (enc_table->enc_type == encoding)
1234                         return enc_table->str;
1235         }
1236         return NULL;
1237 }
1238
1239 /* --- NEW MIME STUFF --- */
1240 struct TypeTable
1241 {
1242         gchar *str;
1243         MimeMediaType type;
1244 };
1245
1246 static struct TypeTable mime_type_table[] = {
1247         {"text", MIMETYPE_TEXT},
1248         {"image", MIMETYPE_IMAGE},
1249         {"audio", MIMETYPE_AUDIO},
1250         {"video", MIMETYPE_VIDEO},
1251         {"application", MIMETYPE_APPLICATION},
1252         {"message", MIMETYPE_MESSAGE},
1253         {"multipart", MIMETYPE_MULTIPART},
1254         {NULL, 0},
1255 };
1256
1257 const gchar *procmime_get_media_type_str(MimeMediaType type)
1258 {
1259         struct TypeTable *type_table;
1260         
1261         for (type_table = mime_type_table; type_table->str != NULL; type_table++) {
1262                 if (type_table->type == type)
1263                         return type_table->str;
1264         }
1265         return NULL;
1266 }
1267
1268 MimeMediaType procmime_get_media_type(const gchar *str)
1269 {
1270         struct TypeTable *typetablearray;
1271
1272         for (typetablearray = mime_type_table; typetablearray->str != NULL; typetablearray++)
1273                 if (g_ascii_strncasecmp(str, typetablearray->str, strlen(typetablearray->str)) == 0)
1274                         return typetablearray->type;
1275
1276         return MIMETYPE_UNKNOWN;
1277 }
1278
1279 /*!
1280  *\brief        Safe wrapper for content type string.
1281  *
1282  *\return       const gchar * Pointer to content type string. 
1283  */
1284 gchar *procmime_get_content_type_str(MimeMediaType type,
1285                                            const char *subtype)
1286 {
1287         const gchar *type_str = NULL;
1288
1289         if (subtype == NULL || !(type_str = procmime_get_media_type_str(type)))
1290                 return g_strdup("unknown");
1291         return g_strdup_printf("%s/%s", type_str, subtype);
1292 }
1293
1294 static int procmime_parse_mimepart(MimeInfo *parent,
1295                              gchar *content_type,
1296                              gchar *content_encoding,
1297                              gchar *content_description,
1298                              gchar *content_id,
1299                              gchar *content_disposition,
1300                              gchar *content_location,
1301                              const gchar *original_msgid,
1302                              const gchar *disposition_notification_hdr,
1303                              const gchar *filename,
1304                              guint offset,
1305                              guint length,
1306                              gboolean short_scan);
1307
1308 static void procmime_parse_message_rfc822(MimeInfo *mimeinfo, gboolean short_scan)
1309 {
1310         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1311                                 {"Content-Transfer-Encoding:",
1312                                                    NULL, FALSE},
1313                                 {"Content-Description:",
1314                                                    NULL, TRUE},
1315                                 {"Content-ID:",
1316                                                    NULL, TRUE},
1317                                 {"Content-Disposition:",
1318                                                    NULL, TRUE},
1319                                 {"Content-Location:",
1320                                                    NULL, TRUE},
1321                                 {"MIME-Version:",
1322                                                    NULL, TRUE},
1323                                 {"Original-Message-ID:",
1324                                                    NULL, TRUE},
1325                                 {"Disposition:",
1326                                                    NULL, TRUE},
1327                                 {NULL,             NULL, FALSE}};
1328         guint content_start, i;
1329         FILE *fp;
1330         gchar *tmp;
1331         gint len = 0;
1332
1333         procmime_decode_content(mimeinfo);
1334
1335         fp = g_fopen(mimeinfo->data.filename, "rb");
1336         if (fp == NULL) {
1337                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1338                 return;
1339         }
1340         fseek(fp, mimeinfo->offset, SEEK_SET);
1341         procheader_get_header_fields(fp, hentry);
1342         if (hentry[0].body != NULL) {
1343                 tmp = conv_unmime_header(hentry[0].body, NULL);
1344                 g_free(hentry[0].body);
1345                 hentry[0].body = tmp;
1346         }                
1347         if (hentry[2].body != NULL) {
1348                 tmp = conv_unmime_header(hentry[2].body, NULL);
1349                 g_free(hentry[2].body);
1350                 hentry[2].body = tmp;
1351         }                
1352         if (hentry[4].body != NULL) {
1353                 tmp = conv_unmime_header(hentry[4].body, NULL);
1354                 g_free(hentry[4].body);
1355                 hentry[4].body = tmp;
1356         }                
1357         if (hentry[5].body != NULL) {
1358                 tmp = conv_unmime_header(hentry[5].body, NULL);
1359                 g_free(hentry[5].body);
1360                 hentry[5].body = tmp;
1361         }                
1362         if (hentry[7].body != NULL) {
1363                 tmp = conv_unmime_header(hentry[7].body, NULL);
1364                 g_free(hentry[7].body);
1365                 hentry[7].body = tmp;
1366         }
1367         if (hentry[8].body != NULL) {
1368                 tmp = conv_unmime_header(hentry[8].body, NULL);
1369                 g_free(hentry[8].body);
1370                 hentry[8].body = tmp;
1371         }
1372   
1373         content_start = ftell(fp);
1374         fclose(fp);
1375         
1376         len = mimeinfo->length - (content_start - mimeinfo->offset);
1377         if (len < 0)
1378                 len = 0;
1379         procmime_parse_mimepart(mimeinfo,
1380                                 hentry[0].body, hentry[1].body,
1381                                 hentry[2].body, hentry[3].body,
1382                                 hentry[4].body, hentry[5].body,
1383                                 hentry[7].body, hentry[8].body, 
1384                                 mimeinfo->data.filename, content_start,
1385                                 len, short_scan);
1386         
1387         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1388                 g_free(hentry[i].body);
1389                 hentry[i].body = NULL;
1390         }
1391 }
1392
1393 static void procmime_parse_disposition_notification(MimeInfo *mimeinfo, 
1394                 const gchar *original_msgid, const gchar *disposition_notification_hdr,
1395                 gboolean short_scan)
1396 {
1397         HeaderEntry hentry[] = {{"Original-Message-ID:",  NULL, TRUE},
1398                                 {"Disposition:",          NULL, TRUE},
1399                                 {NULL,                    NULL, FALSE}};
1400         guint i;
1401         FILE *fp;
1402         gchar *orig_msg_id = NULL;
1403         gchar *disp = NULL;
1404
1405         procmime_decode_content(mimeinfo);
1406
1407         debug_print("parse disposition notification\n");
1408         fp = g_fopen(mimeinfo->data.filename, "rb");
1409         if (fp == NULL) {
1410                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1411                 return;
1412         }
1413         fseek(fp, mimeinfo->offset, SEEK_SET);
1414
1415         if (original_msgid && disposition_notification_hdr) {
1416                 hentry[0].body = g_strdup(original_msgid);
1417                 hentry[1].body = g_strdup(disposition_notification_hdr);
1418         } else {
1419                 procheader_get_header_fields(fp, hentry);
1420         }
1421
1422         if (!hentry[0].body || !hentry[1].body) {
1423                 debug_print("MsgId %s, Disp %s\n",
1424                         hentry[0].body ? hentry[0].body:"(nil)",
1425                         hentry[1].body ? hentry[1].body:"(nil)");
1426                 goto bail;
1427         }
1428
1429         orig_msg_id = g_strdup(hentry[0].body);
1430         disp = g_strdup(hentry[1].body);
1431
1432         extract_parenthesis(orig_msg_id, '<', '>');
1433         remove_space(orig_msg_id);
1434         
1435         if (strstr(disp, "displayed")) {
1436                 /* find sent message, if possible */
1437                 MsgInfo *info = NULL;
1438                 GList *flist;
1439                 debug_print("%s has been displayed.\n", orig_msg_id);
1440                 for (flist = folder_get_list(); flist != NULL; flist = g_list_next(flist)) {
1441                         FolderItem *outbox = ((Folder *)(flist->data))->outbox;
1442                         if (!outbox) {
1443                                 debug_print("skipping folder with no outbox...\n");
1444                                 continue;
1445                         }
1446                         info = folder_item_get_msginfo_by_msgid(outbox, orig_msg_id);
1447                         debug_print("%s %s in %s\n", info?"found":"didn't find", orig_msg_id, outbox->path);
1448                         if (info) {
1449                                 procmsg_msginfo_set_flags(info, MSG_RETRCPT_GOT, 0);
1450                                 procmsg_msginfo_free(info);
1451                         }
1452                 }
1453         }
1454         g_free(orig_msg_id);
1455         g_free(disp);
1456 bail:
1457         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1458                 g_free(hentry[i].body);
1459                 hentry[i].body = NULL;
1460         }
1461 }
1462
1463 #define GET_HEADERS() {                                         \
1464         procheader_get_header_fields(fp, hentry);               \
1465         if (hentry[0].body != NULL) {                           \
1466                 tmp = conv_unmime_header(hentry[0].body, NULL); \
1467                 g_free(hentry[0].body);                         \
1468                 hentry[0].body = tmp;                           \
1469         }                                                       \
1470         if (hentry[2].body != NULL) {                           \
1471                 tmp = conv_unmime_header(hentry[2].body, NULL); \
1472                 g_free(hentry[2].body);                         \
1473                 hentry[2].body = tmp;                           \
1474         }                                                       \
1475         if (hentry[4].body != NULL) {                           \
1476                 tmp = conv_unmime_header(hentry[4].body, NULL); \
1477                 g_free(hentry[4].body);                         \
1478                 hentry[4].body = tmp;                           \
1479         }                                                       \
1480         if (hentry[5].body != NULL) {                           \
1481                 tmp = conv_unmime_header(hentry[5].body, NULL); \
1482                 g_free(hentry[5].body);                         \
1483                 hentry[5].body = tmp;                           \
1484         }                                                       \
1485         if (hentry[6].body != NULL) {                           \
1486                 tmp = conv_unmime_header(hentry[6].body, NULL); \
1487                 g_free(hentry[6].body);                         \
1488                 hentry[6].body = tmp;                           \
1489         }                                                       \
1490         if (hentry[7].body != NULL) {                           \
1491                 tmp = conv_unmime_header(hentry[7].body, NULL); \
1492                 g_free(hentry[7].body);                         \
1493                 hentry[7].body = tmp;                           \
1494         }                                                       \
1495 }
1496
1497 static void procmime_parse_multipart(MimeInfo *mimeinfo, gboolean short_scan)
1498 {
1499         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1500                                 {"Content-Transfer-Encoding:",
1501                                                    NULL, FALSE},
1502                                 {"Content-Description:",
1503                                                    NULL, TRUE},
1504                                 {"Content-ID:",
1505                                                    NULL, TRUE},
1506                                 {"Content-Disposition:",
1507                                                    NULL, TRUE},
1508                                 {"Content-Location:",
1509                                                    NULL, TRUE},
1510                                 {"Original-Message-ID:",
1511                                                    NULL, TRUE},
1512                                 {"Disposition:",
1513                                                    NULL, TRUE},
1514                                 {NULL,             NULL, FALSE}};
1515         gchar *p, *tmp;
1516         gchar *boundary;
1517         gint boundary_len = 0, lastoffset = -1, i;
1518         gchar buf[BUFFSIZE];
1519         FILE *fp;
1520         int result = 0;
1521         gboolean done = FALSE;
1522
1523         boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
1524         if (!boundary)
1525                 return;
1526         boundary_len = strlen(boundary);
1527
1528         procmime_decode_content(mimeinfo);
1529
1530         fp = g_fopen(mimeinfo->data.filename, "rb");
1531         if (fp == NULL) {
1532                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1533                 return;
1534         }
1535         fseek(fp, mimeinfo->offset, SEEK_SET);
1536         while ((p = fgets(buf, sizeof(buf), fp)) != NULL && result == 0) {
1537                 if (ftell(fp) - 1 > (mimeinfo->offset + mimeinfo->length))
1538                         break;
1539
1540                 if (IS_BOUNDARY(buf, boundary, boundary_len)) {
1541                         if (lastoffset != -1) {
1542                                 gint len = (ftell(fp) - strlen(buf)) - lastoffset - 1;
1543                                 if (len < 0)
1544                                         len = 0;
1545                                 result = procmime_parse_mimepart(mimeinfo,
1546                                                         hentry[0].body, hentry[1].body,
1547                                                         hentry[2].body, hentry[3].body, 
1548                                                         hentry[4].body, hentry[5].body,
1549                                                         hentry[6].body, hentry[7].body,
1550                                                         mimeinfo->data.filename, lastoffset,
1551                                                         len, short_scan);
1552                                 if (result == 1 && short_scan) {
1553                                         done = TRUE;
1554                                         break;
1555                                 }
1556                         } 
1557                         
1558                         if (buf[2 + boundary_len]     == '-' &&
1559                             buf[2 + boundary_len + 1] == '-') {
1560                                 break;
1561                         }
1562                         for (i = 0; i < (sizeof hentry / sizeof hentry[0]) ; i++) {
1563                                 g_free(hentry[i].body);
1564                                 hentry[i].body = NULL;
1565                         }
1566                         GET_HEADERS();
1567                         lastoffset = ftell(fp);
1568                 }
1569         }
1570         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1571                 g_free(hentry[i].body);
1572                 hentry[i].body = NULL;
1573         }
1574         fclose(fp);
1575 }
1576
1577 static void parse_parameters(const gchar *parameters, GHashTable *table)
1578 {
1579         gchar *params, *param, *next;
1580         GSList *convlist = NULL, *concatlist = NULL, *cur;
1581
1582         params = g_strdup(parameters);
1583         param = params;
1584         next = params;
1585         for (; next != NULL; param = next) {
1586                 gchar *attribute, *value, *tmp, *down_attr;
1587                 gint len;
1588                 gboolean convert = FALSE;
1589
1590                 next = strchr_with_skip_quote(param, '"', ';');
1591                 if (next != NULL) {
1592                         next[0] = '\0';
1593                         next++;
1594                 }
1595
1596                 g_strstrip(param);
1597
1598                 attribute = param;
1599                 value = strchr(attribute, '=');
1600                 if (value == NULL)
1601                         continue;
1602
1603                 value[0] = '\0';
1604                 value++;
1605                 while (value[0] == ' ')
1606                         value++;
1607
1608                 down_attr = g_utf8_strdown(attribute, -1);
1609                 
1610                 len = strlen(down_attr);
1611                 if (down_attr[len - 1] == '*') {
1612                         gchar *srcpos, *dstpos, *endpos;
1613
1614                         convert = TRUE;
1615                         down_attr[len - 1] = '\0';
1616
1617                         srcpos = value;
1618                         dstpos = value;
1619                         endpos = value + strlen(value);
1620                         while (srcpos < endpos) {
1621                                 if (*srcpos != '%')
1622                                         *dstpos = *srcpos;
1623                                 else {
1624                                         guchar dstvalue;
1625
1626                                         if (!get_hex_value(&dstvalue, srcpos[1], srcpos[2]))
1627                                                 *dstpos = '?';
1628                                         else
1629                                                 *dstpos = dstvalue;
1630                                         srcpos += 2;
1631                                 }
1632                                 srcpos++;
1633                                 dstpos++;
1634                         }
1635                         *dstpos = '\0';
1636                 } else {
1637                         if (value[0] == '"')
1638                                 extract_quote(value, '"');
1639                         else if ((tmp = strchr(value, ' ')) != NULL)
1640                                 *tmp = '\0';
1641                 }
1642
1643                 if (down_attr) {
1644                         while (down_attr[0] == ' ')
1645                                 down_attr++;
1646                         while (down_attr[strlen(down_attr)-1] == ' ') 
1647                                 down_attr[strlen(down_attr)-1] = '\0';
1648                 } 
1649                 if (value) {
1650                         while (value[0] == ' ')
1651                                 value++;
1652                         while (value[strlen(value)-1] == ' ') 
1653                                 value[strlen(value)-1] = '\0';
1654                 }               
1655                 if (strrchr(down_attr, '*') != NULL) {
1656                         gchar *tmpattr;
1657
1658                         tmpattr = g_strdup(down_attr);
1659                         tmp = strrchr(tmpattr, '*');
1660                         tmp[0] = '\0';
1661
1662                         if ((tmp[1] == '0') && (tmp[2] == '\0') && 
1663                             (g_slist_find_custom(concatlist, down_attr, g_str_equal) == NULL))
1664                                 concatlist = g_slist_prepend(concatlist, g_strdup(tmpattr));
1665
1666                         if (convert && (g_slist_find_custom(convlist, down_attr, g_str_equal) == NULL))
1667                                 convlist = g_slist_prepend(convlist, g_strdup(tmpattr));
1668
1669                         g_free(tmpattr);
1670                 } else if (convert) {
1671                         if (g_slist_find_custom(convlist, down_attr, g_str_equal) == NULL)
1672                                 convlist = g_slist_prepend(convlist, g_strdup(down_attr));
1673                 }
1674
1675                 if (g_hash_table_lookup(table, down_attr) == NULL)
1676                         g_hash_table_insert(table, g_strdup(down_attr), g_strdup(value));
1677                 g_free(down_attr);
1678         }
1679
1680         for (cur = concatlist; cur != NULL; cur = g_slist_next(cur)) {
1681                 gchar *attribute, *attrwnum, *partvalue;
1682                 gint n = 0;
1683                 GString *value;
1684
1685                 attribute = (gchar *) cur->data;
1686                 value = g_string_sized_new(64);
1687
1688                 attrwnum = g_strdup_printf("%s*%d", attribute, n);
1689                 while ((partvalue = g_hash_table_lookup(table, attrwnum)) != NULL) {
1690                         g_string_append(value, partvalue);
1691
1692                         g_free(attrwnum);
1693                         n++;
1694                         attrwnum = g_strdup_printf("%s*%d", attribute, n);
1695                 }
1696                 g_free(attrwnum);
1697
1698                 g_hash_table_insert(table, g_strdup(attribute), g_strdup(value->str));
1699                 g_string_free(value, TRUE);
1700         }
1701         slist_free_strings(concatlist);
1702         g_slist_free(concatlist);
1703
1704         for (cur = convlist; cur != NULL; cur = g_slist_next(cur)) {
1705                 gchar *attribute, *key, *value;
1706                 gchar *charset, *lang, *oldvalue, *newvalue;
1707
1708                 attribute = (gchar *) cur->data;
1709                 if (!g_hash_table_lookup_extended(
1710                         table, attribute, (gpointer *)(gchar *) &key, (gpointer *)(gchar *) &value))
1711                         continue;
1712
1713                 charset = value;
1714                 lang = strchr(charset, '\'');
1715                 if (lang == NULL)
1716                         continue;
1717                 lang[0] = '\0';
1718                 lang++;
1719                 oldvalue = strchr(lang, '\'');
1720                 if (oldvalue == NULL)
1721                         continue;
1722                 oldvalue[0] = '\0';
1723                 oldvalue++;
1724
1725                 newvalue = conv_codeset_strdup(oldvalue, charset, CS_UTF_8);
1726
1727                 g_hash_table_remove(table, attribute);
1728                 g_free(key);
1729                 g_free(value);
1730
1731                 g_hash_table_insert(table, g_strdup(attribute), newvalue);
1732         }
1733         slist_free_strings(convlist);
1734         g_slist_free(convlist);
1735
1736         g_free(params);
1737 }       
1738
1739 static void procmime_parse_content_type(const gchar *content_type, MimeInfo *mimeinfo)
1740 {
1741         g_return_if_fail(content_type != NULL);
1742         g_return_if_fail(mimeinfo != NULL);
1743
1744         /* RFC 2045, page 13 says that the mime subtype is MANDATORY;
1745          * if it's not available we use the default Content-Type */
1746         if ((content_type[0] == '\0') || (strchr(content_type, '/') == NULL)) {
1747                 mimeinfo->type = MIMETYPE_TEXT;
1748                 mimeinfo->subtype = g_strdup("plain");
1749                 if (g_hash_table_lookup(mimeinfo->typeparameters,
1750                                        "charset") == NULL) {
1751                         g_hash_table_insert(mimeinfo->typeparameters,
1752                                     g_strdup("charset"),
1753                                     g_strdup(
1754                                         conv_get_locale_charset_str_no_utf8()));
1755                 }
1756         } else {
1757                 gchar *type, *subtype, *params;
1758
1759                 type = g_strdup(content_type);
1760                 subtype = strchr(type, '/') + 1;
1761                 *(subtype - 1) = '\0';
1762                 if ((params = strchr(subtype, ';')) != NULL) {
1763                         params[0] = '\0';
1764                         params++;
1765                 }
1766
1767                 mimeinfo->type = procmime_get_media_type(type);
1768                 mimeinfo->subtype = g_strstrip(g_strdup(subtype));
1769
1770                 /* Get mimeinfo->typeparameters */
1771                 if (params != NULL)
1772                         parse_parameters(params, mimeinfo->typeparameters);
1773
1774                 g_free(type);
1775         }
1776 }
1777
1778 static void procmime_parse_content_disposition(const gchar *content_disposition, MimeInfo *mimeinfo)
1779 {
1780         gchar *tmp, *params;
1781
1782         g_return_if_fail(content_disposition != NULL);
1783         g_return_if_fail(mimeinfo != NULL);
1784
1785         tmp = g_strdup(content_disposition);
1786         if ((params = strchr(tmp, ';')) != NULL) {
1787                 params[0] = '\0';
1788                 params++;
1789         }       
1790         g_strstrip(tmp);
1791
1792         if (!g_ascii_strcasecmp(tmp, "inline")) 
1793                 mimeinfo->disposition = DISPOSITIONTYPE_INLINE;
1794         else if (!g_ascii_strcasecmp(tmp, "attachment"))
1795                 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1796         else
1797                 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1798         
1799         if (params != NULL)
1800                 parse_parameters(params, mimeinfo->dispositionparameters);
1801
1802         g_free(tmp);
1803 }
1804
1805
1806 static void procmime_parse_content_encoding(const gchar *content_encoding, MimeInfo *mimeinfo)
1807 {
1808         struct EncodingTable *enc_table;
1809         
1810         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1811                 if (g_ascii_strcasecmp(enc_table->str, content_encoding) == 0) {
1812                         mimeinfo->encoding_type = enc_table->enc_type;
1813                         return;
1814                 }
1815         }
1816         mimeinfo->encoding_type = ENC_UNKNOWN;
1817         return;
1818 }
1819
1820 static GSList *registered_parsers = NULL;
1821
1822 static MimeParser *procmime_get_mimeparser_for_type(MimeMediaType type, const gchar *sub_type)
1823 {
1824         GSList *cur;
1825         for (cur = registered_parsers; cur; cur = cur->next) {
1826                 MimeParser *parser = (MimeParser *)cur->data;
1827                 if (parser->type == type && !strcmp2(parser->sub_type, sub_type))
1828                         return parser;
1829         }
1830         return NULL;
1831 }
1832
1833 void procmime_mimeparser_register(MimeParser *parser)
1834 {
1835         if (!procmime_get_mimeparser_for_type(parser->type, parser->sub_type))
1836                 registered_parsers = g_slist_append(registered_parsers, parser);
1837 }
1838
1839
1840 void procmime_mimeparser_unregister(MimeParser *parser) 
1841 {
1842         registered_parsers = g_slist_remove(registered_parsers, parser);
1843 }
1844
1845 static gboolean procmime_mimeparser_parse(MimeParser *parser, MimeInfo *mimeinfo)
1846 {
1847         g_return_val_if_fail(parser->parse != NULL, FALSE);
1848         return parser->parse(parser, mimeinfo); 
1849 }
1850
1851 static int procmime_parse_mimepart(MimeInfo *parent,
1852                              gchar *content_type,
1853                              gchar *content_encoding,
1854                              gchar *content_description,
1855                              gchar *content_id,
1856                              gchar *content_disposition,
1857                              gchar *content_location,
1858                              const gchar *original_msgid,
1859                              const gchar *disposition_notification_hdr,
1860                              const gchar *filename,
1861                              guint offset,
1862                              guint length,
1863                              gboolean short_scan)
1864 {
1865         MimeInfo *mimeinfo;
1866         MimeParser *parser = NULL;
1867         gboolean parsed = FALSE;
1868         int result = 0;
1869
1870         /* Create MimeInfo */
1871         mimeinfo = procmime_mimeinfo_new();
1872         mimeinfo->content = MIMECONTENT_FILE;
1873         if (parent != NULL) {
1874                 if (g_node_depth(parent->node) > 32) {
1875                         /* 32 is an arbitrary value
1876                          * this avoids DOSsing ourselves 
1877                          * with enormous messages
1878                          */
1879                         procmime_mimeinfo_free_all(mimeinfo);
1880                         return -1;                      
1881                 }
1882                 g_node_append(parent->node, mimeinfo->node);
1883         }
1884         mimeinfo->data.filename = g_strdup(filename);
1885         mimeinfo->offset = offset;
1886         mimeinfo->length = length;
1887
1888         if (content_type != NULL) {
1889                 procmime_parse_content_type(content_type, mimeinfo);
1890         } else {
1891                 mimeinfo->type = MIMETYPE_TEXT;
1892                 mimeinfo->subtype = g_strdup("plain");
1893                 if (g_hash_table_lookup(mimeinfo->typeparameters,
1894                                        "charset") == NULL) {
1895                         g_hash_table_insert(mimeinfo->typeparameters,
1896                                     g_strdup("charset"),
1897                                     g_strdup(
1898                                         conv_get_locale_charset_str_no_utf8()));
1899                 }
1900         }
1901
1902         if (content_encoding != NULL) {
1903                 procmime_parse_content_encoding(content_encoding, mimeinfo);
1904         } else {
1905                 mimeinfo->encoding_type = ENC_UNKNOWN;
1906         }
1907
1908         if (content_description != NULL)
1909                 mimeinfo->description = g_strdup(content_description);
1910         else
1911                 mimeinfo->description = NULL;
1912
1913         if (content_id != NULL)
1914                 mimeinfo->id = g_strdup(content_id);
1915         else
1916                 mimeinfo->id = NULL;
1917
1918         if (content_location != NULL)
1919                 mimeinfo->location = g_strdup(content_location);
1920         else
1921                 mimeinfo->location = NULL;
1922
1923         if (content_disposition != NULL) 
1924                 procmime_parse_content_disposition(content_disposition, mimeinfo);
1925         else
1926                 mimeinfo->disposition = DISPOSITIONTYPE_UNKNOWN;
1927
1928         /* Call parser for mime type */
1929         if ((parser = procmime_get_mimeparser_for_type(mimeinfo->type, mimeinfo->subtype)) != NULL) {
1930                 parsed = procmime_mimeparser_parse(parser, mimeinfo);
1931         } 
1932         if (!parsed) {
1933                 switch (mimeinfo->type) {
1934                 case MIMETYPE_TEXT:
1935                         if (g_ascii_strcasecmp(mimeinfo->subtype, "plain") == 0 && short_scan) {
1936                                 return 1;
1937                         }
1938                         break;
1939
1940                 case MIMETYPE_MESSAGE:
1941                         if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
1942                                 procmime_parse_message_rfc822(mimeinfo, short_scan);
1943                         }
1944                         if (g_ascii_strcasecmp(mimeinfo->subtype, "disposition-notification") == 0) {
1945                                 procmime_parse_disposition_notification(mimeinfo, 
1946                                         original_msgid, disposition_notification_hdr, short_scan);
1947                         }
1948                         break;
1949                         
1950                 case MIMETYPE_MULTIPART:
1951                         procmime_parse_multipart(mimeinfo, short_scan);
1952                         break;
1953                 
1954                 case MIMETYPE_APPLICATION:
1955                         if (g_ascii_strcasecmp(mimeinfo->subtype, "octet-stream") == 0
1956                         && original_msgid && *original_msgid 
1957                         && disposition_notification_hdr && *disposition_notification_hdr) {
1958                                 procmime_parse_disposition_notification(mimeinfo, 
1959                                         original_msgid, disposition_notification_hdr, short_scan);
1960                         }
1961                         break;
1962                 default:
1963                         break;
1964                 }
1965         }
1966
1967         return result;
1968 }
1969
1970 static gchar *typenames[] = {
1971     "text",
1972     "image",
1973     "audio",
1974     "video",
1975     "application",
1976     "message",
1977     "multipart",
1978     "unknown",
1979 };
1980
1981 static gboolean output_func(GNode *node, gpointer data)
1982 {
1983         guint i, depth;
1984         MimeInfo *mimeinfo = (MimeInfo *) node->data;
1985
1986         depth = g_node_depth(node);
1987         for (i = 0; i < depth; i++)
1988                 g_print("    ");
1989         g_print("%s/%s (offset:%d length:%d encoding: %d)\n", typenames[mimeinfo->type], mimeinfo->subtype, mimeinfo->offset, mimeinfo->length, mimeinfo->encoding_type);
1990
1991         return FALSE;
1992 }
1993
1994 static void output_mime_structure(MimeInfo *mimeinfo, int indent)
1995 {
1996         g_node_traverse(mimeinfo->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1, output_func, NULL);
1997 }
1998
1999 static MimeInfo *procmime_scan_file_with_offset(const gchar *filename, int offset, gboolean short_scan)
2000 {
2001         MimeInfo *mimeinfo;
2002         struct stat buf;
2003
2004         stat(filename, &buf);
2005
2006         mimeinfo = procmime_mimeinfo_new();
2007         mimeinfo->content = MIMECONTENT_FILE;
2008         mimeinfo->encoding_type = ENC_UNKNOWN;
2009         mimeinfo->type = MIMETYPE_MESSAGE;
2010         mimeinfo->subtype = g_strdup("rfc822");
2011         mimeinfo->data.filename = g_strdup(filename);
2012         mimeinfo->offset = offset;
2013         mimeinfo->length = buf.st_size - offset;
2014
2015         procmime_parse_message_rfc822(mimeinfo, short_scan);
2016         if (debug_get_mode())
2017                 output_mime_structure(mimeinfo, 0);
2018
2019         return mimeinfo;
2020 }
2021
2022 static MimeInfo *procmime_scan_file_full(const gchar *filename, gboolean short_scan)
2023 {
2024         MimeInfo *mimeinfo;
2025
2026         g_return_val_if_fail(filename != NULL, NULL);
2027
2028         mimeinfo = procmime_scan_file_with_offset(filename, 0, short_scan);
2029
2030         return mimeinfo;
2031 }
2032
2033 MimeInfo *procmime_scan_file(const gchar *filename)
2034 {
2035         return procmime_scan_file_full(filename, FALSE);
2036 }
2037
2038 static MimeInfo *procmime_scan_file_short(const gchar *filename)
2039 {
2040         return procmime_scan_file_full(filename, TRUE);
2041 }
2042
2043 static MimeInfo *procmime_scan_queue_file_full(const gchar *filename, gboolean short_scan)
2044 {
2045         FILE *fp;
2046         MimeInfo *mimeinfo;
2047         gchar buf[BUFFSIZE];
2048         gint offset = 0;
2049
2050         g_return_val_if_fail(filename != NULL, NULL);
2051
2052         /* Open file */
2053         if ((fp = g_fopen(filename, "rb")) == NULL)
2054                 return NULL;
2055         /* Skip queue header */
2056         while (fgets(buf, sizeof(buf), fp) != NULL) {
2057                 /* new way */
2058                 if ((!strncmp(buf, "X-Claws-End-Special-Headers: 1",
2059                         strlen("X-Claws-End-Special-Headers:"))) ||
2060                    (!strncmp(buf, "X-Sylpheed-End-Special-Headers: 1",
2061                         strlen("X-Sylpheed-End-Special-Headers:"))))
2062                         break;
2063                 /* old way */
2064                 if (buf[0] == '\r' || buf[0] == '\n') break;
2065                 /* from other mailers */
2066                 if (!strncmp(buf, "Date: ", 6)
2067                 ||  !strncmp(buf, "To: ", 4)
2068                 ||  !strncmp(buf, "From: ", 6)
2069                 ||  !strncmp(buf, "Subject: ", 9)) {
2070                         rewind(fp);
2071                         break;
2072                 }
2073         }
2074         offset = ftell(fp);
2075         fclose(fp);
2076
2077         mimeinfo = procmime_scan_file_with_offset(filename, offset, short_scan);
2078
2079         return mimeinfo;
2080 }
2081
2082 MimeInfo *procmime_scan_queue_file(const gchar *filename)
2083 {
2084         return procmime_scan_queue_file_full(filename, FALSE);
2085 }
2086
2087 static MimeInfo *procmime_scan_queue_file_short(const gchar *filename)
2088 {
2089         return procmime_scan_queue_file_full(filename, TRUE);
2090 }
2091
2092 typedef enum {
2093     ENC_AS_TOKEN,
2094     ENC_AS_QUOTED_STRING,
2095     ENC_AS_EXTENDED,
2096     ENC_TO_ASCII,
2097 } EncodeAs;
2098
2099 typedef struct _ParametersData {
2100         FILE *fp;
2101         guint len;
2102         guint ascii_only;
2103         gint error;
2104 } ParametersData;
2105
2106 static void write_parameters(gpointer key, gpointer value, gpointer user_data)
2107 {
2108         gchar *param = key;
2109         gchar *val = value, *valpos, *tmp;
2110         ParametersData *pdata = (ParametersData *)user_data;
2111         GString *buf = g_string_new("");
2112
2113         EncodeAs encas = ENC_AS_TOKEN;
2114
2115         for (valpos = val; *valpos != 0; valpos++) {
2116                 if (!IS_ASCII(*valpos) || *valpos == '"') {
2117                         encas = ENC_AS_EXTENDED;
2118                         break;
2119                 }
2120             
2121                 /* CTLs */
2122                 if (((*valpos >= 0) && (*valpos < 037)) || (*valpos == 0177)) {
2123                         encas = ENC_AS_QUOTED_STRING;
2124                         continue;
2125                 }
2126
2127                 /* tspecials + SPACE */
2128                 switch (*valpos) {
2129                 case ' ':
2130                 case '(': 
2131                 case ')':
2132                 case '<':
2133                 case '>':
2134                 case '@':
2135                 case ',':
2136                 case ';':
2137                 case ':':
2138                 case '\\':
2139                 case '\'':
2140                 case '/':
2141                 case '[':
2142                 case ']':
2143                 case '?':
2144                 case '=':
2145                         encas = ENC_AS_QUOTED_STRING;
2146                         continue;
2147                 }
2148         }
2149         
2150         if (encas == ENC_AS_EXTENDED && pdata->ascii_only == TRUE) 
2151                 encas = ENC_TO_ASCII;
2152
2153         switch (encas) {
2154         case ENC_AS_TOKEN:
2155                 g_string_append_printf(buf, "%s=%s", param, val);
2156                 break;
2157
2158         case ENC_TO_ASCII:
2159                 tmp = g_strdup(val);
2160                 g_strcanon(tmp, 
2161                         " ()<>@,';:\\/[]?=.0123456789"
2162                         "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2163                         "abcdefghijklmnopqrstuvwxyz",
2164                         '_');
2165                 g_string_append_printf(buf, "%s=\"%s\"", param, tmp);
2166                 g_free(tmp);
2167                 break;
2168
2169         case ENC_AS_QUOTED_STRING:
2170                 g_string_append_printf(buf, "%s=\"%s\"", param, val);
2171                 break;
2172
2173         case ENC_AS_EXTENDED:
2174                 if (!g_utf8_validate(val, -1, NULL))
2175                         g_string_append_printf(buf, "%s*=%s''", param,
2176                                 conv_get_locale_charset_str());
2177                 else
2178                         g_string_append_printf(buf, "%s*=%s''", param,
2179                                 CS_INTERNAL);
2180                 for (valpos = val; *valpos != '\0'; valpos++) {
2181                         if (IS_ASCII(*valpos) && isalnum(*valpos)) {
2182                                 g_string_append_printf(buf, "%c", *valpos);
2183                         } else {
2184                                 gchar hexstr[3] = "XX";
2185                                 get_hex_str(hexstr, *valpos);
2186                                 g_string_append_printf(buf, "%%%s", hexstr);
2187                         }
2188                 }
2189                 break;          
2190         }
2191         
2192         if (buf->str && strlen(buf->str)) {
2193                 if (pdata->len + strlen(buf->str) + 2 > 76) {
2194                         if (fprintf(pdata->fp, ";\n %s", buf->str) < 0)
2195                                 pdata->error = TRUE;
2196                         pdata->len = strlen(buf->str) + 1;
2197                 } else {
2198                         if (fprintf(pdata->fp, "; %s", buf->str) < 0)
2199                                 pdata->error = TRUE;
2200                         pdata->len += strlen(buf->str) + 2;
2201                 }
2202         }
2203         g_string_free(buf, TRUE);
2204 }
2205
2206 #define TRY(func) { \
2207         if (!(func)) { \
2208                 return -1; \
2209         } \
2210 }
2211
2212 int procmime_write_mime_header(MimeInfo *mimeinfo, FILE *fp)
2213 {
2214         struct TypeTable *type_table;
2215         ParametersData *pdata = g_new0(ParametersData, 1);
2216         debug_print("procmime_write_mime_header\n");
2217         
2218         pdata->fp = fp;
2219         pdata->ascii_only = FALSE;
2220         pdata->error = FALSE;
2221         for (type_table = mime_type_table; type_table->str != NULL; type_table++)
2222                 if (mimeinfo->type == type_table->type) {
2223                         gchar *buf = g_strdup_printf(
2224                                 "Content-Type: %s/%s", type_table->str, mimeinfo->subtype);
2225                         if (fprintf(fp, "%s", buf) < 0) {
2226                                 g_free(buf);
2227                                 g_free(pdata);
2228                                 return -1;
2229                         }
2230                         pdata->len = strlen(buf);
2231                         pdata->ascii_only = TRUE;
2232                         g_free(buf);
2233                         break;
2234                 }
2235         g_hash_table_foreach(mimeinfo->typeparameters, write_parameters, pdata);
2236         if (pdata->error == TRUE) {
2237                 g_free(pdata);
2238                 return -1;
2239         }
2240         g_free(pdata);
2241
2242         TRY(fprintf(fp, "\n") >= 0);
2243
2244         if (mimeinfo->encoding_type != ENC_UNKNOWN)
2245                 TRY(fprintf(fp, "Content-Transfer-Encoding: %s\n", procmime_get_encoding_str(mimeinfo->encoding_type)) >= 0);
2246
2247         if (mimeinfo->description != NULL)
2248                 TRY(fprintf(fp, "Content-Description: %s\n", mimeinfo->description) >= 0);
2249
2250         if (mimeinfo->id != NULL)
2251                 TRY(fprintf(fp, "Content-ID: %s\n", mimeinfo->id) >= 0);
2252
2253         if (mimeinfo->location != NULL)
2254                 TRY(fprintf(fp, "Content-Location: %s\n", mimeinfo->location) >= 0);
2255
2256         if (mimeinfo->disposition != DISPOSITIONTYPE_UNKNOWN) {
2257                 ParametersData *pdata = g_new0(ParametersData, 1);
2258                 gchar *buf = NULL;
2259                 if (mimeinfo->disposition == DISPOSITIONTYPE_INLINE)
2260                         buf = g_strdup("Content-Disposition: inline");
2261                 else if (mimeinfo->disposition == DISPOSITIONTYPE_ATTACHMENT)
2262                         buf = g_strdup("Content-Disposition: attachment");
2263                 else
2264                         buf = g_strdup("Content-Disposition: unknown");
2265
2266                 if (fprintf(fp, "%s", buf) < 0) {
2267                         g_free(buf);
2268                         g_free(pdata);
2269                         return -1;
2270                 }
2271                 pdata->len = strlen(buf);
2272                 g_free(buf);
2273
2274                 pdata->fp = fp;
2275                 pdata->ascii_only = FALSE;
2276                 pdata->error = FALSE;
2277                 g_hash_table_foreach(mimeinfo->dispositionparameters, write_parameters, pdata);
2278                 if (pdata->error == TRUE) {
2279                         g_free(pdata);
2280                         return -1;
2281                 }
2282                 g_free(pdata);
2283                 TRY(fprintf(fp, "\n") >= 0);
2284         }
2285
2286         TRY(fprintf(fp, "\n") >= 0);
2287         
2288         return 0;
2289 }
2290
2291 static gint procmime_write_message_rfc822(MimeInfo *mimeinfo, FILE *fp)
2292 {
2293         FILE *infp;
2294         GNode *childnode;
2295         MimeInfo *child;
2296         gchar buf[BUFFSIZE];
2297         gboolean skip = FALSE;;
2298         size_t len;
2299
2300         debug_print("procmime_write_message_rfc822\n");
2301
2302         /* write header */
2303         switch (mimeinfo->content) {
2304         case MIMECONTENT_FILE:
2305                 if ((infp = g_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2306                         FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2307                         return -1;
2308                 }
2309                 fseek(infp, mimeinfo->offset, SEEK_SET);
2310                 while (fgets(buf, sizeof(buf), infp) == buf) {
2311                         strcrchomp(buf);
2312                         if (buf[0] == '\n' && buf[1] == '\0')
2313                                 break;
2314                         if (skip && (buf[0] == ' ' || buf[0] == '\t'))
2315                                 continue;
2316                         if (g_ascii_strncasecmp(buf, "Mime-Version:", 13) == 0 ||
2317                             g_ascii_strncasecmp(buf, "Content-Type:", 13) == 0 ||
2318                             g_ascii_strncasecmp(buf, "Content-Transfer-Encoding:", 26) == 0 ||
2319                             g_ascii_strncasecmp(buf, "Content-Description:", 20) == 0 ||
2320                             g_ascii_strncasecmp(buf, "Content-ID:", 11) == 0 ||
2321                             g_ascii_strncasecmp(buf, "Content-Location:", 17) == 0 ||
2322                             g_ascii_strncasecmp(buf, "Content-Disposition:", 20) == 0) {
2323                                 skip = TRUE;
2324                                 continue;
2325                         }
2326                         len = strlen(buf);
2327                         if (fwrite(buf, sizeof(gchar), len, fp) < len) {
2328                                 g_warning("failed to dump %zd bytes from file", len);
2329                                 fclose(infp);
2330                                 return -1;
2331                         }
2332                         skip = FALSE;
2333                 }
2334                 fclose(infp);
2335                 break;
2336
2337         case MIMECONTENT_MEM:
2338                 len = strlen(mimeinfo->data.mem);
2339                 if (fwrite(mimeinfo->data.mem, sizeof(gchar), len, fp) < len) {
2340                         g_warning("failed to dump %zd bytes from mem", len);
2341                         return -1;
2342                 }
2343                 break;
2344
2345         default:
2346                 break;
2347         }
2348
2349         childnode = mimeinfo->node->children;
2350         if (childnode == NULL)
2351                 return -1;
2352
2353         child = (MimeInfo *) childnode->data;
2354         if (fprintf(fp, "Mime-Version: 1.0\n") < 0) {
2355                 g_warning("failed to write mime version");
2356                 return -1;
2357         }
2358         if (procmime_write_mime_header(child, fp) < 0)
2359                 return -1;
2360         return procmime_write_mimeinfo(child, fp);
2361 }
2362
2363 static gint procmime_write_multipart(MimeInfo *mimeinfo, FILE *fp)
2364 {
2365         FILE *infp;
2366         GNode *childnode;
2367         gchar *boundary, *str, *str2;
2368         gchar buf[BUFFSIZE];
2369         gboolean firstboundary;
2370         size_t len;
2371
2372         debug_print("procmime_write_multipart\n");
2373
2374         boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
2375
2376         switch (mimeinfo->content) {
2377         case MIMECONTENT_FILE:
2378                 if ((infp = g_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2379                         FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2380                         return -1;
2381                 }
2382                 fseek(infp, mimeinfo->offset, SEEK_SET);
2383                 while (fgets(buf, sizeof(buf), infp) == buf) {
2384                         if (IS_BOUNDARY(buf, boundary, strlen(boundary)))
2385                                 break;
2386                         len = strlen(buf);
2387                         if (fwrite(buf, sizeof(gchar), len, fp) < len) {
2388                                 g_warning("failed to write %zd", len);
2389                                 fclose(infp);
2390                                 return -1;
2391                         }
2392                 }
2393                 fclose(infp);
2394                 break;
2395
2396         case MIMECONTENT_MEM:
2397                 str = g_strdup(mimeinfo->data.mem);
2398                 if (((str2 = strstr(str, boundary)) != NULL) && ((str2 - str) >= 2) &&
2399                     (*(str2 - 1) == '-') && (*(str2 - 2) == '-'))
2400                         *(str2 - 2) = '\0';
2401                 len = strlen(str);
2402                 if (fwrite(str, sizeof(gchar), len, fp) < len) {
2403                         g_warning("failed to write %zd from mem", len);
2404                         g_free(str);
2405                         return -1;
2406                 }
2407                 g_free(str);
2408                 break;
2409
2410         default:
2411                 break;
2412         }
2413
2414         childnode = mimeinfo->node->children;
2415         firstboundary = TRUE;
2416         while (childnode != NULL) {
2417                 MimeInfo *child = childnode->data;
2418
2419                 if (firstboundary)
2420                         firstboundary = FALSE;
2421                 else
2422                         TRY(fprintf(fp, "\n") >= 0);
2423                         
2424                 TRY(fprintf(fp, "--%s\n", boundary) >= 0);
2425
2426                 if (procmime_write_mime_header(child, fp) < 0)
2427                         return -1;
2428                 if (procmime_write_mimeinfo(child, fp) < 0)
2429                         return -1;
2430
2431                 childnode = g_node_next_sibling(childnode);
2432         }       
2433         TRY(fprintf(fp, "\n--%s--\n", boundary) >= 0);
2434
2435         return 0;
2436 }
2437
2438 gint procmime_write_mimeinfo(MimeInfo *mimeinfo, FILE *fp)
2439 {
2440         FILE *infp;
2441         size_t len;
2442         debug_print("procmime_write_mimeinfo\n");
2443
2444         if (G_NODE_IS_LEAF(mimeinfo->node)) {
2445                 switch (mimeinfo->content) {
2446                 case MIMECONTENT_FILE:
2447                         if ((infp = g_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2448                                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2449                                 return -1;
2450                         }
2451                         copy_file_part_to_fp(infp, mimeinfo->offset, mimeinfo->length, fp);
2452                         fclose(infp);
2453                         return 0;
2454
2455                 case MIMECONTENT_MEM:
2456                         len = strlen(mimeinfo->data.mem);
2457                         if (fwrite(mimeinfo->data.mem, sizeof(gchar), len, fp) < len)
2458                                 return -1;
2459                         return 0;
2460
2461                 default:
2462                         return 0;
2463                 }
2464         } else {
2465                 /* Call writer for mime type */
2466                 switch (mimeinfo->type) {
2467                 case MIMETYPE_MESSAGE:
2468                         if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
2469                                 return procmime_write_message_rfc822(mimeinfo, fp);
2470                         }
2471                         break;
2472                         
2473                 case MIMETYPE_MULTIPART:
2474                         return procmime_write_multipart(mimeinfo, fp);
2475                         
2476                 default:
2477                         break;
2478                 }
2479
2480                 return -1;
2481         }
2482
2483         return 0;
2484 }
2485
2486 gchar *procmime_get_part_file_name(MimeInfo *mimeinfo)
2487 {
2488         gchar *base;
2489
2490         if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
2491                 base = g_strdup("mimetmp.html");
2492         else {
2493                 const gchar *basetmp;
2494                 gchar *basename;
2495
2496                 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
2497                 if (basetmp == NULL)
2498                         basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
2499                 if (basetmp == NULL)
2500                         basetmp = "mimetmp";
2501                 basename = g_path_get_basename(basetmp);
2502                 if (*basename == '\0') {
2503                         g_free(basename);
2504                         basename = g_strdup("mimetmp");
2505                 }
2506                 base = conv_filename_from_utf8(basename);
2507                 g_free(basename);
2508                 subst_for_shellsafe_filename(base);
2509         }
2510         
2511         return base;
2512 }
2513