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