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