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