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