2008-08-28 [colin] 3.5.0cvs78
[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                 if (privacy_mimeinfo_is_signed(partinfo))
845                         procmsg_msginfo_set_flags(msginfo, 0, MSG_SIGNED);
846         }
847
848         if (partinfo)
849                 outfp = procmime_get_text_content(partinfo);
850
851         procmime_mimeinfo_free_all(mimeinfo);
852
853         return outfp;
854 }
855
856 gboolean procmime_msginfo_is_encrypted(MsgInfo *msginfo)
857 {
858         MimeInfo *mimeinfo, *partinfo;
859         gboolean result = FALSE;
860
861         g_return_val_if_fail(msginfo != NULL, FALSE);
862
863         mimeinfo = procmime_scan_message(msginfo);
864         if (!mimeinfo) {
865                 return FALSE;
866         }
867
868         partinfo = mimeinfo;
869         result = (find_encrypted_part(partinfo) != NULL);
870         procmime_mimeinfo_free_all(mimeinfo);
871
872         return result;
873 }
874
875 static gboolean procmime_find_string_part(MimeInfo *mimeinfo, const gchar *filename,
876                                    const gchar *str, StrFindFunc find_func)
877 {
878         FILE *outfp;
879         gchar buf[BUFFSIZE];
880
881         g_return_val_if_fail(mimeinfo != NULL, FALSE);
882         g_return_val_if_fail(mimeinfo->type == MIMETYPE_TEXT, FALSE);
883         g_return_val_if_fail(str != NULL, FALSE);
884         g_return_val_if_fail(find_func != NULL, FALSE);
885
886         outfp = procmime_get_text_content(mimeinfo);
887
888         if (!outfp)
889                 return FALSE;
890
891         while (fgets(buf, sizeof(buf), outfp) != NULL) {
892                 strretchomp(buf);
893                 if (find_func(buf, str)) {
894                         fclose(outfp);
895                         return TRUE;
896                 }
897         }
898
899         fclose(outfp);
900
901         return FALSE;
902 }
903
904 gboolean procmime_find_string(MsgInfo *msginfo, const gchar *str,
905                               StrFindFunc find_func)
906 {
907         MimeInfo *mimeinfo;
908         MimeInfo *partinfo;
909         gchar *filename;
910         gboolean found = FALSE;
911
912         g_return_val_if_fail(msginfo != NULL, FALSE);
913         g_return_val_if_fail(str != NULL, FALSE);
914         g_return_val_if_fail(find_func != NULL, FALSE);
915
916         filename = procmsg_get_message_file(msginfo);
917         if (!filename) return FALSE;
918         mimeinfo = procmime_scan_message(msginfo);
919
920         for (partinfo = mimeinfo; partinfo != NULL;
921              partinfo = procmime_mimeinfo_next(partinfo)) {
922                 if (partinfo->type == MIMETYPE_TEXT) {
923                         if (procmime_find_string_part
924                                 (partinfo, filename, str, find_func) == TRUE) {
925                                 found = TRUE;
926                                 break;
927                         }
928                 }
929         }
930
931         procmime_mimeinfo_free_all(mimeinfo);
932         g_free(filename);
933
934         return found;
935 }
936
937 gchar *procmime_get_tmp_file_name(MimeInfo *mimeinfo)
938 {
939         static guint32 id = 0;
940         gchar *base;
941         gchar *filename;
942         gchar f_prefix[10];
943
944         g_return_val_if_fail(mimeinfo != NULL, NULL);
945
946         g_snprintf(f_prefix, sizeof(f_prefix), "%08x.", id++);
947
948         if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
949                 base = g_strdup("mimetmp.html");
950         else {
951                 const gchar *basetmp;
952
953                 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
954                 if (basetmp == NULL)
955                         basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
956                 if (basetmp == NULL)
957                         basetmp = "mimetmp";
958                 basetmp = g_path_get_basename(basetmp);
959                 if (*basetmp == '\0') 
960                         basetmp = g_strdup("mimetmp");
961                 base = conv_filename_from_utf8(basetmp);
962                 g_free((gchar*)basetmp);
963                 subst_for_shellsafe_filename(base);
964         }
965
966         filename = g_strconcat(get_mime_tmp_dir(), G_DIR_SEPARATOR_S,
967                                f_prefix, base, NULL);
968
969         g_free(base);
970         
971         return filename;
972 }
973
974 static GList *mime_type_list = NULL;
975
976 gchar *procmime_get_mime_type(const gchar *filename)
977 {
978         static GHashTable *mime_type_table = NULL;
979         MimeType *mime_type;
980         const gchar *p;
981         gchar *ext = NULL;
982         gchar *base;
983
984         if (!mime_type_table) {
985                 mime_type_table = procmime_get_mime_type_table();
986                 if (!mime_type_table) return NULL;
987         }
988
989         base = g_path_get_basename(filename);
990         if ((p = strrchr(base, '.')) != NULL)
991                 ext = g_utf8_strdown(p + 1, -1);
992         g_free(base);
993
994         mime_type = g_hash_table_lookup(mime_type_table, ext);
995         g_free(ext);
996         if (mime_type) {
997                 gchar *str;
998
999                 str = g_strconcat(mime_type->type, "/", mime_type->sub_type,
1000                                   NULL);
1001                 return str;
1002         }
1003
1004         return NULL;
1005 }
1006
1007 static guint procmime_str_hash(gconstpointer gptr)
1008 {
1009         guint hash_result = 0;
1010         const char *str;
1011
1012         for (str = gptr; str && *str; str++) {
1013                 if (isupper(*str)) hash_result += (*str + ' ');
1014                 else hash_result += *str;
1015         }
1016
1017         return hash_result;
1018 }
1019
1020 static gint procmime_str_equal(gconstpointer gptr1, gconstpointer gptr2)
1021 {
1022         const char *str1 = gptr1;
1023         const char *str2 = gptr2;
1024
1025         return !g_utf8_collate(str1, str2);
1026 }
1027
1028 static GHashTable *procmime_get_mime_type_table(void)
1029 {
1030         GHashTable *table = NULL;
1031         GList *cur;
1032         MimeType *mime_type;
1033         gchar **exts;
1034
1035         if (!mime_type_list) {
1036                 mime_type_list = procmime_get_mime_type_list();
1037                 if (!mime_type_list) return NULL;
1038         }
1039
1040         table = g_hash_table_new(procmime_str_hash, procmime_str_equal);
1041
1042         for (cur = mime_type_list; cur != NULL; cur = cur->next) {
1043                 gint i;
1044                 gchar *key;
1045
1046                 mime_type = (MimeType *)cur->data;
1047
1048                 if (!mime_type->extension) continue;
1049
1050                 exts = g_strsplit(mime_type->extension, " ", 16);
1051                 for (i = 0; exts[i] != NULL; i++) {
1052                         /* use previously dup'd key on overwriting */
1053                         if (g_hash_table_lookup(table, exts[i]))
1054                                 key = exts[i];
1055                         else
1056                                 key = g_strdup(exts[i]);
1057                         g_hash_table_insert(table, key, mime_type);
1058                 }
1059                 g_strfreev(exts);
1060         }
1061
1062         return table;
1063 }
1064
1065 GList *procmime_get_mime_type_list(void)
1066 {
1067         GList *list = NULL;
1068         FILE *fp;
1069         gchar buf[BUFFSIZE];
1070         gchar *p;
1071         gchar *delim;
1072         MimeType *mime_type;
1073         gboolean fp_is_glob_file = TRUE;
1074
1075         if (mime_type_list) 
1076                 return mime_type_list;
1077         
1078 #if defined(__NetBSD__) || defined(__OpenBSD__) || defined(__FreeBSD__)
1079         if ((fp = g_fopen(DATAROOTDIR "/mime/globs", "rb")) == NULL) 
1080 #else
1081         if ((fp = g_fopen("/usr/share/mime/globs", "rb")) == NULL) 
1082 #endif
1083         {
1084                 fp_is_glob_file = FALSE;
1085                 if ((fp = g_fopen("/etc/mime.types", "rb")) == NULL) {
1086                         if ((fp = g_fopen(SYSCONFDIR "/mime.types", "rb")) 
1087                                 == NULL) {
1088                                 FILE_OP_ERROR(SYSCONFDIR "/mime.types", 
1089                                         "fopen");
1090                                 return NULL;
1091                         }
1092                 }
1093         }
1094
1095         while (fgets(buf, sizeof(buf), fp) != NULL) {
1096                 p = strchr(buf, '#');
1097                 if (p) *p = '\0';
1098                 g_strstrip(buf);
1099
1100                 p = buf;
1101                 
1102                 if (fp_is_glob_file) {
1103                         while (*p && !g_ascii_isspace(*p) && (*p!=':')) p++;
1104                 } else {
1105                         while (*p && !g_ascii_isspace(*p)) p++;
1106                 }
1107
1108                 if (*p) {
1109                         *p = '\0';
1110                         p++;
1111                 }
1112                 delim = strchr(buf, '/');
1113                 if (delim == NULL) continue;
1114                 *delim = '\0';
1115
1116                 mime_type = g_new(MimeType, 1);
1117                 mime_type->type = g_strdup(buf);
1118                 mime_type->sub_type = g_strdup(delim + 1);
1119
1120                 if (fp_is_glob_file) {
1121                         while (*p && (g_ascii_isspace(*p)||(*p=='*')||(*p=='.'))) p++;
1122                 } else {
1123                         while (*p && g_ascii_isspace(*p)) p++;
1124                 }
1125
1126                 if (*p)
1127                         mime_type->extension = g_utf8_strdown(p, -1);
1128                 else
1129                         mime_type->extension = NULL;
1130
1131                 list = g_list_append(list, mime_type);
1132         }
1133
1134         fclose(fp);
1135
1136         if (!list)
1137                 g_warning("Can't read mime.types\n");
1138
1139         return list;
1140 }
1141
1142 EncodingType procmime_get_encoding_for_charset(const gchar *charset)
1143 {
1144         if (!charset)
1145                 return ENC_8BIT;
1146         else if (!g_ascii_strncasecmp(charset, "ISO-2022-", 9) ||
1147                  !g_ascii_strcasecmp(charset, "US-ASCII"))
1148                 return ENC_7BIT;
1149         else if (!g_ascii_strcasecmp(charset, "ISO-8859-5") ||
1150                  !g_ascii_strncasecmp(charset, "KOI8-", 5) ||
1151                  !g_ascii_strcasecmp(charset, "Windows-1251"))
1152                 return ENC_8BIT;
1153         else if (!g_ascii_strncasecmp(charset, "ISO-8859-", 9))
1154                 return ENC_QUOTED_PRINTABLE;
1155         else if (!g_ascii_strncasecmp(charset, "UTF-8", 5))
1156                 return ENC_QUOTED_PRINTABLE;
1157         else 
1158                 return ENC_8BIT;
1159 }
1160
1161 EncodingType procmime_get_encoding_for_text_file(const gchar *file, gboolean *has_binary)
1162 {
1163         FILE *fp;
1164         guchar buf[BUFFSIZE];
1165         size_t len;
1166         size_t octet_chars = 0;
1167         size_t total_len = 0;
1168         gfloat octet_percentage;
1169         gboolean force_b64 = FALSE;
1170
1171         if ((fp = g_fopen(file, "rb")) == NULL) {
1172                 FILE_OP_ERROR(file, "fopen");
1173                 return ENC_UNKNOWN;
1174         }
1175
1176         while ((len = fread(buf, sizeof(guchar), sizeof(buf), fp)) > 0) {
1177                 guchar *p;
1178                 gint i;
1179
1180                 for (p = buf, i = 0; i < len; ++p, ++i) {
1181                         if (*p & 0x80)
1182                                 ++octet_chars;
1183                         if (*p == '\0') {
1184                                 force_b64 = TRUE;
1185                                 *has_binary = TRUE;
1186                         }
1187                 }
1188                 total_len += len;
1189         }
1190
1191         fclose(fp);
1192         
1193         if (total_len > 0)
1194                 octet_percentage = (gfloat)octet_chars / (gfloat)total_len;
1195         else
1196                 octet_percentage = 0.0;
1197
1198         debug_print("procmime_get_encoding_for_text_file(): "
1199                     "8bit chars: %zd / %zd (%f%%)\n", octet_chars, total_len,
1200                     100.0 * octet_percentage);
1201
1202         if (octet_percentage > 0.20 || force_b64) {
1203                 debug_print("using BASE64\n");
1204                 return ENC_BASE64;
1205         } else if (octet_chars > 0) {
1206                 debug_print("using quoted-printable\n");
1207                 return ENC_QUOTED_PRINTABLE;
1208         } else {
1209                 debug_print("using 7bit\n");
1210                 return ENC_7BIT;
1211         }
1212 }
1213
1214 struct EncodingTable 
1215 {
1216         gchar *str;
1217         EncodingType enc_type;
1218 };
1219
1220 struct EncodingTable encoding_table[] = {
1221         {"7bit", ENC_7BIT},
1222         {"8bit", ENC_8BIT},
1223         {"binary", ENC_BINARY},
1224         {"quoted-printable", ENC_QUOTED_PRINTABLE},
1225         {"base64", ENC_BASE64},
1226         {"x-uuencode", ENC_UNKNOWN},
1227         {NULL, ENC_UNKNOWN},
1228 };
1229
1230 const gchar *procmime_get_encoding_str(EncodingType encoding)
1231 {
1232         struct EncodingTable *enc_table;
1233         
1234         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1235                 if (enc_table->enc_type == encoding)
1236                         return enc_table->str;
1237         }
1238         return NULL;
1239 }
1240
1241 /* --- NEW MIME STUFF --- */
1242 struct TypeTable
1243 {
1244         gchar *str;
1245         MimeMediaType type;
1246 };
1247
1248 static struct TypeTable mime_type_table[] = {
1249         {"text", MIMETYPE_TEXT},
1250         {"image", MIMETYPE_IMAGE},
1251         {"audio", MIMETYPE_AUDIO},
1252         {"video", MIMETYPE_VIDEO},
1253         {"application", MIMETYPE_APPLICATION},
1254         {"message", MIMETYPE_MESSAGE},
1255         {"multipart", MIMETYPE_MULTIPART},
1256         {NULL, 0},
1257 };
1258
1259 const gchar *procmime_get_media_type_str(MimeMediaType type)
1260 {
1261         struct TypeTable *type_table;
1262         
1263         for (type_table = mime_type_table; type_table->str != NULL; type_table++) {
1264                 if (type_table->type == type)
1265                         return type_table->str;
1266         }
1267         return NULL;
1268 }
1269
1270 MimeMediaType procmime_get_media_type(const gchar *str)
1271 {
1272         struct TypeTable *typetablearray;
1273
1274         for (typetablearray = mime_type_table; typetablearray->str != NULL; typetablearray++)
1275                 if (g_ascii_strncasecmp(str, typetablearray->str, strlen(typetablearray->str)) == 0)
1276                         return typetablearray->type;
1277
1278         return MIMETYPE_UNKNOWN;
1279 }
1280
1281 /*!
1282  *\brief        Safe wrapper for content type string.
1283  *
1284  *\return       const gchar * Pointer to content type string. 
1285  */
1286 gchar *procmime_get_content_type_str(MimeMediaType type,
1287                                            const char *subtype)
1288 {
1289         const gchar *type_str = NULL;
1290
1291         if (subtype == NULL || !(type_str = procmime_get_media_type_str(type)))
1292                 return g_strdup("unknown");
1293         return g_strdup_printf("%s/%s", type_str, subtype);
1294 }
1295
1296 static int procmime_parse_mimepart(MimeInfo *parent,
1297                              gchar *content_type,
1298                              gchar *content_encoding,
1299                              gchar *content_description,
1300                              gchar *content_id,
1301                              gchar *content_disposition,
1302                              gchar *content_location,
1303                              const gchar *original_msgid,
1304                              const gchar *disposition_notification_hdr,
1305                              const gchar *filename,
1306                              guint offset,
1307                              guint length,
1308                              gboolean short_scan);
1309
1310 static void procmime_parse_message_rfc822(MimeInfo *mimeinfo, gboolean short_scan)
1311 {
1312         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1313                                 {"Content-Transfer-Encoding:",
1314                                                    NULL, FALSE},
1315                                 {"Content-Description:",
1316                                                    NULL, TRUE},
1317                                 {"Content-ID:",
1318                                                    NULL, TRUE},
1319                                 {"Content-Disposition:",
1320                                                    NULL, TRUE},
1321                                 {"Content-Location:",
1322                                                    NULL, TRUE},
1323                                 {"MIME-Version:",
1324                                                    NULL, TRUE},
1325                                 {"Original-Message-ID:",
1326                                                    NULL, TRUE},
1327                                 {"Disposition:",
1328                                                    NULL, TRUE},
1329                                 {NULL,             NULL, FALSE}};
1330         guint content_start, i;
1331         FILE *fp;
1332         gchar *tmp;
1333         gint len = 0;
1334
1335         procmime_decode_content(mimeinfo);
1336
1337         fp = g_fopen(mimeinfo->data.filename, "rb");
1338         if (fp == NULL) {
1339                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1340                 return;
1341         }
1342         fseek(fp, mimeinfo->offset, SEEK_SET);
1343         procheader_get_header_fields(fp, hentry);
1344         if (hentry[0].body != NULL) {
1345                 tmp = conv_unmime_header(hentry[0].body, NULL);
1346                 g_free(hentry[0].body);
1347                 hentry[0].body = tmp;
1348         }                
1349         if (hentry[2].body != NULL) {
1350                 tmp = conv_unmime_header(hentry[2].body, NULL);
1351                 g_free(hentry[2].body);
1352                 hentry[2].body = tmp;
1353         }                
1354         if (hentry[4].body != NULL) {
1355                 tmp = conv_unmime_header(hentry[4].body, NULL);
1356                 g_free(hentry[4].body);
1357                 hentry[4].body = tmp;
1358         }                
1359         if (hentry[5].body != NULL) {
1360                 tmp = conv_unmime_header(hentry[5].body, NULL);
1361                 g_free(hentry[5].body);
1362                 hentry[5].body = tmp;
1363         }                
1364         if (hentry[7].body != NULL) {
1365                 tmp = conv_unmime_header(hentry[7].body, NULL);
1366                 g_free(hentry[7].body);
1367                 hentry[7].body = tmp;
1368         }
1369         if (hentry[8].body != NULL) {
1370                 tmp = conv_unmime_header(hentry[8].body, NULL);
1371                 g_free(hentry[8].body);
1372                 hentry[8].body = tmp;
1373         }
1374   
1375         content_start = ftell(fp);
1376         fclose(fp);
1377         
1378         len = mimeinfo->length - (content_start - mimeinfo->offset);
1379         if (len < 0)
1380                 len = 0;
1381         procmime_parse_mimepart(mimeinfo,
1382                                 hentry[0].body, hentry[1].body,
1383                                 hentry[2].body, hentry[3].body,
1384                                 hentry[4].body, hentry[5].body,
1385                                 hentry[7].body, hentry[8].body, 
1386                                 mimeinfo->data.filename, content_start,
1387                                 len, short_scan);
1388         
1389         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1390                 g_free(hentry[i].body);
1391                 hentry[i].body = NULL;
1392         }
1393 }
1394
1395 static void procmime_parse_disposition_notification(MimeInfo *mimeinfo, 
1396                 const gchar *original_msgid, const gchar *disposition_notification_hdr,
1397                 gboolean short_scan)
1398 {
1399         HeaderEntry hentry[] = {{"Original-Message-ID:",  NULL, TRUE},
1400                                 {"Disposition:",          NULL, TRUE},
1401                                 {NULL,                    NULL, FALSE}};
1402         guint i;
1403         FILE *fp;
1404         gchar *orig_msg_id = NULL;
1405         gchar *disp = NULL;
1406
1407         procmime_decode_content(mimeinfo);
1408
1409         debug_print("parse disposition notification\n");
1410         fp = g_fopen(mimeinfo->data.filename, "rb");
1411         if (fp == NULL) {
1412                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1413                 return;
1414         }
1415         fseek(fp, mimeinfo->offset, SEEK_SET);
1416
1417         if (original_msgid && disposition_notification_hdr) {
1418                 hentry[0].body = g_strdup(original_msgid);
1419                 hentry[1].body = g_strdup(disposition_notification_hdr);
1420         } else {
1421                 procheader_get_header_fields(fp, hentry);
1422         }
1423
1424         if (!hentry[0].body || !hentry[1].body) {
1425                 debug_print("MsgId %s, Disp %s\n",
1426                         hentry[0].body ? hentry[0].body:"(nil)",
1427                         hentry[1].body ? hentry[1].body:"(nil)");
1428                 goto bail;
1429         }
1430
1431         orig_msg_id = g_strdup(hentry[0].body);
1432         disp = g_strdup(hentry[1].body);
1433
1434         extract_parenthesis(orig_msg_id, '<', '>');
1435         remove_space(orig_msg_id);
1436         
1437         if (strstr(disp, "displayed")) {
1438                 /* find sent message, if possible */
1439                 MsgInfo *info = NULL;
1440                 GList *flist;
1441                 debug_print("%s has been displayed.\n", orig_msg_id);
1442                 for (flist = folder_get_list(); flist != NULL; flist = g_list_next(flist)) {
1443                         FolderItem *outbox = ((Folder *)(flist->data))->outbox;
1444                         if (!outbox) {
1445                                 debug_print("skipping folder with no outbox...\n");
1446                                 continue;
1447                         }
1448                         info = folder_item_get_msginfo_by_msgid(outbox, orig_msg_id);
1449                         debug_print("%s %s in %s\n", info?"found":"didn't find", orig_msg_id, outbox->path);
1450                         if (info) {
1451                                 procmsg_msginfo_set_flags(info, MSG_RETRCPT_GOT, 0);
1452                                 procmsg_msginfo_free(info);
1453                         }
1454                 }
1455         }
1456         g_free(orig_msg_id);
1457         g_free(disp);
1458 bail:
1459         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1460                 g_free(hentry[i].body);
1461                 hentry[i].body = NULL;
1462         }
1463 }
1464
1465 #define GET_HEADERS() {                                         \
1466         procheader_get_header_fields(fp, hentry);               \
1467         if (hentry[0].body != NULL) {                           \
1468                 tmp = conv_unmime_header(hentry[0].body, NULL); \
1469                 g_free(hentry[0].body);                         \
1470                 hentry[0].body = tmp;                           \
1471         }                                                       \
1472         if (hentry[2].body != NULL) {                           \
1473                 tmp = conv_unmime_header(hentry[2].body, NULL); \
1474                 g_free(hentry[2].body);                         \
1475                 hentry[2].body = tmp;                           \
1476         }                                                       \
1477         if (hentry[4].body != NULL) {                           \
1478                 tmp = conv_unmime_header(hentry[4].body, NULL); \
1479                 g_free(hentry[4].body);                         \
1480                 hentry[4].body = tmp;                           \
1481         }                                                       \
1482         if (hentry[5].body != NULL) {                           \
1483                 tmp = conv_unmime_header(hentry[5].body, NULL); \
1484                 g_free(hentry[5].body);                         \
1485                 hentry[5].body = tmp;                           \
1486         }                                                       \
1487         if (hentry[6].body != NULL) {                           \
1488                 tmp = conv_unmime_header(hentry[6].body, NULL); \
1489                 g_free(hentry[6].body);                         \
1490                 hentry[6].body = tmp;                           \
1491         }                                                       \
1492         if (hentry[7].body != NULL) {                           \
1493                 tmp = conv_unmime_header(hentry[7].body, NULL); \
1494                 g_free(hentry[7].body);                         \
1495                 hentry[7].body = tmp;                           \
1496         }                                                       \
1497 }
1498
1499 static void procmime_parse_multipart(MimeInfo *mimeinfo, gboolean short_scan)
1500 {
1501         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1502                                 {"Content-Transfer-Encoding:",
1503                                                    NULL, FALSE},
1504                                 {"Content-Description:",
1505                                                    NULL, TRUE},
1506                                 {"Content-ID:",
1507                                                    NULL, TRUE},
1508                                 {"Content-Disposition:",
1509                                                    NULL, TRUE},
1510                                 {"Content-Location:",
1511                                                    NULL, TRUE},
1512                                 {"Original-Message-ID:",
1513                                                    NULL, TRUE},
1514                                 {"Disposition:",
1515                                                    NULL, TRUE},
1516                                 {NULL,             NULL, FALSE}};
1517         gchar *p, *tmp;
1518         gchar *boundary;
1519         gint boundary_len = 0, lastoffset = -1, i;
1520         gchar buf[BUFFSIZE];
1521         FILE *fp;
1522         int result = 0;
1523         gboolean done = FALSE;
1524
1525         boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
1526         if (!boundary)
1527                 return;
1528         boundary_len = strlen(boundary);
1529
1530         procmime_decode_content(mimeinfo);
1531
1532         fp = g_fopen(mimeinfo->data.filename, "rb");
1533         if (fp == NULL) {
1534                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1535                 return;
1536         }
1537         fseek(fp, mimeinfo->offset, SEEK_SET);
1538         while ((p = fgets(buf, sizeof(buf), fp)) != NULL && result == 0) {
1539                 if (ftell(fp) - 1 > (mimeinfo->offset + mimeinfo->length))
1540                         break;
1541
1542                 if (IS_BOUNDARY(buf, boundary, boundary_len)) {
1543                         if (lastoffset != -1) {
1544                                 gint len = (ftell(fp) - strlen(buf)) - lastoffset - 1;
1545                                 if (len < 0)
1546                                         len = 0;
1547                                 result = procmime_parse_mimepart(mimeinfo,
1548                                                         hentry[0].body, hentry[1].body,
1549                                                         hentry[2].body, hentry[3].body, 
1550                                                         hentry[4].body, hentry[5].body,
1551                                                         hentry[6].body, hentry[7].body,
1552                                                         mimeinfo->data.filename, lastoffset,
1553                                                         len, short_scan);
1554                                 if (result == 1 && short_scan) {
1555                                         done = TRUE;
1556                                         break;
1557                                 }
1558                         } 
1559                         
1560                         if (buf[2 + boundary_len]     == '-' &&
1561                             buf[2 + boundary_len + 1] == '-') {
1562                                 break;
1563                         }
1564                         for (i = 0; i < (sizeof hentry / sizeof hentry[0]) ; i++) {
1565                                 g_free(hentry[i].body);
1566                                 hentry[i].body = NULL;
1567                         }
1568                         GET_HEADERS();
1569                         lastoffset = ftell(fp);
1570                 }
1571         }
1572         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1573                 g_free(hentry[i].body);
1574                 hentry[i].body = NULL;
1575         }
1576         fclose(fp);
1577 }
1578
1579 static void parse_parameters(const gchar *parameters, GHashTable *table)
1580 {
1581         gchar *params, *param, *next;
1582         GSList *convlist = NULL, *concatlist = NULL, *cur;
1583
1584         params = g_strdup(parameters);
1585         param = params;
1586         next = params;
1587         for (; next != NULL; param = next) {
1588                 gchar *attribute, *value, *tmp, *down_attr;
1589                 gint len;
1590                 gboolean convert = FALSE;
1591
1592                 next = strchr_with_skip_quote(param, '"', ';');
1593                 if (next != NULL) {
1594                         next[0] = '\0';
1595                         next++;
1596                 }
1597
1598                 g_strstrip(param);
1599
1600                 attribute = param;
1601                 value = strchr(attribute, '=');
1602                 if (value == NULL)
1603                         continue;
1604
1605                 value[0] = '\0';
1606                 value++;
1607                 while (value[0] == ' ')
1608                         value++;
1609
1610                 down_attr = g_utf8_strdown(attribute, -1);
1611                 
1612                 len = strlen(down_attr);
1613                 if (down_attr[len - 1] == '*') {
1614                         gchar *srcpos, *dstpos, *endpos;
1615
1616                         convert = TRUE;
1617                         down_attr[len - 1] = '\0';
1618
1619                         srcpos = value;
1620                         dstpos = value;
1621                         endpos = value + strlen(value);
1622                         while (srcpos < endpos) {
1623                                 if (*srcpos != '%')
1624                                         *dstpos = *srcpos;
1625                                 else {
1626                                         guchar dstvalue;
1627
1628                                         if (!get_hex_value(&dstvalue, srcpos[1], srcpos[2]))
1629                                                 *dstpos = '?';
1630                                         else
1631                                                 *dstpos = dstvalue;
1632                                         srcpos += 2;
1633                                 }
1634                                 srcpos++;
1635                                 dstpos++;
1636                         }
1637                         *dstpos = '\0';
1638                 } else {
1639                         if (value[0] == '"')
1640                                 extract_quote(value, '"');
1641                         else if ((tmp = strchr(value, ' ')) != NULL)
1642                                 *tmp = '\0';
1643                 }
1644
1645                 if (down_attr) {
1646                         while (down_attr[0] == ' ')
1647                                 down_attr++;
1648                         while (down_attr[strlen(down_attr)-1] == ' ') 
1649                                 down_attr[strlen(down_attr)-1] = '\0';
1650                 } 
1651                 if (value) {
1652                         while (value[0] == ' ')
1653                                 value++;
1654                         while (value[strlen(value)-1] == ' ') 
1655                                 value[strlen(value)-1] = '\0';
1656                 }               
1657                 if (strrchr(down_attr, '*') != NULL) {
1658                         gchar *tmpattr;
1659
1660                         tmpattr = g_strdup(down_attr);
1661                         tmp = strrchr(tmpattr, '*');
1662                         tmp[0] = '\0';
1663
1664                         if ((tmp[1] == '0') && (tmp[2] == '\0') && 
1665                             (g_slist_find_custom(concatlist, down_attr, g_str_equal) == NULL))
1666                                 concatlist = g_slist_prepend(concatlist, g_strdup(tmpattr));
1667
1668                         if (convert && (g_slist_find_custom(convlist, down_attr, g_str_equal) == NULL))
1669                                 convlist = g_slist_prepend(convlist, g_strdup(tmpattr));
1670
1671                         g_free(tmpattr);
1672                 } else if (convert) {
1673                         if (g_slist_find_custom(convlist, down_attr, g_str_equal) == NULL)
1674                                 convlist = g_slist_prepend(convlist, g_strdup(down_attr));
1675                 }
1676
1677                 if (g_hash_table_lookup(table, down_attr) == NULL)
1678                         g_hash_table_insert(table, g_strdup(down_attr), g_strdup(value));
1679                 g_free(down_attr);
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