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