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