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