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