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