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