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