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