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