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