Python plugin: Example: Make recursive-mark-as-read also work on mailbox
[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                         /* use previously dup'd key on overwriting */
1154                         if (g_hash_table_lookup(table, exts[i]))
1155                                 key = exts[i];
1156                         else
1157                                 key = g_strdup(exts[i]);
1158                         g_hash_table_insert(table, key, mime_type);
1159                 }
1160                 g_strfreev(exts);
1161         }
1162
1163         return table;
1164 }
1165
1166 GList *procmime_get_mime_type_list(void)
1167 {
1168         GList *list = NULL;
1169         FILE *fp;
1170         gchar buf[BUFFSIZE];
1171         gchar *p;
1172         gchar *delim;
1173         MimeType *mime_type;
1174         gboolean fp_is_glob_file = TRUE;
1175
1176         if (mime_type_list) 
1177                 return mime_type_list;
1178         
1179 #if defined(__NetBSD__) || defined(__OpenBSD__) || defined(__FreeBSD__)
1180         if ((fp = procmime_fopen(DATAROOTDIR "/mime/globs", "rb")) == NULL) 
1181 #else
1182         if ((fp = procmime_fopen("/usr/share/mime/globs", "rb")) == NULL) 
1183 #endif
1184         {
1185                 fp_is_glob_file = FALSE;
1186                 if ((fp = procmime_fopen("/etc/mime.types", "rb")) == NULL) {
1187                         if ((fp = procmime_fopen(SYSCONFDIR "/mime.types", "rb")) 
1188                                 == NULL) {
1189                                 FILE_OP_ERROR(SYSCONFDIR "/mime.types", 
1190                                         "fopen");
1191                                 return NULL;
1192                         }
1193                 }
1194         }
1195
1196         while (SC_FGETS(buf, sizeof(buf), fp) != NULL) {
1197                 p = strchr(buf, '#');
1198                 if (p) *p = '\0';
1199                 g_strstrip(buf);
1200
1201                 p = buf;
1202                 
1203                 if (fp_is_glob_file) {
1204                         while (*p && !g_ascii_isspace(*p) && (*p!=':')) p++;
1205                 } else {
1206                         while (*p && !g_ascii_isspace(*p)) p++;
1207                 }
1208
1209                 if (*p) {
1210                         *p = '\0';
1211                         p++;
1212                 }
1213                 delim = strchr(buf, '/');
1214                 if (delim == NULL) continue;
1215                 *delim = '\0';
1216
1217                 mime_type = g_new(MimeType, 1);
1218                 mime_type->type = g_strdup(buf);
1219                 mime_type->sub_type = g_strdup(delim + 1);
1220
1221                 if (fp_is_glob_file) {
1222                         while (*p && (g_ascii_isspace(*p)||(*p=='*')||(*p=='.'))) p++;
1223                 } else {
1224                         while (*p && g_ascii_isspace(*p)) p++;
1225                 }
1226
1227                 if (*p)
1228                         mime_type->extension = g_utf8_strdown(p, -1);
1229                 else
1230                         mime_type->extension = NULL;
1231
1232                 list = g_list_append(list, mime_type);
1233         }
1234
1235         procmime_fclose(fp);
1236
1237         if (!list)
1238                 g_warning("Can't read mime.types\n");
1239
1240         return list;
1241 }
1242
1243 EncodingType procmime_get_encoding_for_charset(const gchar *charset)
1244 {
1245         if (!charset)
1246                 return ENC_8BIT;
1247         else if (!g_ascii_strncasecmp(charset, "ISO-2022-", 9) ||
1248                  !g_ascii_strcasecmp(charset, "US-ASCII"))
1249                 return ENC_7BIT;
1250         else if (!g_ascii_strcasecmp(charset, "ISO-8859-5") ||
1251                  !g_ascii_strncasecmp(charset, "KOI8-", 5) ||
1252                  !g_ascii_strcasecmp(charset, "Windows-1251"))
1253                 return ENC_8BIT;
1254         else if (!g_ascii_strncasecmp(charset, "ISO-8859-", 9))
1255                 return ENC_QUOTED_PRINTABLE;
1256         else if (!g_ascii_strncasecmp(charset, "UTF-8", 5))
1257                 return ENC_QUOTED_PRINTABLE;
1258         else 
1259                 return ENC_8BIT;
1260 }
1261
1262 EncodingType procmime_get_encoding_for_text_file(const gchar *file, gboolean *has_binary)
1263 {
1264         FILE *fp;
1265         guchar buf[BUFFSIZE];
1266         size_t len;
1267         size_t octet_chars = 0;
1268         size_t total_len = 0;
1269         gfloat octet_percentage;
1270         gboolean force_b64 = FALSE;
1271
1272         if ((fp = procmime_fopen(file, "rb")) == NULL) {
1273                 FILE_OP_ERROR(file, "fopen");
1274                 return ENC_UNKNOWN;
1275         }
1276
1277         while ((len = SC_FREAD(buf, sizeof(guchar), sizeof(buf), fp)) > 0) {
1278                 guchar *p;
1279                 gint i;
1280
1281                 for (p = buf, i = 0; i < len; ++p, ++i) {
1282                         if (*p & 0x80)
1283                                 ++octet_chars;
1284                         if (*p == '\0') {
1285                                 force_b64 = TRUE;
1286                                 *has_binary = TRUE;
1287                         }
1288                 }
1289                 total_len += len;
1290         }
1291
1292         procmime_fclose(fp);
1293         
1294         if (total_len > 0)
1295                 octet_percentage = (gfloat)octet_chars / (gfloat)total_len;
1296         else
1297                 octet_percentage = 0.0;
1298
1299         debug_print("procmime_get_encoding_for_text_file(): "
1300                     "8bit chars: %zd / %zd (%f%%)\n", octet_chars, total_len,
1301                     100.0 * octet_percentage);
1302
1303         if (octet_percentage > 0.20 || force_b64) {
1304                 debug_print("using BASE64\n");
1305                 return ENC_BASE64;
1306         } else if (octet_chars > 0) {
1307                 debug_print("using quoted-printable\n");
1308                 return ENC_QUOTED_PRINTABLE;
1309         } else {
1310                 debug_print("using 7bit\n");
1311                 return ENC_7BIT;
1312         }
1313 }
1314
1315 struct EncodingTable 
1316 {
1317         gchar *str;
1318         EncodingType enc_type;
1319 };
1320
1321 struct EncodingTable encoding_table[] = {
1322         {"7bit", ENC_7BIT},
1323         {"8bit", ENC_8BIT},
1324         {"binary", ENC_BINARY},
1325         {"quoted-printable", ENC_QUOTED_PRINTABLE},
1326         {"base64", ENC_BASE64},
1327         {"x-uuencode", ENC_UNKNOWN},
1328         {NULL, ENC_UNKNOWN},
1329 };
1330
1331 const gchar *procmime_get_encoding_str(EncodingType encoding)
1332 {
1333         struct EncodingTable *enc_table;
1334         
1335         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1336                 if (enc_table->enc_type == encoding)
1337                         return enc_table->str;
1338         }
1339         return NULL;
1340 }
1341
1342 /* --- NEW MIME STUFF --- */
1343 struct TypeTable
1344 {
1345         gchar *str;
1346         MimeMediaType type;
1347 };
1348
1349 static struct TypeTable mime_type_table[] = {
1350         {"text", MIMETYPE_TEXT},
1351         {"image", MIMETYPE_IMAGE},
1352         {"audio", MIMETYPE_AUDIO},
1353         {"video", MIMETYPE_VIDEO},
1354         {"application", MIMETYPE_APPLICATION},
1355         {"message", MIMETYPE_MESSAGE},
1356         {"multipart", MIMETYPE_MULTIPART},
1357         {NULL, 0},
1358 };
1359
1360 const gchar *procmime_get_media_type_str(MimeMediaType type)
1361 {
1362         struct TypeTable *type_table;
1363         
1364         for (type_table = mime_type_table; type_table->str != NULL; type_table++) {
1365                 if (type_table->type == type)
1366                         return type_table->str;
1367         }
1368         return NULL;
1369 }
1370
1371 MimeMediaType procmime_get_media_type(const gchar *str)
1372 {
1373         struct TypeTable *typetablearray;
1374
1375         for (typetablearray = mime_type_table; typetablearray->str != NULL; typetablearray++)
1376                 if (g_ascii_strncasecmp(str, typetablearray->str, strlen(typetablearray->str)) == 0)
1377                         return typetablearray->type;
1378
1379         return MIMETYPE_UNKNOWN;
1380 }
1381
1382 /*!
1383  *\brief        Safe wrapper for content type string.
1384  *
1385  *\return       const gchar * Pointer to content type string. 
1386  */
1387 gchar *procmime_get_content_type_str(MimeMediaType type,
1388                                            const char *subtype)
1389 {
1390         const gchar *type_str = NULL;
1391
1392         if (subtype == NULL || !(type_str = procmime_get_media_type_str(type)))
1393                 return g_strdup("unknown");
1394         return g_strdup_printf("%s/%s", type_str, subtype);
1395 }
1396
1397 static int procmime_parse_mimepart(MimeInfo *parent,
1398                              gchar *content_type,
1399                              gchar *content_encoding,
1400                              gchar *content_description,
1401                              gchar *content_id,
1402                              gchar *content_disposition,
1403                              gchar *content_location,
1404                              const gchar *original_msgid,
1405                              const gchar *disposition_notification_hdr,
1406                              const gchar *filename,
1407                              guint offset,
1408                              guint length,
1409                              gboolean short_scan);
1410
1411 static void procmime_parse_message_rfc822(MimeInfo *mimeinfo, gboolean short_scan)
1412 {
1413         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1414                                 {"Content-Transfer-Encoding:",
1415                                                    NULL, FALSE},
1416                                 {"Content-Description:",
1417                                                    NULL, TRUE},
1418                                 {"Content-ID:",
1419                                                    NULL, TRUE},
1420                                 {"Content-Disposition:",
1421                                                    NULL, TRUE},
1422                                 {"Content-Location:",
1423                                                    NULL, TRUE},
1424                                 {"MIME-Version:",
1425                                                    NULL, TRUE},
1426                                 {"Original-Message-ID:",
1427                                                    NULL, TRUE},
1428                                 {"Disposition:",
1429                                                    NULL, TRUE},
1430                                 {NULL,             NULL, FALSE}};
1431         guint content_start, i;
1432         FILE *fp;
1433         gchar *tmp;
1434         gint len = 0;
1435
1436         procmime_decode_content(mimeinfo);
1437
1438         fp = procmime_fopen(mimeinfo->data.filename, "rb");
1439         if (fp == NULL) {
1440                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1441                 return;
1442         }
1443         fseek(fp, mimeinfo->offset, SEEK_SET);
1444         procheader_get_header_fields(fp, hentry);
1445         if (hentry[0].body != NULL) {
1446                 tmp = conv_unmime_header(hentry[0].body, NULL, FALSE);
1447                 g_free(hentry[0].body);
1448                 hentry[0].body = tmp;
1449         }                
1450         if (hentry[2].body != NULL) {
1451                 tmp = conv_unmime_header(hentry[2].body, NULL, FALSE);
1452                 g_free(hentry[2].body);
1453                 hentry[2].body = tmp;
1454         }                
1455         if (hentry[4].body != NULL) {
1456                 tmp = conv_unmime_header(hentry[4].body, NULL, FALSE);
1457                 g_free(hentry[4].body);
1458                 hentry[4].body = tmp;
1459         }                
1460         if (hentry[5].body != NULL) {
1461                 tmp = conv_unmime_header(hentry[5].body, NULL, FALSE);
1462                 g_free(hentry[5].body);
1463                 hentry[5].body = tmp;
1464         }                
1465         if (hentry[7].body != NULL) {
1466                 tmp = conv_unmime_header(hentry[7].body, NULL, FALSE);
1467                 g_free(hentry[7].body);
1468                 hentry[7].body = tmp;
1469         }
1470         if (hentry[8].body != NULL) {
1471                 tmp = conv_unmime_header(hentry[8].body, NULL, FALSE);
1472                 g_free(hentry[8].body);
1473                 hentry[8].body = tmp;
1474         }
1475   
1476         content_start = ftell(fp);
1477         procmime_fclose(fp);
1478         
1479         len = mimeinfo->length - (content_start - mimeinfo->offset);
1480         if (len < 0)
1481                 len = 0;
1482         procmime_parse_mimepart(mimeinfo,
1483                                 hentry[0].body, hentry[1].body,
1484                                 hentry[2].body, hentry[3].body,
1485                                 hentry[4].body, hentry[5].body,
1486                                 hentry[7].body, hentry[8].body, 
1487                                 mimeinfo->data.filename, content_start,
1488                                 len, short_scan);
1489         
1490         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1491                 g_free(hentry[i].body);
1492                 hentry[i].body = NULL;
1493         }
1494 }
1495
1496 static void procmime_parse_disposition_notification(MimeInfo *mimeinfo, 
1497                 const gchar *original_msgid, const gchar *disposition_notification_hdr,
1498                 gboolean short_scan)
1499 {
1500         HeaderEntry hentry[] = {{"Original-Message-ID:",  NULL, TRUE},
1501                                 {"Disposition:",          NULL, TRUE},
1502                                 {NULL,                    NULL, FALSE}};
1503         guint i;
1504         FILE *fp;
1505         gchar *orig_msg_id = NULL;
1506         gchar *disp = NULL;
1507
1508         procmime_decode_content(mimeinfo);
1509
1510         debug_print("parse disposition notification\n");
1511         fp = procmime_fopen(mimeinfo->data.filename, "rb");
1512         if (fp == NULL) {
1513                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1514                 return;
1515         }
1516         fseek(fp, mimeinfo->offset, SEEK_SET);
1517
1518         if (original_msgid && disposition_notification_hdr) {
1519                 hentry[0].body = g_strdup(original_msgid);
1520                 hentry[1].body = g_strdup(disposition_notification_hdr);
1521         } else {
1522                 procheader_get_header_fields(fp, hentry);
1523         }
1524     
1525         procmime_fclose(fp);
1526
1527         if (!hentry[0].body || !hentry[1].body) {
1528                 debug_print("MsgId %s, Disp %s\n",
1529                         hentry[0].body ? hentry[0].body:"(nil)",
1530                         hentry[1].body ? hentry[1].body:"(nil)");
1531                 goto bail;
1532         }
1533
1534         orig_msg_id = g_strdup(hentry[0].body);
1535         disp = g_strdup(hentry[1].body);
1536
1537         extract_parenthesis(orig_msg_id, '<', '>');
1538         remove_space(orig_msg_id);
1539         
1540         if (strstr(disp, "displayed")) {
1541                 /* find sent message, if possible */
1542                 MsgInfo *info = NULL;
1543                 GList *flist;
1544                 debug_print("%s has been displayed.\n", orig_msg_id);
1545                 for (flist = folder_get_list(); flist != NULL; flist = g_list_next(flist)) {
1546                         FolderItem *outbox = ((Folder *)(flist->data))->outbox;
1547                         if (!outbox) {
1548                                 debug_print("skipping folder with no outbox...\n");
1549                                 continue;
1550                         }
1551                         info = folder_item_get_msginfo_by_msgid(outbox, orig_msg_id);
1552                         debug_print("%s %s in %s\n", info?"found":"didn't find", orig_msg_id, outbox->path);
1553                         if (info) {
1554                                 procmsg_msginfo_set_flags(info, MSG_RETRCPT_GOT, 0);
1555                                 procmsg_msginfo_free(info);
1556                         }
1557                 }
1558         }
1559         g_free(orig_msg_id);
1560         g_free(disp);
1561 bail:
1562         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1563                 g_free(hentry[i].body);
1564                 hentry[i].body = NULL;
1565         }
1566 }
1567
1568 #define GET_HEADERS() {                                         \
1569         procheader_get_header_fields(fp, hentry);               \
1570         if (hentry[0].body != NULL) {                           \
1571                 tmp = conv_unmime_header(hentry[0].body, NULL, FALSE);  \
1572                 g_free(hentry[0].body);                         \
1573                 hentry[0].body = tmp;                           \
1574         }                                                       \
1575         if (hentry[2].body != NULL) {                           \
1576                 tmp = conv_unmime_header(hentry[2].body, NULL, FALSE);  \
1577                 g_free(hentry[2].body);                         \
1578                 hentry[2].body = tmp;                           \
1579         }                                                       \
1580         if (hentry[4].body != NULL) {                           \
1581                 tmp = conv_unmime_header(hentry[4].body, NULL, FALSE);  \
1582                 g_free(hentry[4].body);                         \
1583                 hentry[4].body = tmp;                           \
1584         }                                                       \
1585         if (hentry[5].body != NULL) {                           \
1586                 tmp = conv_unmime_header(hentry[5].body, NULL, FALSE);  \
1587                 g_free(hentry[5].body);                         \
1588                 hentry[5].body = tmp;                           \
1589         }                                                       \
1590         if (hentry[6].body != NULL) {                           \
1591                 tmp = conv_unmime_header(hentry[6].body, NULL, FALSE);  \
1592                 g_free(hentry[6].body);                         \
1593                 hentry[6].body = tmp;                           \
1594         }                                                       \
1595         if (hentry[7].body != NULL) {                           \
1596                 tmp = conv_unmime_header(hentry[7].body, NULL, FALSE);  \
1597                 g_free(hentry[7].body);                         \
1598                 hentry[7].body = tmp;                           \
1599         }                                                       \
1600 }
1601
1602 static void procmime_parse_multipart(MimeInfo *mimeinfo, gboolean short_scan)
1603 {
1604         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1605                                 {"Content-Transfer-Encoding:",
1606                                                    NULL, FALSE},
1607                                 {"Content-Description:",
1608                                                    NULL, TRUE},
1609                                 {"Content-ID:",
1610                                                    NULL, TRUE},
1611                                 {"Content-Disposition:",
1612                                                    NULL, TRUE},
1613                                 {"Content-Location:",
1614                                                    NULL, TRUE},
1615                                 {"Original-Message-ID:",
1616                                                    NULL, TRUE},
1617                                 {"Disposition:",
1618                                                    NULL, TRUE},
1619                                 {NULL,             NULL, FALSE}};
1620         gchar *p, *tmp;
1621         gchar *boundary;
1622         gint boundary_len = 0, lastoffset = -1, i;
1623         gchar buf[BUFFSIZE];
1624         FILE *fp;
1625         int result = 0;
1626         gboolean start_found = FALSE;
1627         gboolean end_found = FALSE;
1628
1629         boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
1630         if (!boundary)
1631                 return;
1632         boundary_len = strlen(boundary);
1633
1634         procmime_decode_content(mimeinfo);
1635
1636         fp = procmime_fopen(mimeinfo->data.filename, "rb");
1637         if (fp == NULL) {
1638                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1639                 return;
1640         }
1641
1642         fseek(fp, mimeinfo->offset, SEEK_SET);
1643         while ((p = SC_FGETS(buf, sizeof(buf), fp)) != NULL && result == 0) {
1644                 if (ftell(fp) - 1 > (mimeinfo->offset + mimeinfo->length))
1645                         break;
1646
1647                 if (IS_BOUNDARY(buf, boundary, boundary_len)) {
1648                         start_found = TRUE;
1649
1650                         if (lastoffset != -1) {
1651                                 gint len = (ftell(fp) - strlen(buf)) - lastoffset - 1;
1652                                 if (len < 0)
1653                                         len = 0;
1654                                 result = procmime_parse_mimepart(mimeinfo,
1655                                                         hentry[0].body, hentry[1].body,
1656                                                         hentry[2].body, hentry[3].body, 
1657                                                         hentry[4].body, hentry[5].body,
1658                                                         hentry[6].body, hentry[7].body,
1659                                                         mimeinfo->data.filename, lastoffset,
1660                                                         len, short_scan);
1661                                 if (result == 1 && short_scan)
1662                                         break;
1663                                 
1664                         } 
1665                         
1666                         if (buf[2 + boundary_len]     == '-' &&
1667                             buf[2 + boundary_len + 1] == '-') {
1668                                 end_found = TRUE;
1669                                 break;
1670                         }
1671                         for (i = 0; i < (sizeof hentry / sizeof hentry[0]) ; i++) {
1672                                 g_free(hentry[i].body);
1673                                 hentry[i].body = NULL;
1674                         }
1675                         GET_HEADERS();
1676                         lastoffset = ftell(fp);
1677                 }
1678         }
1679         
1680         if (start_found && !end_found && lastoffset != -1) {
1681                 gint len = (ftell(fp) - strlen(buf)) - lastoffset - 1;
1682
1683                 if (len >= 0) {
1684                         result = procmime_parse_mimepart(mimeinfo,
1685                                         hentry[0].body, hentry[1].body,
1686                                         hentry[2].body, hentry[3].body, 
1687                                         hentry[4].body, hentry[5].body,
1688                                         hentry[6].body, hentry[7].body,
1689                                         mimeinfo->data.filename, lastoffset,
1690                                         len, short_scan);
1691                 }
1692                 mimeinfo->broken = TRUE;
1693         }
1694         
1695         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1696                 g_free(hentry[i].body);
1697                 hentry[i].body = NULL;
1698         }
1699         procmime_fclose(fp);
1700 }
1701
1702 static void parse_parameters(const gchar *parameters, GHashTable *table)
1703 {
1704         gchar *params, *param, *next;
1705         GSList *convlist = NULL, *concatlist = NULL, *cur;
1706
1707         params = g_strdup(parameters);
1708         param = params;
1709         next = params;
1710         for (; next != NULL; param = next) {
1711                 gchar *attribute, *value, *tmp, *down_attr, *orig_down_attr;
1712                 gint len;
1713                 gboolean convert = FALSE;
1714
1715                 next = strchr_with_skip_quote(param, '"', ';');
1716                 if (next != NULL) {
1717                         next[0] = '\0';
1718                         next++;
1719                 }
1720
1721                 g_strstrip(param);
1722
1723                 attribute = param;
1724                 value = strchr(attribute, '=');
1725                 if (value == NULL)
1726                         continue;
1727
1728                 value[0] = '\0';
1729                 value++;
1730                 while (value[0] == ' ')
1731                         value++;
1732
1733                 down_attr = g_utf8_strdown(attribute, -1);
1734                 orig_down_attr = down_attr;
1735         
1736                 len = down_attr ? strlen(down_attr):0;
1737                 if (len > 0 && down_attr[len - 1] == '*') {
1738                         gchar *srcpos, *dstpos, *endpos;
1739
1740                         convert = TRUE;
1741                         down_attr[len - 1] = '\0';
1742
1743                         srcpos = value;
1744                         dstpos = value;
1745                         endpos = value + strlen(value);
1746                         while (srcpos < endpos) {
1747                                 if (*srcpos != '%')
1748                                         *dstpos = *srcpos;
1749                                 else {
1750                                         guchar dstvalue;
1751
1752                                         if (!get_hex_value(&dstvalue, srcpos[1], srcpos[2]))
1753                                                 *dstpos = '?';
1754                                         else
1755                                                 *dstpos = dstvalue;
1756                                         srcpos += 2;
1757                                 }
1758                                 srcpos++;
1759                                 dstpos++;
1760                         }
1761                         *dstpos = '\0';
1762                         if (value[0] == '"')
1763                                 extract_quote(value, '"');
1764                 } else {
1765                         if (value[0] == '"')
1766                                 extract_quote(value, '"');
1767                         else if ((tmp = strchr(value, ' ')) != NULL)
1768                                 *tmp = '\0';
1769                 }
1770
1771                 if (down_attr) {
1772                         while (down_attr[0] == ' ')
1773                                 down_attr++;
1774                         while (down_attr[strlen(down_attr)-1] == ' ') 
1775                                 down_attr[strlen(down_attr)-1] = '\0';
1776                 } 
1777                 if (value) {
1778                         while (value[0] == ' ')
1779                                 value++;
1780                         while (value[strlen(value)-1] == ' ') 
1781                                 value[strlen(value)-1] = '\0';
1782                 }               
1783                 if (down_attr && strrchr(down_attr, '*') != NULL) {
1784                         gchar *tmpattr;
1785
1786                         tmpattr = g_strdup(down_attr);
1787                         tmp = strrchr(tmpattr, '*');
1788                         tmp[0] = '\0';
1789
1790                         if ((tmp[1] == '0') && (tmp[2] == '\0') && 
1791                             (g_slist_find_custom(concatlist, down_attr, (GCompareFunc)g_strcmp0) == NULL))
1792                                 concatlist = g_slist_prepend(concatlist, g_strdup(tmpattr));
1793
1794                         if (convert && (g_slist_find_custom(convlist, tmpattr, (GCompareFunc)g_strcmp0) == NULL))
1795                                 convlist = g_slist_prepend(convlist, g_strdup(tmpattr));
1796
1797                         g_free(tmpattr);
1798                 } else if (convert) {
1799                         if (g_slist_find_custom(convlist, down_attr, (GCompareFunc)g_strcmp0) == NULL)
1800                                 convlist = g_slist_prepend(convlist, g_strdup(down_attr));
1801                 }
1802
1803                 if (g_hash_table_lookup(table, down_attr) == NULL)
1804                         g_hash_table_insert(table, g_strdup(down_attr), g_strdup(value));
1805                 g_free(orig_down_attr);
1806         }
1807
1808         for (cur = concatlist; cur != NULL; cur = g_slist_next(cur)) {
1809                 gchar *attribute, *attrwnum, *partvalue;
1810                 gint n = 0;
1811                 GString *value;
1812
1813                 attribute = (gchar *) cur->data;
1814                 value = g_string_sized_new(64);
1815
1816                 attrwnum = g_strdup_printf("%s*%d", attribute, n);
1817                 while ((partvalue = g_hash_table_lookup(table, attrwnum)) != NULL) {
1818                         g_string_append(value, partvalue);
1819
1820                         g_hash_table_remove(table, attrwnum);
1821                         g_free(attrwnum);
1822                         n++;
1823                         attrwnum = g_strdup_printf("%s*%d", attribute, n);
1824                 }
1825                 g_free(attrwnum);
1826
1827                 g_hash_table_insert(table, g_strdup(attribute), g_strdup(value->str));
1828                 g_string_free(value, TRUE);
1829         }
1830         slist_free_strings_full(concatlist);
1831
1832         for (cur = convlist; cur != NULL; cur = g_slist_next(cur)) {
1833                 gchar *attribute, *key, *value;
1834                 gchar *charset, *lang, *oldvalue, *newvalue;
1835
1836                 attribute = (gchar *) cur->data;
1837                 if (!g_hash_table_lookup_extended(
1838                         table, attribute, (gpointer *)(gchar *) &key, (gpointer *)(gchar *) &value))
1839                         continue;
1840
1841                 charset = value;
1842                 if (charset == NULL)
1843                         continue;
1844                 lang = strchr(charset, '\'');
1845                 if (lang == NULL)
1846                         continue;
1847                 lang[0] = '\0';
1848                 lang++;
1849                 oldvalue = strchr(lang, '\'');
1850                 if (oldvalue == NULL)
1851                         continue;
1852                 oldvalue[0] = '\0';
1853                 oldvalue++;
1854
1855                 newvalue = conv_codeset_strdup(oldvalue, charset, CS_UTF_8);
1856
1857                 g_hash_table_remove(table, attribute);
1858                 g_free(key);
1859                 g_free(value);
1860
1861                 g_hash_table_insert(table, g_strdup(attribute), newvalue);
1862         }
1863         slist_free_strings_full(convlist);
1864
1865         g_free(params);
1866 }       
1867
1868 static void procmime_parse_content_type(const gchar *content_type, MimeInfo *mimeinfo)
1869 {
1870         cm_return_if_fail(content_type != NULL);
1871         cm_return_if_fail(mimeinfo != NULL);
1872
1873         /* RFC 2045, page 13 says that the mime subtype is MANDATORY;
1874          * if it's not available we use the default Content-Type */
1875         if ((content_type[0] == '\0') || (strchr(content_type, '/') == NULL)) {
1876                 mimeinfo->type = MIMETYPE_TEXT;
1877                 mimeinfo->subtype = g_strdup("plain");
1878                 if (g_hash_table_lookup(mimeinfo->typeparameters,
1879                                        "charset") == NULL) {
1880                         g_hash_table_insert(mimeinfo->typeparameters,
1881                                     g_strdup("charset"),
1882                                     g_strdup(
1883                                         conv_get_locale_charset_str_no_utf8()));
1884                 }
1885         } else {
1886                 gchar *type, *subtype, *params;
1887
1888                 type = g_strdup(content_type);
1889                 subtype = strchr(type, '/') + 1;
1890                 *(subtype - 1) = '\0';
1891                 if ((params = strchr(subtype, ';')) != NULL) {
1892                         params[0] = '\0';
1893                         params++;
1894                 }
1895
1896                 mimeinfo->type = procmime_get_media_type(type);
1897                 mimeinfo->subtype = g_strstrip(g_strdup(subtype));
1898
1899                 /* Get mimeinfo->typeparameters */
1900                 if (params != NULL)
1901                         parse_parameters(params, mimeinfo->typeparameters);
1902
1903                 g_free(type);
1904         }
1905 }
1906
1907 static void procmime_parse_content_disposition(const gchar *content_disposition, MimeInfo *mimeinfo)
1908 {
1909         gchar *tmp, *params;
1910
1911         cm_return_if_fail(content_disposition != NULL);
1912         cm_return_if_fail(mimeinfo != NULL);
1913
1914         tmp = g_strdup(content_disposition);
1915         if ((params = strchr(tmp, ';')) != NULL) {
1916                 params[0] = '\0';
1917                 params++;
1918         }       
1919         g_strstrip(tmp);
1920
1921         if (!g_ascii_strcasecmp(tmp, "inline")) 
1922                 mimeinfo->disposition = DISPOSITIONTYPE_INLINE;
1923         else if (!g_ascii_strcasecmp(tmp, "attachment"))
1924                 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1925         else
1926                 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1927         
1928         if (params != NULL)
1929                 parse_parameters(params, mimeinfo->dispositionparameters);
1930
1931         g_free(tmp);
1932 }
1933
1934
1935 static void procmime_parse_content_encoding(const gchar *content_encoding, MimeInfo *mimeinfo)
1936 {
1937         struct EncodingTable *enc_table;
1938         
1939         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1940                 if (g_ascii_strcasecmp(enc_table->str, content_encoding) == 0) {
1941                         mimeinfo->encoding_type = enc_table->enc_type;
1942                         return;
1943                 }
1944         }
1945         mimeinfo->encoding_type = ENC_UNKNOWN;
1946         return;
1947 }
1948
1949 static GSList *registered_parsers = NULL;
1950
1951 static MimeParser *procmime_get_mimeparser_for_type(MimeMediaType type, const gchar *sub_type)
1952 {
1953         GSList *cur;
1954         for (cur = registered_parsers; cur; cur = cur->next) {
1955                 MimeParser *parser = (MimeParser *)cur->data;
1956                 if (parser->type == type && !strcmp2(parser->sub_type, sub_type))
1957                         return parser;
1958         }
1959         return NULL;
1960 }
1961
1962 void procmime_mimeparser_register(MimeParser *parser)
1963 {
1964         if (!procmime_get_mimeparser_for_type(parser->type, parser->sub_type))
1965                 registered_parsers = g_slist_append(registered_parsers, parser);
1966 }
1967
1968
1969 void procmime_mimeparser_unregister(MimeParser *parser) 
1970 {
1971         registered_parsers = g_slist_remove(registered_parsers, parser);
1972 }
1973
1974 static gboolean procmime_mimeparser_parse(MimeParser *parser, MimeInfo *mimeinfo)
1975 {
1976         cm_return_val_if_fail(parser->parse != NULL, FALSE);
1977         return parser->parse(parser, mimeinfo); 
1978 }
1979
1980 static int procmime_parse_mimepart(MimeInfo *parent,
1981                              gchar *content_type,
1982                              gchar *content_encoding,
1983                              gchar *content_description,
1984                              gchar *content_id,
1985                              gchar *content_disposition,
1986                              gchar *content_location,
1987                              const gchar *original_msgid,
1988                              const gchar *disposition_notification_hdr,
1989                              const gchar *filename,
1990                              guint offset,
1991                              guint length,
1992                              gboolean short_scan)
1993 {
1994         MimeInfo *mimeinfo;
1995         MimeParser *parser = NULL;
1996         gboolean parsed = FALSE;
1997         int result = 0;
1998
1999         /* Create MimeInfo */
2000         mimeinfo = procmime_mimeinfo_new();
2001         mimeinfo->content = MIMECONTENT_FILE;
2002
2003         if (parent != NULL) {
2004                 if (g_node_depth(parent->node) > 32) {
2005                         /* 32 is an arbitrary value
2006                          * this avoids DOSsing ourselves 
2007                          * with enormous messages
2008                          */
2009                         procmime_mimeinfo_free_all(mimeinfo);
2010                         return -1;                      
2011                 }
2012                 g_node_append(parent->node, mimeinfo->node);
2013         }
2014         mimeinfo->data.filename = g_strdup(filename);
2015         mimeinfo->offset = offset;
2016         mimeinfo->length = length;
2017
2018         if (content_type != NULL) {
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                 procmime_parse_content_encoding(content_encoding, mimeinfo);
2034         } else {
2035                 mimeinfo->encoding_type = ENC_UNKNOWN;
2036         }
2037
2038         if (content_description != NULL)
2039                 mimeinfo->description = g_strdup(content_description);
2040         else
2041                 mimeinfo->description = NULL;
2042
2043         if (content_id != NULL)
2044                 mimeinfo->id = g_strdup(content_id);
2045         else
2046                 mimeinfo->id = NULL;
2047
2048         if (content_location != NULL)
2049                 mimeinfo->location = g_strdup(content_location);
2050         else
2051                 mimeinfo->location = NULL;
2052
2053         if (content_disposition != NULL) 
2054                 procmime_parse_content_disposition(content_disposition, mimeinfo);
2055         else
2056                 mimeinfo->disposition = DISPOSITIONTYPE_UNKNOWN;
2057
2058         /* Call parser for mime type */
2059         if ((parser = procmime_get_mimeparser_for_type(mimeinfo->type, mimeinfo->subtype)) != NULL) {
2060                 parsed = procmime_mimeparser_parse(parser, mimeinfo);
2061         } 
2062         if (!parsed) {
2063                 switch (mimeinfo->type) {
2064                 case MIMETYPE_TEXT:
2065                         if (g_ascii_strcasecmp(mimeinfo->subtype, "plain") == 0 && short_scan) {
2066                                 return 1;
2067                         }
2068                         break;
2069
2070                 case MIMETYPE_MESSAGE:
2071                         if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
2072                                 procmime_parse_message_rfc822(mimeinfo, short_scan);
2073                         }
2074                         if (g_ascii_strcasecmp(mimeinfo->subtype, "disposition-notification") == 0) {
2075                                 procmime_parse_disposition_notification(mimeinfo, 
2076                                         original_msgid, disposition_notification_hdr, short_scan);
2077                         }
2078                         break;
2079                         
2080                 case MIMETYPE_MULTIPART:
2081                         procmime_parse_multipart(mimeinfo, short_scan);
2082                         break;
2083                 
2084                 case MIMETYPE_APPLICATION:
2085                         if (g_ascii_strcasecmp(mimeinfo->subtype, "octet-stream") == 0
2086                         && original_msgid && *original_msgid 
2087                         && disposition_notification_hdr && *disposition_notification_hdr) {
2088                                 procmime_parse_disposition_notification(mimeinfo, 
2089                                         original_msgid, disposition_notification_hdr, short_scan);
2090                         }
2091                         break;
2092                 default:
2093                         break;
2094                 }
2095         }
2096
2097         return result;
2098 }
2099
2100 static gchar *typenames[] = {
2101     "text",
2102     "image",
2103     "audio",
2104     "video",
2105     "application",
2106     "message",
2107     "multipart",
2108     "unknown",
2109 };
2110
2111 static gboolean output_func(GNode *node, gpointer data)
2112 {
2113         guint i, depth;
2114         MimeInfo *mimeinfo = (MimeInfo *) node->data;
2115
2116         depth = g_node_depth(node);
2117         for (i = 0; i < depth; i++)
2118                 g_print("    ");
2119         g_print("%s/%s (offset:%d length:%d encoding: %d)\n", typenames[mimeinfo->type], mimeinfo->subtype, mimeinfo->offset, mimeinfo->length, mimeinfo->encoding_type);
2120
2121         return FALSE;
2122 }
2123
2124 static void output_mime_structure(MimeInfo *mimeinfo, int indent)
2125 {
2126         g_node_traverse(mimeinfo->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1, output_func, NULL);
2127 }
2128
2129 static MimeInfo *procmime_scan_file_with_offset(const gchar *filename, int offset, gboolean short_scan)
2130 {
2131         MimeInfo *mimeinfo;
2132         struct stat buf;
2133
2134         g_stat(filename, &buf);
2135
2136         mimeinfo = procmime_mimeinfo_new();
2137         mimeinfo->content = MIMECONTENT_FILE;
2138         mimeinfo->encoding_type = ENC_UNKNOWN;
2139         mimeinfo->type = MIMETYPE_MESSAGE;
2140         mimeinfo->subtype = g_strdup("rfc822");
2141         mimeinfo->data.filename = g_strdup(filename);
2142         mimeinfo->offset = offset;
2143         mimeinfo->length = buf.st_size - offset;
2144
2145         procmime_parse_message_rfc822(mimeinfo, short_scan);
2146         if (debug_get_mode())
2147                 output_mime_structure(mimeinfo, 0);
2148
2149         return mimeinfo;
2150 }
2151
2152 static MimeInfo *procmime_scan_file_full(const gchar *filename, gboolean short_scan)
2153 {
2154         MimeInfo *mimeinfo;
2155
2156         cm_return_val_if_fail(filename != NULL, NULL);
2157
2158         mimeinfo = procmime_scan_file_with_offset(filename, 0, short_scan);
2159
2160         return mimeinfo;
2161 }
2162
2163 MimeInfo *procmime_scan_file(const gchar *filename)
2164 {
2165         return procmime_scan_file_full(filename, FALSE);
2166 }
2167
2168 static MimeInfo *procmime_scan_file_short(const gchar *filename)
2169 {
2170         return procmime_scan_file_full(filename, TRUE);
2171 }
2172
2173 static MimeInfo *procmime_scan_queue_file_full(const gchar *filename, gboolean short_scan)
2174 {
2175         FILE *fp;
2176         MimeInfo *mimeinfo;
2177         gchar buf[BUFFSIZE];
2178         gint offset = 0;
2179
2180         cm_return_val_if_fail(filename != NULL, NULL);
2181
2182         /* Open file */
2183         if ((fp = procmime_fopen(filename, "rb")) == NULL)
2184                 return NULL;
2185         /* Skip queue header */
2186         while (SC_FGETS(buf, sizeof(buf), fp) != NULL) {
2187                 /* new way */
2188                 if ((!strncmp(buf, "X-Claws-End-Special-Headers: 1",
2189                         strlen("X-Claws-End-Special-Headers:"))) ||
2190                    (!strncmp(buf, "X-Sylpheed-End-Special-Headers: 1",
2191                         strlen("X-Sylpheed-End-Special-Headers:"))))
2192                         break;
2193                 /* old way */
2194                 if (buf[0] == '\r' || buf[0] == '\n') break;
2195                 /* from other mailers */
2196                 if (!strncmp(buf, "Date: ", 6)
2197                 ||  !strncmp(buf, "To: ", 4)
2198                 ||  !strncmp(buf, "From: ", 6)
2199                 ||  !strncmp(buf, "Subject: ", 9)) {
2200                         rewind(fp);
2201                         break;
2202                 }
2203         }
2204         offset = ftell(fp);
2205         procmime_fclose(fp);
2206
2207         mimeinfo = procmime_scan_file_with_offset(filename, offset, short_scan);
2208
2209         return mimeinfo;
2210 }
2211
2212 MimeInfo *procmime_scan_queue_file(const gchar *filename)
2213 {
2214         return procmime_scan_queue_file_full(filename, FALSE);
2215 }
2216
2217 static MimeInfo *procmime_scan_queue_file_short(const gchar *filename)
2218 {
2219         return procmime_scan_queue_file_full(filename, TRUE);
2220 }
2221
2222 typedef enum {
2223     ENC_AS_TOKEN,
2224     ENC_AS_QUOTED_STRING,
2225     ENC_AS_EXTENDED,
2226     ENC_AS_ENCWORD
2227 } EncodeAs;
2228
2229 typedef struct _ParametersData {
2230         FILE *fp;
2231         guint len;
2232         gint error;
2233 } ParametersData;
2234
2235 static void write_parameters(gpointer key, gpointer value, gpointer user_data)
2236 {
2237         gchar *param = key;
2238         gchar *val = value, *valpos, *tmp;
2239         ParametersData *pdata = (ParametersData *)user_data;
2240         GString *buf = g_string_new("");
2241         gint len;
2242
2243         EncodeAs encas = ENC_AS_TOKEN;
2244
2245         for (valpos = val; *valpos != 0; valpos++) {
2246                 if (!IS_ASCII(*valpos)) {
2247                         encas = ENC_AS_ENCWORD;
2248                         break;
2249                 }
2250             
2251                 /* CTLs */
2252                 if (((*valpos >= 0) && (*valpos < 037)) || (*valpos == 0177)) {
2253                         encas = ENC_AS_QUOTED_STRING;
2254                         continue;
2255                 }
2256
2257                 /* tspecials + SPACE */
2258                 switch (*valpos) {
2259                 case ' ':
2260                 case '(': 
2261                 case ')':
2262                 case '<':
2263                 case '>':
2264                 case '@':
2265                 case ',':
2266                 case ';':
2267                 case ':':
2268                 case '\\':
2269                 case '"':
2270                 case '/':
2271                 case '[':
2272                 case ']':
2273                 case '?':
2274                 case '=':
2275                         encas = ENC_AS_QUOTED_STRING;
2276                         continue;
2277                 }
2278         }
2279         
2280         switch (encas) {
2281         case ENC_AS_TOKEN:
2282                 g_string_append_printf(buf, "%s=%s", param, val);
2283                 break;
2284
2285         case ENC_AS_QUOTED_STRING:
2286                 g_string_append_printf(buf, "%s=\"%s\"", param, val);
2287                 break;
2288
2289 #if 0 /* we don't use that for now */
2290         case ENC_AS_EXTENDED:
2291                 if (!g_utf8_validate(val, -1, NULL))
2292                         g_string_append_printf(buf, "%s*=%s''", param,
2293                                 conv_get_locale_charset_str());
2294                 else
2295                         g_string_append_printf(buf, "%s*=%s''", param,
2296                                 CS_INTERNAL);
2297                 for (valpos = val; *valpos != '\0'; valpos++) {
2298                         if (IS_ASCII(*valpos) && isalnum(*valpos)) {
2299                                 g_string_append_printf(buf, "%c", *valpos);
2300                         } else {
2301                                 gchar hexstr[3] = "XX";
2302                                 get_hex_str(hexstr, *valpos);
2303                                 g_string_append_printf(buf, "%%%s", hexstr);
2304                         }
2305                 }
2306                 break;
2307 #else
2308         case ENC_AS_EXTENDED:
2309                 debug_print("Unhandled ENC_AS_EXTENDED.");
2310                 break;
2311 #endif
2312         case ENC_AS_ENCWORD:
2313                 len = MAX(strlen(val)*6, 512);
2314                 tmp = g_malloc(len+1);
2315                 codeconv_set_strict(TRUE);
2316                 conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2317                         prefs_common.outgoing_charset);
2318                 codeconv_set_strict(FALSE);
2319                 if (!tmp || !*tmp) {
2320                         codeconv_set_strict(TRUE);
2321                         conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2322                                 conv_get_outgoing_charset_str());
2323                         codeconv_set_strict(FALSE);
2324                 }
2325                 if (!tmp || !*tmp) {
2326                         codeconv_set_strict(TRUE);
2327                         conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2328                                 CS_UTF_8);
2329                         codeconv_set_strict(FALSE);
2330                 }
2331                 if (!tmp || !*tmp) {
2332                         conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2333                                 CS_UTF_8);
2334                 }
2335                 g_string_append_printf(buf, "%s=\"%s\"", param, tmp);
2336                 g_free(tmp);
2337                 break;
2338
2339         }
2340         
2341         if (buf->str && strlen(buf->str)) {
2342                 tmp = strstr(buf->str, "\n");
2343                 if (tmp)
2344                         len = (tmp - buf->str);
2345                 else
2346                         len = strlen(buf->str);
2347                 if (pdata->len + len > 76) {
2348                         if (fprintf(pdata->fp, ";\n %s", buf->str) < 0)
2349                                 pdata->error = TRUE;
2350                         pdata->len = strlen(buf->str) + 1;
2351                 } else {
2352                         if (fprintf(pdata->fp, "; %s", buf->str) < 0)
2353                                 pdata->error = TRUE;
2354                         pdata->len += strlen(buf->str) + 2;
2355                 }
2356         }
2357         g_string_free(buf, TRUE);
2358 }
2359
2360 #define TRY(func) { \
2361         if (!(func)) { \
2362                 return -1; \
2363         } \
2364 }
2365
2366 int procmime_write_mime_header(MimeInfo *mimeinfo, FILE *fp)
2367 {
2368         struct TypeTable *type_table;
2369         ParametersData *pdata = g_new0(ParametersData, 1);
2370         debug_print("procmime_write_mime_header\n");
2371         
2372         pdata->fp = fp;
2373         pdata->error = FALSE;
2374         for (type_table = mime_type_table; type_table->str != NULL; type_table++)
2375                 if (mimeinfo->type == type_table->type) {
2376                         gchar *buf = g_strdup_printf(
2377                                 "Content-Type: %s/%s", type_table->str, mimeinfo->subtype);
2378                         if (fprintf(fp, "%s", buf) < 0) {
2379                                 g_free(buf);
2380                                 g_free(pdata);
2381                                 return -1;
2382                         }
2383                         pdata->len = strlen(buf);
2384                         g_free(buf);
2385                         break;
2386                 }
2387         g_hash_table_foreach(mimeinfo->typeparameters, write_parameters, pdata);
2388         if (pdata->error == TRUE) {
2389                 g_free(pdata);
2390                 return -1;
2391         }
2392         g_free(pdata);
2393
2394         TRY(fprintf(fp, "\n") >= 0);
2395
2396         if (mimeinfo->encoding_type != ENC_UNKNOWN)
2397                 TRY(fprintf(fp, "Content-Transfer-Encoding: %s\n", procmime_get_encoding_str(mimeinfo->encoding_type)) >= 0);
2398
2399         if (mimeinfo->description != NULL)
2400                 TRY(fprintf(fp, "Content-Description: %s\n", mimeinfo->description) >= 0);
2401
2402         if (mimeinfo->id != NULL)
2403                 TRY(fprintf(fp, "Content-ID: %s\n", mimeinfo->id) >= 0);
2404
2405         if (mimeinfo->location != NULL)
2406                 TRY(fprintf(fp, "Content-Location: %s\n", mimeinfo->location) >= 0);
2407
2408         if (mimeinfo->disposition != DISPOSITIONTYPE_UNKNOWN) {
2409                 ParametersData *pdata = g_new0(ParametersData, 1);
2410                 gchar *buf = NULL;
2411                 if (mimeinfo->disposition == DISPOSITIONTYPE_INLINE)
2412                         buf = g_strdup("Content-Disposition: inline");
2413                 else if (mimeinfo->disposition == DISPOSITIONTYPE_ATTACHMENT)
2414                         buf = g_strdup("Content-Disposition: attachment");
2415                 else
2416                         buf = g_strdup("Content-Disposition: unknown");
2417
2418                 if (fprintf(fp, "%s", buf) < 0) {
2419                         g_free(buf);
2420                         g_free(pdata);
2421                         return -1;
2422                 }
2423                 pdata->len = strlen(buf);
2424                 g_free(buf);
2425
2426                 pdata->fp = fp;
2427                 pdata->error = FALSE;
2428                 g_hash_table_foreach(mimeinfo->dispositionparameters, write_parameters, pdata);
2429                 if (pdata->error == TRUE) {
2430                         g_free(pdata);
2431                         return -1;
2432                 }
2433                 g_free(pdata);
2434                 TRY(fprintf(fp, "\n") >= 0);
2435         }
2436
2437         TRY(fprintf(fp, "\n") >= 0);
2438         
2439         return 0;
2440 }
2441
2442 static gint procmime_write_message_rfc822(MimeInfo *mimeinfo, FILE *fp)
2443 {
2444         FILE *infp;
2445         GNode *childnode;
2446         MimeInfo *child;
2447         gchar buf[BUFFSIZE];
2448         gboolean skip = FALSE;;
2449         size_t len;
2450
2451         debug_print("procmime_write_message_rfc822\n");
2452
2453         /* write header */
2454         switch (mimeinfo->content) {
2455         case MIMECONTENT_FILE:
2456                 if ((infp = procmime_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2457                         FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2458                         return -1;
2459                 }
2460                 fseek(infp, mimeinfo->offset, SEEK_SET);
2461                 while (SC_FGETS(buf, sizeof(buf), infp) == buf) {
2462                         strcrchomp(buf);
2463                         if (buf[0] == '\n' && buf[1] == '\0')
2464                                 break;
2465                         if (skip && (buf[0] == ' ' || buf[0] == '\t'))
2466                                 continue;
2467                         if (g_ascii_strncasecmp(buf, "MIME-Version:", 13) == 0 ||
2468                             g_ascii_strncasecmp(buf, "Content-Type:", 13) == 0 ||
2469                             g_ascii_strncasecmp(buf, "Content-Transfer-Encoding:", 26) == 0 ||
2470                             g_ascii_strncasecmp(buf, "Content-Description:", 20) == 0 ||
2471                             g_ascii_strncasecmp(buf, "Content-ID:", 11) == 0 ||
2472                             g_ascii_strncasecmp(buf, "Content-Location:", 17) == 0 ||
2473                             g_ascii_strncasecmp(buf, "Content-Disposition:", 20) == 0) {
2474                                 skip = TRUE;
2475                                 continue;
2476                         }
2477                         len = strlen(buf);
2478                         if (SC_FWRITE(buf, sizeof(gchar), len, fp) < len) {
2479                                 g_warning("failed to dump %zd bytes from file", len);
2480                                 procmime_fclose(infp);
2481                                 return -1;
2482                         }
2483                         skip = FALSE;
2484                 }
2485                 procmime_fclose(infp);
2486                 break;
2487
2488         case MIMECONTENT_MEM:
2489                 len = strlen(mimeinfo->data.mem);
2490                 if (SC_FWRITE(mimeinfo->data.mem, sizeof(gchar), len, fp) < len) {
2491                         g_warning("failed to dump %zd bytes from mem", len);
2492                         return -1;
2493                 }
2494                 break;
2495
2496         default:
2497                 break;
2498         }
2499
2500         childnode = mimeinfo->node->children;
2501         if (childnode == NULL)
2502                 return -1;
2503
2504         child = (MimeInfo *) childnode->data;
2505         if (fprintf(fp, "MIME-Version: 1.0\n") < 0) {
2506                 g_warning("failed to write mime version");
2507                 return -1;
2508         }
2509         if (procmime_write_mime_header(child, fp) < 0)
2510                 return -1;
2511         return procmime_write_mimeinfo(child, fp);
2512 }
2513
2514 static gint procmime_write_multipart(MimeInfo *mimeinfo, FILE *fp)
2515 {
2516         FILE *infp;
2517         GNode *childnode;
2518         gchar *boundary, *str, *str2;
2519         gchar buf[BUFFSIZE];
2520         gboolean firstboundary;
2521         size_t len;
2522
2523         debug_print("procmime_write_multipart\n");
2524
2525         boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
2526
2527         switch (mimeinfo->content) {
2528         case MIMECONTENT_FILE:
2529                 if ((infp = procmime_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2530                         FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2531                         return -1;
2532                 }
2533                 fseek(infp, mimeinfo->offset, SEEK_SET);
2534                 while (SC_FGETS(buf, sizeof(buf), infp) == buf) {
2535                         if (IS_BOUNDARY(buf, boundary, strlen(boundary)))
2536                                 break;
2537                         len = strlen(buf);
2538                         if (SC_FWRITE(buf, sizeof(gchar), len, fp) < len) {
2539                                 g_warning("failed to write %zd", len);
2540                                 procmime_fclose(infp);
2541                                 return -1;
2542                         }
2543                 }
2544                 procmime_fclose(infp);
2545                 break;
2546
2547         case MIMECONTENT_MEM:
2548                 str = g_strdup(mimeinfo->data.mem);
2549                 if (((str2 = strstr(str, boundary)) != NULL) && ((str2 - str) >= 2) &&
2550                     (*(str2 - 1) == '-') && (*(str2 - 2) == '-'))
2551                         *(str2 - 2) = '\0';
2552                 len = strlen(str);
2553                 if (SC_FWRITE(str, sizeof(gchar), len, fp) < len) {
2554                         g_warning("failed to write %zd from mem", len);
2555                         g_free(str);
2556                         return -1;
2557                 }
2558                 g_free(str);
2559                 break;
2560
2561         default:
2562                 break;
2563         }
2564
2565         childnode = mimeinfo->node->children;
2566         firstboundary = TRUE;
2567         while (childnode != NULL) {
2568                 MimeInfo *child = childnode->data;
2569
2570                 if (firstboundary)
2571                         firstboundary = FALSE;
2572                 else
2573                         TRY(fprintf(fp, "\n") >= 0);
2574                         
2575                 TRY(fprintf(fp, "--%s\n", boundary) >= 0);
2576
2577                 if (procmime_write_mime_header(child, fp) < 0)
2578                         return -1;
2579                 if (procmime_write_mimeinfo(child, fp) < 0)
2580                         return -1;
2581
2582                 childnode = g_node_next_sibling(childnode);
2583         }       
2584         TRY(fprintf(fp, "\n--%s--\n", boundary) >= 0);
2585
2586         return 0;
2587 }
2588
2589 gint procmime_write_mimeinfo(MimeInfo *mimeinfo, FILE *fp)
2590 {
2591         FILE *infp;
2592         size_t len;
2593         debug_print("procmime_write_mimeinfo\n");
2594
2595         if (G_NODE_IS_LEAF(mimeinfo->node)) {
2596                 switch (mimeinfo->content) {
2597                 case MIMECONTENT_FILE:
2598                         if ((infp = procmime_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2599                                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2600                                 return -1;
2601                         }
2602                         copy_file_part_to_fp(infp, mimeinfo->offset, mimeinfo->length, fp);
2603                         procmime_fclose(infp);
2604                         return 0;
2605
2606                 case MIMECONTENT_MEM:
2607                         len = strlen(mimeinfo->data.mem);
2608                         if (SC_FWRITE(mimeinfo->data.mem, sizeof(gchar), len, fp) < len)
2609                                 return -1;
2610                         return 0;
2611
2612                 default:
2613                         return 0;
2614                 }
2615         } else {
2616                 /* Call writer for mime type */
2617                 switch (mimeinfo->type) {
2618                 case MIMETYPE_MESSAGE:
2619                         if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
2620                                 return procmime_write_message_rfc822(mimeinfo, fp);
2621                         }
2622                         break;
2623                         
2624                 case MIMETYPE_MULTIPART:
2625                         return procmime_write_multipart(mimeinfo, fp);
2626                         
2627                 default:
2628                         break;
2629                 }
2630
2631                 return -1;
2632         }
2633
2634         return 0;
2635 }
2636
2637 gchar *procmime_get_part_file_name(MimeInfo *mimeinfo)
2638 {
2639         gchar *base;
2640
2641         if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
2642                 base = g_strdup("mimetmp.html");
2643         else {
2644                 const gchar *basetmp;
2645                 gchar *basename;
2646
2647                 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
2648                 if (basetmp == NULL)
2649                         basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
2650                 if (basetmp == NULL)
2651                         basetmp = "mimetmp";
2652                 basename = g_path_get_basename(basetmp);
2653                 if (*basename == '\0') {
2654                         g_free(basename);
2655                         basename = g_strdup("mimetmp");
2656                 }
2657                 base = conv_filename_from_utf8(basename);
2658                 g_free(basename);
2659                 subst_for_shellsafe_filename(base);
2660         }
2661         
2662         return base;
2663 }
2664