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