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