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