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