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