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