c47c7b68b3cc6ab1e277e54195b16563fbbb4401
[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 #endif
943
944         if (tmpfile != NULL) {
945                 g_unlink(tmpfile);
946                 g_free(tmpfile);
947         }
948
949         if (procmime_get_part_to_stream(outfp, mimeinfo) < 0) {
950                 return NULL;
951         }
952
953 #ifdef HAVE_FGETS_UNLOCKED
954         funlockfile(outfp);
955 #endif
956         return outfp;
957 }
958
959 /* search the first text part of (multipart) MIME message,
960    decode, convert it and output to outfp. */
961 FILE *procmime_get_first_text_content(MsgInfo *msginfo)
962 {
963         FILE *outfp = NULL;
964         MimeInfo *mimeinfo, *partinfo;
965         gboolean empty_ok = FALSE, short_scan = TRUE;
966
967         cm_return_val_if_fail(msginfo != NULL, NULL);
968
969         /* first we try to short-scan (for speed), refusing empty parts */
970 scan_again:
971         if (short_scan)
972                 mimeinfo = procmime_scan_message_short(msginfo);
973         else
974                 mimeinfo = procmime_scan_message(msginfo);
975         if (!mimeinfo) return NULL;
976
977         partinfo = mimeinfo;
978         while (partinfo && (partinfo->type != MIMETYPE_TEXT ||
979                (partinfo->length == 0 && !empty_ok))) {
980                 partinfo = procmime_mimeinfo_next(partinfo);
981         }
982         if (partinfo)
983                 outfp = procmime_get_text_content(partinfo);
984         else if (!empty_ok && short_scan) {
985                 /* if short scan didn't find a non-empty part, rescan
986                  * fully for non-empty parts
987                  */
988                 short_scan = FALSE;
989                 procmime_mimeinfo_free_all(&mimeinfo);
990                 goto scan_again;
991         } else if (!empty_ok && !short_scan) {
992                 /* if full scan didn't find a non-empty part, rescan
993                  * accepting empty parts 
994                  */
995                 empty_ok = TRUE;
996                 procmime_mimeinfo_free_all(&mimeinfo);
997                 goto scan_again;
998         }
999         procmime_mimeinfo_free_all(&mimeinfo);
1000
1001         /* outfp already unlocked at this time */
1002         return outfp;
1003 }
1004
1005
1006 static gboolean find_encrypted_func(GNode *node, gpointer data)
1007 {
1008         MimeInfo *mimeinfo = (MimeInfo *) node->data;
1009         MimeInfo **encinfo = (MimeInfo **) data;
1010         
1011         if (privacy_mimeinfo_is_encrypted(mimeinfo)) {
1012                 *encinfo = mimeinfo;
1013                 return TRUE;
1014         }
1015         
1016         return FALSE;
1017 }
1018
1019 static MimeInfo *find_encrypted_part(MimeInfo *rootinfo)
1020 {
1021         MimeInfo *encinfo = NULL;
1022
1023         g_node_traverse(rootinfo->node, G_IN_ORDER, G_TRAVERSE_ALL, -1,
1024                 find_encrypted_func, &encinfo);
1025         
1026         return encinfo;
1027 }
1028
1029 /* search the first encrypted text part of (multipart) MIME message,
1030    decode, convert it and output to outfp. */
1031 FILE *procmime_get_first_encrypted_text_content(MsgInfo *msginfo)
1032 {
1033         FILE *outfp = NULL;
1034         MimeInfo *mimeinfo, *partinfo, *encinfo;
1035
1036         cm_return_val_if_fail(msginfo != NULL, NULL);
1037
1038         mimeinfo = procmime_scan_message(msginfo);
1039         if (!mimeinfo) {
1040                 return NULL;
1041         }
1042
1043         partinfo = mimeinfo;
1044         if ((encinfo = find_encrypted_part(partinfo)) != NULL) {
1045                 debug_print("decrypting message part\n");
1046                 if (privacy_mimeinfo_decrypt(encinfo) < 0) {
1047                         alertpanel_error(_("Couldn't decrypt: %s"),
1048                                 privacy_get_error());
1049                         return NULL;
1050                 }
1051         }
1052         partinfo = mimeinfo;
1053         while (partinfo && partinfo->type != MIMETYPE_TEXT) {
1054                 partinfo = procmime_mimeinfo_next(partinfo);
1055                 if (privacy_mimeinfo_is_signed(partinfo))
1056                         procmsg_msginfo_set_flags(msginfo, 0, MSG_SIGNED);
1057         }
1058
1059         if (partinfo)
1060                 outfp = procmime_get_text_content(partinfo);
1061
1062         procmime_mimeinfo_free_all(&mimeinfo);
1063
1064         /* outfp already unlocked at this time */
1065         return outfp;
1066 }
1067
1068 gboolean procmime_msginfo_is_encrypted(MsgInfo *msginfo)
1069 {
1070         MimeInfo *mimeinfo, *partinfo;
1071         gboolean result = FALSE;
1072
1073         cm_return_val_if_fail(msginfo != NULL, FALSE);
1074
1075         mimeinfo = procmime_scan_message(msginfo);
1076         if (!mimeinfo) {
1077                 return FALSE;
1078         }
1079
1080         partinfo = mimeinfo;
1081         result = (find_encrypted_part(partinfo) != NULL);
1082         procmime_mimeinfo_free_all(&mimeinfo);
1083
1084         return result;
1085 }
1086
1087 gchar *procmime_get_tmp_file_name(MimeInfo *mimeinfo)
1088 {
1089         static guint32 id = 0;
1090         gchar *base;
1091         gchar *filename;
1092         gchar f_prefix[10];
1093
1094         cm_return_val_if_fail(mimeinfo != NULL, NULL);
1095
1096         g_snprintf(f_prefix, sizeof(f_prefix), "%08x.", id++);
1097
1098         if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
1099                 base = g_strdup("mimetmp.html");
1100         else {
1101                 const gchar *basetmp;
1102
1103                 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
1104                 if (basetmp == NULL)
1105                         basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
1106                 if (basetmp == NULL)
1107                         basetmp = "mimetmp";
1108                 basetmp = g_path_get_basename(basetmp);
1109                 if (*basetmp == '\0') 
1110                         basetmp = g_strdup("mimetmp");
1111                 base = conv_filename_from_utf8(basetmp);
1112                 g_free((gchar*)basetmp);
1113                 subst_for_shellsafe_filename(base);
1114         }
1115
1116         filename = g_strconcat(get_mime_tmp_dir(), G_DIR_SEPARATOR_S,
1117                                f_prefix, base, NULL);
1118
1119         g_free(base);
1120         
1121         return filename;
1122 }
1123
1124 static GList *mime_type_list = NULL;
1125
1126 gchar *procmime_get_mime_type(const gchar *filename)
1127 {
1128         const gchar *p;
1129         gchar *ext = NULL;
1130         gchar *base;
1131 #ifndef G_OS_WIN32
1132         static GHashTable *mime_type_table = NULL;
1133         MimeType *mime_type;
1134
1135         if (!mime_type_table) {
1136                 mime_type_table = procmime_get_mime_type_table();
1137                 if (!mime_type_table) return NULL;
1138         }
1139 #endif
1140
1141         if (filename == NULL)
1142                 return NULL;
1143
1144         base = g_path_get_basename(filename);
1145         if ((p = strrchr(base, '.')) != NULL)
1146                 ext = g_utf8_strdown(p + 1, -1);
1147         else
1148                 ext = g_utf8_strdown(base, -1);
1149         g_free(base);
1150
1151 #ifndef G_OS_WIN32
1152         mime_type = g_hash_table_lookup(mime_type_table, ext);
1153         
1154         if (mime_type) {
1155                 gchar *str;
1156                 str = g_strconcat(mime_type->type, "/", mime_type->sub_type,
1157                                   NULL);
1158                 debug_print("got type %s for %s\n", str, ext);
1159                 g_free(ext);
1160                 return str;
1161         }
1162         g_free(ext);
1163         return NULL;
1164 #else
1165         gchar *str = get_content_type_from_registry_with_ext(ext);
1166
1167         g_free(ext);
1168         return str;
1169 #endif
1170 }
1171
1172 static guint procmime_str_hash(gconstpointer gptr)
1173 {
1174         guint hash_result = 0;
1175         const char *str;
1176
1177         for (str = gptr; str && *str; str++) {
1178                 if (isupper(*str)) hash_result += (*str + ' ');
1179                 else hash_result += *str;
1180         }
1181
1182         return hash_result;
1183 }
1184
1185 static gint procmime_str_equal(gconstpointer gptr1, gconstpointer gptr2)
1186 {
1187         const char *str1 = gptr1;
1188         const char *str2 = gptr2;
1189
1190         return !g_utf8_collate(str1, str2);
1191 }
1192
1193 static GHashTable *procmime_get_mime_type_table(void)
1194 {
1195         GHashTable *table = NULL;
1196         GList *cur;
1197         MimeType *mime_type;
1198         gchar **exts;
1199
1200         if (!mime_type_list) {
1201                 mime_type_list = procmime_get_mime_type_list();
1202                 if (!mime_type_list) return NULL;
1203         }
1204
1205         table = g_hash_table_new(procmime_str_hash, procmime_str_equal);
1206
1207         for (cur = mime_type_list; cur != NULL; cur = cur->next) {
1208                 gint i;
1209                 gchar *key;
1210
1211                 mime_type = (MimeType *)cur->data;
1212
1213                 if (!mime_type->extension) continue;
1214
1215                 exts = g_strsplit(mime_type->extension, " ", 16);
1216                 for (i = 0; exts[i] != NULL; i++) {
1217                         /* Don't overwrite previously inserted extension */
1218                         if (!g_hash_table_lookup(table, exts[i])) {
1219                                 key = g_strdup(exts[i]);
1220                                 g_hash_table_insert(table, key, mime_type);
1221                         }
1222                 }
1223                 g_strfreev(exts);
1224         }
1225
1226         return table;
1227 }
1228
1229 GList *procmime_get_mime_type_list(void)
1230 {
1231         GList *list = NULL;
1232         FILE *fp;
1233         gchar buf[BUFFSIZE];
1234         gchar *p;
1235         gchar *delim;
1236         MimeType *mime_type;
1237         gboolean fp_is_glob_file = TRUE;
1238
1239         if (mime_type_list) 
1240                 return mime_type_list;
1241         
1242 #if defined(__NetBSD__) || defined(__OpenBSD__) || defined(__FreeBSD__)
1243         if ((fp = procmime_fopen(DATAROOTDIR "/mime/globs", "rb")) == NULL) 
1244 #else
1245         if ((fp = procmime_fopen("/usr/share/mime/globs", "rb")) == NULL) 
1246 #endif
1247         {
1248                 fp_is_glob_file = FALSE;
1249                 if ((fp = procmime_fopen("/etc/mime.types", "rb")) == NULL) {
1250                         if ((fp = procmime_fopen(SYSCONFDIR "/mime.types", "rb")) 
1251                                 == NULL) {
1252                                 FILE_OP_ERROR(SYSCONFDIR "/mime.types", 
1253                                         "fopen");
1254                                 return NULL;
1255                         }
1256                 }
1257         }
1258
1259         while (SC_FGETS(buf, sizeof(buf), fp) != NULL) {
1260                 p = strchr(buf, '#');
1261                 if (p) *p = '\0';
1262                 g_strstrip(buf);
1263
1264                 p = buf;
1265                 
1266                 if (fp_is_glob_file) {
1267                         while (*p && !g_ascii_isspace(*p) && (*p!=':')) p++;
1268                 } else {
1269                         while (*p && !g_ascii_isspace(*p)) p++;
1270                 }
1271
1272                 if (*p) {
1273                         *p = '\0';
1274                         p++;
1275                 }
1276                 delim = strchr(buf, '/');
1277                 if (delim == NULL) continue;
1278                 *delim = '\0';
1279
1280                 mime_type = g_new(MimeType, 1);
1281                 mime_type->type = g_strdup(buf);
1282                 mime_type->sub_type = g_strdup(delim + 1);
1283
1284                 if (fp_is_glob_file) {
1285                         while (*p && (g_ascii_isspace(*p)||(*p=='*')||(*p=='.'))) p++;
1286                 } else {
1287                         while (*p && g_ascii_isspace(*p)) p++;
1288                 }
1289
1290                 if (*p)
1291                         mime_type->extension = g_utf8_strdown(p, -1);
1292                 else
1293                         mime_type->extension = NULL;
1294
1295                 list = g_list_append(list, mime_type);
1296         }
1297
1298         procmime_fclose(fp);
1299
1300         if (!list)
1301                 g_warning("Can't read mime.types");
1302
1303         return list;
1304 }
1305
1306 EncodingType procmime_get_encoding_for_charset(const gchar *charset)
1307 {
1308         if (!charset)
1309                 return ENC_8BIT;
1310         else if (!g_ascii_strncasecmp(charset, "ISO-2022-", 9) ||
1311                  !g_ascii_strcasecmp(charset, "US-ASCII"))
1312                 return ENC_7BIT;
1313         else if (!g_ascii_strcasecmp(charset, "ISO-8859-5") ||
1314                  !g_ascii_strncasecmp(charset, "KOI8-", 5) ||
1315                  !g_ascii_strcasecmp(charset, "X-MAC-CYRILLIC") ||
1316                  !g_ascii_strcasecmp(charset, "MAC-CYRILLIC") ||
1317                  !g_ascii_strcasecmp(charset, "Windows-1251"))
1318                 return ENC_8BIT;
1319         else if (!g_ascii_strncasecmp(charset, "ISO-8859-", 9))
1320                 return ENC_QUOTED_PRINTABLE;
1321         else if (!g_ascii_strncasecmp(charset, "UTF-8", 5))
1322                 return ENC_QUOTED_PRINTABLE;
1323         else 
1324                 return ENC_8BIT;
1325 }
1326
1327 EncodingType procmime_get_encoding_for_text_file(const gchar *file, gboolean *has_binary)
1328 {
1329         FILE *fp;
1330         guchar buf[BUFFSIZE];
1331         size_t len;
1332         size_t octet_chars = 0;
1333         size_t total_len = 0;
1334         gfloat octet_percentage;
1335         gboolean force_b64 = FALSE;
1336
1337         if ((fp = procmime_fopen(file, "rb")) == NULL) {
1338                 FILE_OP_ERROR(file, "fopen");
1339                 return ENC_UNKNOWN;
1340         }
1341
1342         while ((len = SC_FREAD(buf, sizeof(guchar), sizeof(buf), fp)) > 0) {
1343                 guchar *p;
1344                 gint i;
1345
1346                 for (p = buf, i = 0; i < len; ++p, ++i) {
1347                         if (*p & 0x80)
1348                                 ++octet_chars;
1349                         if (*p == '\0') {
1350                                 force_b64 = TRUE;
1351                                 *has_binary = TRUE;
1352                         }
1353                 }
1354                 total_len += len;
1355         }
1356
1357         procmime_fclose(fp);
1358         
1359         if (total_len > 0)
1360                 octet_percentage = (gfloat)octet_chars / (gfloat)total_len;
1361         else
1362                 octet_percentage = 0.0;
1363
1364         debug_print("procmime_get_encoding_for_text_file(): "
1365                     "8bit chars: %zd / %zd (%f%%)\n", octet_chars, total_len,
1366                     100.0 * octet_percentage);
1367
1368         if (octet_percentage > 0.20 || force_b64) {
1369                 debug_print("using BASE64\n");
1370                 return ENC_BASE64;
1371         } else if (octet_chars > 0) {
1372                 debug_print("using quoted-printable\n");
1373                 return ENC_QUOTED_PRINTABLE;
1374         } else {
1375                 debug_print("using 7bit\n");
1376                 return ENC_7BIT;
1377         }
1378 }
1379
1380 struct EncodingTable 
1381 {
1382         gchar *str;
1383         EncodingType enc_type;
1384 };
1385
1386 struct EncodingTable encoding_table[] = {
1387         {"7bit", ENC_7BIT},
1388         {"8bit", ENC_8BIT},
1389         {"binary", ENC_BINARY},
1390         {"quoted-printable", ENC_QUOTED_PRINTABLE},
1391         {"base64", ENC_BASE64},
1392         {"x-uuencode", ENC_UNKNOWN},
1393         {NULL, ENC_UNKNOWN},
1394 };
1395
1396 const gchar *procmime_get_encoding_str(EncodingType encoding)
1397 {
1398         struct EncodingTable *enc_table;
1399         
1400         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1401                 if (enc_table->enc_type == encoding)
1402                         return enc_table->str;
1403         }
1404         return NULL;
1405 }
1406
1407 /* --- NEW MIME STUFF --- */
1408 struct TypeTable
1409 {
1410         gchar *str;
1411         MimeMediaType type;
1412 };
1413
1414 static struct TypeTable mime_type_table[] = {
1415         {"text", MIMETYPE_TEXT},
1416         {"image", MIMETYPE_IMAGE},
1417         {"audio", MIMETYPE_AUDIO},
1418         {"video", MIMETYPE_VIDEO},
1419         {"application", MIMETYPE_APPLICATION},
1420         {"message", MIMETYPE_MESSAGE},
1421         {"multipart", MIMETYPE_MULTIPART},
1422         {NULL, 0},
1423 };
1424
1425 const gchar *procmime_get_media_type_str(MimeMediaType type)
1426 {
1427         struct TypeTable *type_table;
1428         
1429         for (type_table = mime_type_table; type_table->str != NULL; type_table++) {
1430                 if (type_table->type == type)
1431                         return type_table->str;
1432         }
1433         return NULL;
1434 }
1435
1436 MimeMediaType procmime_get_media_type(const gchar *str)
1437 {
1438         struct TypeTable *typetablearray;
1439
1440         for (typetablearray = mime_type_table; typetablearray->str != NULL; typetablearray++)
1441                 if (g_ascii_strncasecmp(str, typetablearray->str, strlen(typetablearray->str)) == 0)
1442                         return typetablearray->type;
1443
1444         return MIMETYPE_UNKNOWN;
1445 }
1446
1447 /*!
1448  *\brief        Safe wrapper for content type string.
1449  *
1450  *\return       const gchar * Pointer to content type string. 
1451  */
1452 gchar *procmime_get_content_type_str(MimeMediaType type,
1453                                            const char *subtype)
1454 {
1455         const gchar *type_str = NULL;
1456
1457         if (subtype == NULL || !(type_str = procmime_get_media_type_str(type)))
1458                 return g_strdup("unknown");
1459         return g_strdup_printf("%s/%s", type_str, subtype);
1460 }
1461
1462 static int procmime_parse_mimepart(MimeInfo *parent,
1463                              gchar *content_type,
1464                              gchar *content_encoding,
1465                              gchar *content_description,
1466                              gchar *content_id,
1467                              gchar *content_disposition,
1468                              gchar *content_location,
1469                              const gchar *original_msgid,
1470                              const gchar *disposition_notification_hdr,
1471                              const gchar *filename,
1472                              guint offset,
1473                              guint length,
1474                              gboolean short_scan);
1475
1476 static void procmime_parse_message_rfc822(MimeInfo *mimeinfo, gboolean short_scan)
1477 {
1478         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1479                                 {"Content-Transfer-Encoding:",
1480                                                    NULL, FALSE},
1481                                 {"Content-Description:",
1482                                                    NULL, TRUE},
1483                                 {"Content-ID:",
1484                                                    NULL, TRUE},
1485                                 {"Content-Disposition:",
1486                                                    NULL, TRUE},
1487                                 {"Content-Location:",
1488                                                    NULL, TRUE},
1489                                 {"MIME-Version:",
1490                                                    NULL, TRUE},
1491                                 {"Original-Message-ID:",
1492                                                    NULL, TRUE},
1493                                 {"Disposition:",
1494                                                    NULL, TRUE},
1495                                 {NULL,             NULL, FALSE}};
1496         guint content_start, i;
1497         FILE *fp;
1498         gchar *tmp;
1499         gint len = 0;
1500
1501         procmime_decode_content(mimeinfo);
1502
1503         fp = procmime_fopen(mimeinfo->data.filename, "rb");
1504         if (fp == NULL) {
1505                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1506                 return;
1507         }
1508         if (fseek(fp, mimeinfo->offset, SEEK_SET) < 0) {
1509                 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
1510                 procmime_fclose(fp);
1511                 return;
1512         }
1513         procheader_get_header_fields(fp, hentry);
1514         if (hentry[0].body != NULL) {
1515                 tmp = conv_unmime_header(hentry[0].body, NULL, FALSE);
1516                 g_free(hentry[0].body);
1517                 hentry[0].body = tmp;
1518         }                
1519         if (hentry[2].body != NULL) {
1520                 tmp = conv_unmime_header(hentry[2].body, NULL, FALSE);
1521                 g_free(hentry[2].body);
1522                 hentry[2].body = tmp;
1523         }                
1524         if (hentry[4].body != NULL) {
1525                 tmp = conv_unmime_header(hentry[4].body, NULL, FALSE);
1526                 g_free(hentry[4].body);
1527                 hentry[4].body = tmp;
1528         }                
1529         if (hentry[5].body != NULL) {
1530                 tmp = conv_unmime_header(hentry[5].body, NULL, FALSE);
1531                 g_free(hentry[5].body);
1532                 hentry[5].body = tmp;
1533         }                
1534         if (hentry[7].body != NULL) {
1535                 tmp = conv_unmime_header(hentry[7].body, NULL, FALSE);
1536                 g_free(hentry[7].body);
1537                 hentry[7].body = tmp;
1538         }
1539         if (hentry[8].body != NULL) {
1540                 tmp = conv_unmime_header(hentry[8].body, NULL, FALSE);
1541                 g_free(hentry[8].body);
1542                 hentry[8].body = tmp;
1543         }
1544   
1545         content_start = ftell(fp);
1546         procmime_fclose(fp);
1547         
1548         len = mimeinfo->length - (content_start - mimeinfo->offset);
1549         if (len < 0)
1550                 len = 0;
1551         procmime_parse_mimepart(mimeinfo,
1552                                 hentry[0].body, hentry[1].body,
1553                                 hentry[2].body, hentry[3].body,
1554                                 hentry[4].body, hentry[5].body,
1555                                 hentry[7].body, hentry[8].body, 
1556                                 mimeinfo->data.filename, content_start,
1557                                 len, short_scan);
1558         
1559         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1560                 g_free(hentry[i].body);
1561                 hentry[i].body = NULL;
1562         }
1563 }
1564
1565 static void procmime_parse_disposition_notification(MimeInfo *mimeinfo, 
1566                 const gchar *original_msgid, const gchar *disposition_notification_hdr,
1567                 gboolean short_scan)
1568 {
1569         HeaderEntry hentry[] = {{"Original-Message-ID:",  NULL, TRUE},
1570                                 {"Disposition:",          NULL, TRUE},
1571                                 {NULL,                    NULL, FALSE}};
1572         guint i;
1573         FILE *fp;
1574         gchar *orig_msg_id = NULL;
1575         gchar *disp = NULL;
1576
1577         procmime_decode_content(mimeinfo);
1578
1579         debug_print("parse disposition notification\n");
1580         fp = procmime_fopen(mimeinfo->data.filename, "rb");
1581         if (fp == NULL) {
1582                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1583                 return;
1584         }
1585         if (fseek(fp, mimeinfo->offset, SEEK_SET) < 0) {
1586                 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
1587                 procmime_fclose(fp);
1588                 return;
1589         }
1590
1591         if (original_msgid && disposition_notification_hdr) {
1592                 hentry[0].body = g_strdup(original_msgid);
1593                 hentry[1].body = g_strdup(disposition_notification_hdr);
1594         } else {
1595                 procheader_get_header_fields(fp, hentry);
1596         }
1597     
1598         procmime_fclose(fp);
1599
1600         if (!hentry[0].body || !hentry[1].body) {
1601                 debug_print("MsgId %s, Disp %s\n",
1602                         hentry[0].body ? hentry[0].body:"(nil)",
1603                         hentry[1].body ? hentry[1].body:"(nil)");
1604                 goto bail;
1605         }
1606
1607         orig_msg_id = g_strdup(hentry[0].body);
1608         disp = g_strdup(hentry[1].body);
1609
1610         extract_parenthesis(orig_msg_id, '<', '>');
1611         remove_space(orig_msg_id);
1612         
1613         if (strstr(disp, "displayed")) {
1614                 /* find sent message, if possible */
1615                 MsgInfo *info = NULL;
1616                 GList *flist;
1617                 debug_print("%s has been displayed.\n", orig_msg_id);
1618                 for (flist = folder_get_list(); flist != NULL; flist = g_list_next(flist)) {
1619                         FolderItem *outbox = ((Folder *)(flist->data))->outbox;
1620                         if (!outbox) {
1621                                 debug_print("skipping folder with no outbox...\n");
1622                                 continue;
1623                         }
1624                         info = folder_item_get_msginfo_by_msgid(outbox, orig_msg_id);
1625                         debug_print("%s %s in %s\n", info?"found":"didn't find", orig_msg_id, outbox->path);
1626                         if (info) {
1627                                 procmsg_msginfo_set_flags(info, MSG_RETRCPT_GOT, 0);
1628                                 procmsg_msginfo_free(&info);
1629                         }
1630                 }
1631         }
1632         g_free(orig_msg_id);
1633         g_free(disp);
1634 bail:
1635         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1636                 g_free(hentry[i].body);
1637                 hentry[i].body = NULL;
1638         }
1639 }
1640
1641 #define GET_HEADERS() {                                         \
1642         procheader_get_header_fields(fp, hentry);               \
1643         if (hentry[0].body != NULL) {                           \
1644                 tmp = conv_unmime_header(hentry[0].body, NULL, FALSE);  \
1645                 g_free(hentry[0].body);                         \
1646                 hentry[0].body = tmp;                           \
1647         }                                                       \
1648         if (hentry[2].body != NULL) {                           \
1649                 tmp = conv_unmime_header(hentry[2].body, NULL, FALSE);  \
1650                 g_free(hentry[2].body);                         \
1651                 hentry[2].body = tmp;                           \
1652         }                                                       \
1653         if (hentry[4].body != NULL) {                           \
1654                 tmp = conv_unmime_header(hentry[4].body, NULL, FALSE);  \
1655                 g_free(hentry[4].body);                         \
1656                 hentry[4].body = tmp;                           \
1657         }                                                       \
1658         if (hentry[5].body != NULL) {                           \
1659                 tmp = conv_unmime_header(hentry[5].body, NULL, FALSE);  \
1660                 g_free(hentry[5].body);                         \
1661                 hentry[5].body = tmp;                           \
1662         }                                                       \
1663         if (hentry[6].body != NULL) {                           \
1664                 tmp = conv_unmime_header(hentry[6].body, NULL, FALSE);  \
1665                 g_free(hentry[6].body);                         \
1666                 hentry[6].body = tmp;                           \
1667         }                                                       \
1668         if (hentry[7].body != NULL) {                           \
1669                 tmp = conv_unmime_header(hentry[7].body, NULL, FALSE);  \
1670                 g_free(hentry[7].body);                         \
1671                 hentry[7].body = tmp;                           \
1672         }                                                       \
1673 }
1674
1675 static void procmime_parse_multipart(MimeInfo *mimeinfo, gboolean short_scan)
1676 {
1677         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1678                                 {"Content-Transfer-Encoding:",
1679                                                    NULL, FALSE},
1680                                 {"Content-Description:",
1681                                                    NULL, TRUE},
1682                                 {"Content-ID:",
1683                                                    NULL, TRUE},
1684                                 {"Content-Disposition:",
1685                                                    NULL, TRUE},
1686                                 {"Content-Location:",
1687                                                    NULL, TRUE},
1688                                 {"Original-Message-ID:",
1689                                                    NULL, TRUE},
1690                                 {"Disposition:",
1691                                                    NULL, TRUE},
1692                                 {NULL,             NULL, FALSE}};
1693         gchar *tmp;
1694         gchar *boundary;
1695         gint boundary_len = 0, lastoffset = -1, i;
1696         gchar buf[BUFFSIZE];
1697         FILE *fp;
1698         int result = 0;
1699         gboolean start_found = FALSE;
1700         gboolean end_found = FALSE;
1701
1702         boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
1703         if (!boundary)
1704                 return;
1705         boundary_len = strlen(boundary);
1706
1707         procmime_decode_content(mimeinfo);
1708
1709         fp = procmime_fopen(mimeinfo->data.filename, "rb");
1710         if (fp == NULL) {
1711                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1712                 return;
1713         }
1714
1715         if (fseek(fp, mimeinfo->offset, SEEK_SET) < 0) {
1716                 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
1717                 procmime_fclose(fp);
1718                 return;
1719         }
1720
1721         while (SC_FGETS(buf, sizeof(buf), fp) != NULL && result == 0) {
1722                 if (ftell(fp) - 1 > (mimeinfo->offset + mimeinfo->length))
1723                         break;
1724
1725                 if (IS_BOUNDARY(buf, boundary, boundary_len)) {
1726                         start_found = TRUE;
1727
1728                         if (lastoffset != -1) {
1729                                 gint len = (ftell(fp) - strlen(buf)) - lastoffset - 1;
1730                                 if (len < 0)
1731                                         len = 0;
1732                                 result = procmime_parse_mimepart(mimeinfo,
1733                                                         hentry[0].body, hentry[1].body,
1734                                                         hentry[2].body, hentry[3].body, 
1735                                                         hentry[4].body, hentry[5].body,
1736                                                         hentry[6].body, hentry[7].body,
1737                                                         mimeinfo->data.filename, lastoffset,
1738                                                         len, short_scan);
1739                                 if (result == 1 && short_scan)
1740                                         break;
1741                                 
1742                         } 
1743                         
1744                         if (buf[2 + boundary_len]     == '-' &&
1745                             buf[2 + boundary_len + 1] == '-') {
1746                                 end_found = TRUE;
1747                                 break;
1748                         }
1749                         for (i = 0; i < (sizeof hentry / sizeof hentry[0]) ; i++) {
1750                                 g_free(hentry[i].body);
1751                                 hentry[i].body = NULL;
1752                         }
1753                         GET_HEADERS();
1754                         lastoffset = ftell(fp);
1755                 }
1756         }
1757         
1758         if (start_found && !end_found && lastoffset != -1) {
1759                 gint len = (ftell(fp) - strlen(buf)) - lastoffset - 1;
1760
1761                 if (len >= 0) {
1762                         result = procmime_parse_mimepart(mimeinfo,
1763                                         hentry[0].body, hentry[1].body,
1764                                         hentry[2].body, hentry[3].body, 
1765                                         hentry[4].body, hentry[5].body,
1766                                         hentry[6].body, hentry[7].body,
1767                                         mimeinfo->data.filename, lastoffset,
1768                                         len, short_scan);
1769                 }
1770                 mimeinfo->broken = TRUE;
1771         }
1772         
1773         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1774                 g_free(hentry[i].body);
1775                 hentry[i].body = NULL;
1776         }
1777         procmime_fclose(fp);
1778 }
1779
1780 static void parse_parameters(const gchar *parameters, GHashTable *table)
1781 {
1782         gchar *params, *param, *next;
1783         GSList *convlist = NULL, *concatlist = NULL, *cur;
1784
1785         params = g_strdup(parameters);
1786         param = params;
1787         next = params;
1788         for (; next != NULL; param = next) {
1789                 gchar *attribute, *value, *tmp, *down_attr, *orig_down_attr;
1790                 gint len;
1791                 gboolean convert = FALSE;
1792
1793                 next = strchr_with_skip_quote(param, '"', ';');
1794                 if (next != NULL) {
1795                         next[0] = '\0';
1796                         next++;
1797                 }
1798
1799                 g_strstrip(param);
1800
1801                 attribute = param;
1802                 value = strchr(attribute, '=');
1803                 if (value == NULL)
1804                         continue;
1805
1806                 value[0] = '\0';
1807                 value++;
1808                 while (value[0] != '\0' && value[0] == ' ')
1809                         value++;
1810
1811                 down_attr = g_utf8_strdown(attribute, -1);
1812                 orig_down_attr = down_attr;
1813         
1814                 len = down_attr ? strlen(down_attr):0;
1815                 if (len > 0 && down_attr[len - 1] == '*') {
1816                         gchar *srcpos, *dstpos, *endpos;
1817
1818                         convert = TRUE;
1819                         down_attr[len - 1] = '\0';
1820
1821                         srcpos = value;
1822                         dstpos = value;
1823                         endpos = value + strlen(value);
1824                         while (srcpos < endpos) {
1825                                 if (*srcpos != '%')
1826                                         *dstpos = *srcpos;
1827                                 else {
1828                                         guchar dstvalue;
1829
1830                                         if (!get_hex_value(&dstvalue, srcpos[1], srcpos[2]))
1831                                                 *dstpos = '?';
1832                                         else
1833                                                 *dstpos = dstvalue;
1834                                         srcpos += 2;
1835                                 }
1836                                 srcpos++;
1837                                 dstpos++;
1838                         }
1839                         *dstpos = '\0';
1840                         if (value[0] == '"')
1841                                 extract_quote(value, '"');
1842                 } else {
1843                         if (value[0] == '"')
1844                                 extract_quote(value, '"');
1845                         else if ((tmp = strchr(value, ' ')) != NULL)
1846                                 *tmp = '\0';
1847                 }
1848
1849                 if (down_attr) {
1850                         while (down_attr[0] == ' ')
1851                                 down_attr++;
1852                         while (down_attr[strlen(down_attr)-1] == ' ') 
1853                                 down_attr[strlen(down_attr)-1] = '\0';
1854                 } 
1855
1856                 while (value[0] != '\0' && value[0] == ' ')
1857                         value++;
1858                 while (value[strlen(value)-1] == ' ') 
1859                         value[strlen(value)-1] = '\0';
1860
1861                 if (down_attr && strrchr(down_attr, '*') != NULL) {
1862                         gchar *tmpattr;
1863
1864                         tmpattr = g_strdup(down_attr);
1865                         tmp = strrchr(tmpattr, '*');
1866                         tmp[0] = '\0';
1867
1868                         if ((tmp[1] == '0') && (tmp[2] == '\0') && 
1869                             (g_slist_find_custom(concatlist, down_attr, (GCompareFunc)g_strcmp0) == NULL))
1870                                 concatlist = g_slist_prepend(concatlist, g_strdup(tmpattr));
1871
1872                         if (convert && (g_slist_find_custom(convlist, tmpattr, (GCompareFunc)g_strcmp0) == NULL))
1873                                 convlist = g_slist_prepend(convlist, g_strdup(tmpattr));
1874
1875                         g_free(tmpattr);
1876                 } else if (convert) {
1877                         if (g_slist_find_custom(convlist, down_attr, (GCompareFunc)g_strcmp0) == NULL)
1878                                 convlist = g_slist_prepend(convlist, g_strdup(down_attr));
1879                 }
1880
1881                 if (g_hash_table_lookup(table, down_attr) == NULL)
1882                         g_hash_table_insert(table, g_strdup(down_attr), g_strdup(value));
1883                 g_free(orig_down_attr);
1884         }
1885
1886         for (cur = concatlist; cur != NULL; cur = g_slist_next(cur)) {
1887                 gchar *attribute, *attrwnum, *partvalue;
1888                 gint n = 0;
1889                 GString *value;
1890
1891                 attribute = (gchar *) cur->data;
1892                 value = g_string_sized_new(64);
1893
1894                 attrwnum = g_strdup_printf("%s*%d", attribute, n);
1895                 while ((partvalue = g_hash_table_lookup(table, attrwnum)) != NULL) {
1896                         g_string_append(value, partvalue);
1897
1898                         g_hash_table_remove(table, attrwnum);
1899                         g_free(attrwnum);
1900                         n++;
1901                         attrwnum = g_strdup_printf("%s*%d", attribute, n);
1902                 }
1903                 g_free(attrwnum);
1904
1905                 g_hash_table_insert(table, g_strdup(attribute), g_strdup(value->str));
1906                 g_string_free(value, TRUE);
1907         }
1908         slist_free_strings_full(concatlist);
1909
1910         for (cur = convlist; cur != NULL; cur = g_slist_next(cur)) {
1911                 gchar *attribute, *key, *value;
1912                 gchar *charset, *lang, *oldvalue, *newvalue;
1913
1914                 attribute = (gchar *) cur->data;
1915                 if (!g_hash_table_lookup_extended(
1916                         table, attribute, (gpointer *)(gchar *) &key, (gpointer *)(gchar *) &value))
1917                         continue;
1918
1919                 charset = value;
1920                 if (charset == NULL)
1921                         continue;
1922                 lang = strchr(charset, '\'');
1923                 if (lang == NULL)
1924                         continue;
1925                 lang[0] = '\0';
1926                 lang++;
1927                 oldvalue = strchr(lang, '\'');
1928                 if (oldvalue == NULL)
1929                         continue;
1930                 oldvalue[0] = '\0';
1931                 oldvalue++;
1932
1933                 newvalue = conv_codeset_strdup(oldvalue, charset, CS_UTF_8);
1934
1935                 g_hash_table_remove(table, attribute);
1936                 g_free(key);
1937                 g_free(value);
1938
1939                 g_hash_table_insert(table, g_strdup(attribute), newvalue);
1940         }
1941         slist_free_strings_full(convlist);
1942
1943         g_free(params);
1944 }       
1945
1946 static void procmime_parse_content_type(const gchar *content_type, MimeInfo *mimeinfo)
1947 {
1948         cm_return_if_fail(content_type != NULL);
1949         cm_return_if_fail(mimeinfo != NULL);
1950
1951         /* RFC 2045, page 13 says that the mime subtype is MANDATORY;
1952          * if it's not available we use the default Content-Type */
1953         if ((content_type[0] == '\0') || (strchr(content_type, '/') == NULL)) {
1954                 mimeinfo->type = MIMETYPE_TEXT;
1955                 mimeinfo->subtype = g_strdup("plain");
1956                 if (g_hash_table_lookup(mimeinfo->typeparameters,
1957                                        "charset") == NULL) {
1958                         g_hash_table_insert(mimeinfo->typeparameters,
1959                                     g_strdup("charset"),
1960                                     g_strdup(
1961                                         conv_get_locale_charset_str_no_utf8()));
1962                 }
1963         } else {
1964                 gchar *type, *subtype, *params;
1965
1966                 type = g_strdup(content_type);
1967                 subtype = strchr(type, '/') + 1;
1968                 *(subtype - 1) = '\0';
1969                 if ((params = strchr(subtype, ';')) != NULL) {
1970                         params[0] = '\0';
1971                         params++;
1972                 }
1973
1974                 mimeinfo->type = procmime_get_media_type(type);
1975                 mimeinfo->subtype = g_strstrip(g_strdup(subtype));
1976
1977                 /* Get mimeinfo->typeparameters */
1978                 if (params != NULL)
1979                         parse_parameters(params, mimeinfo->typeparameters);
1980
1981                 g_free(type);
1982         }
1983 }
1984
1985 static void procmime_parse_content_disposition(const gchar *content_disposition, MimeInfo *mimeinfo)
1986 {
1987         gchar *tmp, *params;
1988
1989         cm_return_if_fail(content_disposition != NULL);
1990         cm_return_if_fail(mimeinfo != NULL);
1991
1992         tmp = g_strdup(content_disposition);
1993         if ((params = strchr(tmp, ';')) != NULL) {
1994                 params[0] = '\0';
1995                 params++;
1996         }       
1997         g_strstrip(tmp);
1998
1999         if (!g_ascii_strcasecmp(tmp, "inline")) 
2000                 mimeinfo->disposition = DISPOSITIONTYPE_INLINE;
2001         else if (!g_ascii_strcasecmp(tmp, "attachment"))
2002                 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
2003         else
2004                 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
2005         
2006         if (params != NULL)
2007                 parse_parameters(params, mimeinfo->dispositionparameters);
2008
2009         g_free(tmp);
2010 }
2011
2012
2013 static void procmime_parse_content_encoding(const gchar *content_encoding, MimeInfo *mimeinfo)
2014 {
2015         struct EncodingTable *enc_table;
2016         
2017         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
2018                 if (g_ascii_strcasecmp(enc_table->str, content_encoding) == 0) {
2019                         mimeinfo->encoding_type = enc_table->enc_type;
2020                         return;
2021                 }
2022         }
2023         mimeinfo->encoding_type = ENC_UNKNOWN;
2024         return;
2025 }
2026
2027 static GSList *registered_parsers = NULL;
2028
2029 static MimeParser *procmime_get_mimeparser_for_type(MimeMediaType type, const gchar *sub_type)
2030 {
2031         GSList *cur;
2032         for (cur = registered_parsers; cur; cur = cur->next) {
2033                 MimeParser *parser = (MimeParser *)cur->data;
2034                 if (parser->type == type && !strcmp2(parser->sub_type, sub_type))
2035                         return parser;
2036         }
2037         return NULL;
2038 }
2039
2040 void procmime_mimeparser_register(MimeParser *parser)
2041 {
2042         if (!procmime_get_mimeparser_for_type(parser->type, parser->sub_type))
2043                 registered_parsers = g_slist_append(registered_parsers, parser);
2044 }
2045
2046
2047 void procmime_mimeparser_unregister(MimeParser *parser) 
2048 {
2049         registered_parsers = g_slist_remove(registered_parsers, parser);
2050 }
2051
2052 static gboolean procmime_mimeparser_parse(MimeParser *parser, MimeInfo *mimeinfo)
2053 {
2054         cm_return_val_if_fail(parser->parse != NULL, FALSE);
2055         return parser->parse(parser, mimeinfo); 
2056 }
2057
2058 static int procmime_parse_mimepart(MimeInfo *parent,
2059                              gchar *content_type,
2060                              gchar *content_encoding,
2061                              gchar *content_description,
2062                              gchar *content_id,
2063                              gchar *content_disposition,
2064                              gchar *content_location,
2065                              const gchar *original_msgid,
2066                              const gchar *disposition_notification_hdr,
2067                              const gchar *filename,
2068                              guint offset,
2069                              guint length,
2070                              gboolean short_scan)
2071 {
2072         MimeInfo *mimeinfo;
2073         MimeParser *parser = NULL;
2074         gboolean parsed = FALSE;
2075         int result = 0;
2076
2077         /* Create MimeInfo */
2078         mimeinfo = procmime_mimeinfo_new();
2079         mimeinfo->content = MIMECONTENT_FILE;
2080
2081         if (parent != NULL) {
2082                 if (g_node_depth(parent->node) > 32) {
2083                         /* 32 is an arbitrary value
2084                          * this avoids DOSsing ourselves 
2085                          * with enormous messages
2086                          */
2087                         procmime_mimeinfo_free_all(&mimeinfo);
2088                         return -1;                      
2089                 }
2090                 g_node_append(parent->node, mimeinfo->node);
2091         }
2092         mimeinfo->data.filename = g_strdup(filename);
2093         mimeinfo->offset = offset;
2094         mimeinfo->length = length;
2095
2096         if (content_type != NULL) {
2097                 g_strchomp(content_type);
2098                 procmime_parse_content_type(content_type, mimeinfo);
2099         } else {
2100                 mimeinfo->type = MIMETYPE_TEXT;
2101                 mimeinfo->subtype = g_strdup("plain");
2102                 if (g_hash_table_lookup(mimeinfo->typeparameters,
2103                                        "charset") == NULL) {
2104                         g_hash_table_insert(mimeinfo->typeparameters,
2105                                     g_strdup("charset"),
2106                                     g_strdup(
2107                                         conv_get_locale_charset_str_no_utf8()));
2108                 }
2109         }
2110
2111         if (content_encoding != NULL) {
2112                 g_strchomp(content_encoding);
2113                 procmime_parse_content_encoding(content_encoding, mimeinfo);
2114         } else {
2115                 mimeinfo->encoding_type = ENC_UNKNOWN;
2116         }
2117
2118         if (content_description != NULL)
2119                 mimeinfo->description = g_strdup(content_description);
2120         else
2121                 mimeinfo->description = NULL;
2122
2123         if (content_id != NULL)
2124                 mimeinfo->id = g_strdup(content_id);
2125         else
2126                 mimeinfo->id = NULL;
2127
2128         if (content_location != NULL)
2129                 mimeinfo->location = g_strdup(content_location);
2130         else
2131                 mimeinfo->location = NULL;
2132
2133         if (content_disposition != NULL) {
2134                 g_strchomp(content_disposition);
2135                 procmime_parse_content_disposition(content_disposition, mimeinfo);
2136         } else
2137                 mimeinfo->disposition = DISPOSITIONTYPE_UNKNOWN;
2138
2139         /* Call parser for mime type */
2140         if ((parser = procmime_get_mimeparser_for_type(mimeinfo->type, mimeinfo->subtype)) != NULL) {
2141                 parsed = procmime_mimeparser_parse(parser, mimeinfo);
2142         } 
2143         if (!parsed) {
2144                 switch (mimeinfo->type) {
2145                 case MIMETYPE_TEXT:
2146                         if (g_ascii_strcasecmp(mimeinfo->subtype, "plain") == 0 && short_scan) {
2147                                 return 1;
2148                         }
2149                         break;
2150
2151                 case MIMETYPE_MESSAGE:
2152                         if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
2153                                 procmime_parse_message_rfc822(mimeinfo, short_scan);
2154                         }
2155                         if (g_ascii_strcasecmp(mimeinfo->subtype, "disposition-notification") == 0) {
2156                                 procmime_parse_disposition_notification(mimeinfo, 
2157                                         original_msgid, disposition_notification_hdr, short_scan);
2158                         }
2159                         break;
2160                         
2161                 case MIMETYPE_MULTIPART:
2162                         procmime_parse_multipart(mimeinfo, short_scan);
2163                         break;
2164                 
2165                 case MIMETYPE_APPLICATION:
2166                         if (g_ascii_strcasecmp(mimeinfo->subtype, "octet-stream") == 0
2167                         && original_msgid && *original_msgid 
2168                         && disposition_notification_hdr && *disposition_notification_hdr) {
2169                                 procmime_parse_disposition_notification(mimeinfo, 
2170                                         original_msgid, disposition_notification_hdr, short_scan);
2171                         }
2172                         break;
2173                 default:
2174                         break;
2175                 }
2176         }
2177
2178         return result;
2179 }
2180
2181 static gchar *typenames[] = {
2182     "text",
2183     "image",
2184     "audio",
2185     "video",
2186     "application",
2187     "message",
2188     "multipart",
2189     "unknown",
2190 };
2191
2192 static gboolean output_func(GNode *node, gpointer data)
2193 {
2194         guint i, depth;
2195         MimeInfo *mimeinfo = (MimeInfo *) node->data;
2196
2197         depth = g_node_depth(node);
2198         for (i = 0; i < depth; i++)
2199                 g_print("    ");
2200         g_print("%s/%s (offset:%d length:%d encoding: %d)\n", typenames[mimeinfo->type], mimeinfo->subtype, mimeinfo->offset, mimeinfo->length, mimeinfo->encoding_type);
2201
2202         return FALSE;
2203 }
2204
2205 static void output_mime_structure(MimeInfo *mimeinfo, int indent)
2206 {
2207         g_node_traverse(mimeinfo->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1, output_func, NULL);
2208 }
2209
2210 static MimeInfo *procmime_scan_file_with_offset(const gchar *filename, int offset, gboolean short_scan)
2211 {
2212         MimeInfo *mimeinfo;
2213         GStatBuf buf;
2214
2215         if (g_stat(filename, &buf) < 0) {
2216                 FILE_OP_ERROR(filename, "stat");
2217                 return NULL;
2218         }
2219
2220         mimeinfo = procmime_mimeinfo_new();
2221         mimeinfo->content = MIMECONTENT_FILE;
2222         mimeinfo->encoding_type = ENC_UNKNOWN;
2223         mimeinfo->type = MIMETYPE_MESSAGE;
2224         mimeinfo->subtype = g_strdup("rfc822");
2225         mimeinfo->data.filename = g_strdup(filename);
2226         mimeinfo->offset = offset;
2227         mimeinfo->length = buf.st_size - offset;
2228
2229         procmime_parse_message_rfc822(mimeinfo, short_scan);
2230         if (debug_get_mode())
2231                 output_mime_structure(mimeinfo, 0);
2232
2233         return mimeinfo;
2234 }
2235
2236 static MimeInfo *procmime_scan_file_full(const gchar *filename, gboolean short_scan)
2237 {
2238         MimeInfo *mimeinfo;
2239
2240         cm_return_val_if_fail(filename != NULL, NULL);
2241
2242         mimeinfo = procmime_scan_file_with_offset(filename, 0, short_scan);
2243
2244         return mimeinfo;
2245 }
2246
2247 MimeInfo *procmime_scan_file(const gchar *filename)
2248 {
2249         return procmime_scan_file_full(filename, FALSE);
2250 }
2251
2252 static MimeInfo *procmime_scan_file_short(const gchar *filename)
2253 {
2254         return procmime_scan_file_full(filename, TRUE);
2255 }
2256
2257 static MimeInfo *procmime_scan_queue_file_full(const gchar *filename, gboolean short_scan)
2258 {
2259         FILE *fp;
2260         MimeInfo *mimeinfo;
2261         gchar buf[BUFFSIZE];
2262         gint offset = 0;
2263
2264         cm_return_val_if_fail(filename != NULL, NULL);
2265
2266         /* Open file */
2267         if ((fp = procmime_fopen(filename, "rb")) == NULL)
2268                 return NULL;
2269         /* Skip queue header */
2270         while (SC_FGETS(buf, sizeof(buf), fp) != NULL) {
2271                 /* new way */
2272                 if ((!strncmp(buf, "X-Claws-End-Special-Headers: 1",
2273                         strlen("X-Claws-End-Special-Headers:"))) ||
2274                    (!strncmp(buf, "X-Sylpheed-End-Special-Headers: 1",
2275                         strlen("X-Sylpheed-End-Special-Headers:"))))
2276                         break;
2277                 /* old way */
2278                 if (buf[0] == '\r' || buf[0] == '\n') break;
2279                 /* from other mailers */
2280                 if (!strncmp(buf, "Date: ", 6)
2281                 ||  !strncmp(buf, "To: ", 4)
2282                 ||  !strncmp(buf, "From: ", 6)
2283                 ||  !strncmp(buf, "Subject: ", 9)) {
2284                         rewind(fp);
2285                         break;
2286                 }
2287         }
2288         offset = ftell(fp);
2289         procmime_fclose(fp);
2290
2291         mimeinfo = procmime_scan_file_with_offset(filename, offset, short_scan);
2292
2293         return mimeinfo;
2294 }
2295
2296 MimeInfo *procmime_scan_queue_file(const gchar *filename)
2297 {
2298         return procmime_scan_queue_file_full(filename, FALSE);
2299 }
2300
2301 static MimeInfo *procmime_scan_queue_file_short(const gchar *filename)
2302 {
2303         return procmime_scan_queue_file_full(filename, TRUE);
2304 }
2305
2306 typedef enum {
2307     ENC_AS_TOKEN,
2308     ENC_AS_QUOTED_STRING,
2309     ENC_AS_EXTENDED,
2310     ENC_AS_ENCWORD
2311 } EncodeAs;
2312
2313 typedef struct _ParametersData {
2314         FILE *fp;
2315         guint len;
2316         gint error;
2317 } ParametersData;
2318
2319 static void write_parameters(gpointer key, gpointer value, gpointer user_data)
2320 {
2321         gchar *param = key;
2322         gchar *val = value, *valpos, *tmp;
2323         ParametersData *pdata = (ParametersData *)user_data;
2324         GString *buf = g_string_new("");
2325         gint len;
2326
2327         EncodeAs encas = ENC_AS_TOKEN;
2328
2329         for (valpos = val; *valpos != 0; valpos++) {
2330                 if (!IS_ASCII(*valpos)) {
2331                         encas = ENC_AS_ENCWORD;
2332                         break;
2333                 }
2334             
2335                 /* CTLs */
2336                 if (((*valpos >= 0) && (*valpos < 037)) || (*valpos == 0177)) {
2337                         encas = ENC_AS_QUOTED_STRING;
2338                         continue;
2339                 }
2340
2341                 /* tspecials + SPACE */
2342                 switch (*valpos) {
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                 case '?':
2358                 case '=':
2359                         encas = ENC_AS_QUOTED_STRING;
2360                         continue;
2361                 }
2362         }
2363         
2364         switch (encas) {
2365         case ENC_AS_TOKEN:
2366                 g_string_append_printf(buf, "%s=%s", param, val);
2367                 break;
2368
2369         case ENC_AS_QUOTED_STRING:
2370                 g_string_append_printf(buf, "%s=\"%s\"", param, val);
2371                 break;
2372
2373 #if 0 /* we don't use that for now */
2374         case ENC_AS_EXTENDED:
2375                 if (!g_utf8_validate(val, -1, NULL))
2376                         g_string_append_printf(buf, "%s*=%s''", param,
2377                                 conv_get_locale_charset_str());
2378                 else
2379                         g_string_append_printf(buf, "%s*=%s''", param,
2380                                 CS_INTERNAL);
2381                 for (valpos = val; *valpos != '\0'; valpos++) {
2382                         if (IS_ASCII(*valpos) && isalnum(*valpos)) {
2383                                 g_string_append_printf(buf, "%c", *valpos);
2384                         } else {
2385                                 gchar hexstr[3] = "XX";
2386                                 get_hex_str(hexstr, *valpos);
2387                                 g_string_append_printf(buf, "%%%s", hexstr);
2388                         }
2389                 }
2390                 break;
2391 #else
2392         case ENC_AS_EXTENDED:
2393                 debug_print("Unhandled ENC_AS_EXTENDED.\n");
2394                 break;
2395 #endif
2396         case ENC_AS_ENCWORD:
2397                 len = MAX(strlen(val)*6, 512);
2398                 tmp = g_malloc(len+1);
2399                 codeconv_set_strict(TRUE);
2400                 conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2401                         prefs_common.outgoing_charset);
2402                 codeconv_set_strict(FALSE);
2403                 if (!tmp || !*tmp) {
2404                         codeconv_set_strict(TRUE);
2405                         conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2406                                 conv_get_outgoing_charset_str());
2407                         codeconv_set_strict(FALSE);
2408                 }
2409                 if (!tmp || !*tmp) {
2410                         codeconv_set_strict(TRUE);
2411                         conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2412                                 CS_UTF_8);
2413                         codeconv_set_strict(FALSE);
2414                 }
2415                 if (!tmp || !*tmp) {
2416                         conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2417                                 CS_UTF_8);
2418                 }
2419                 g_string_append_printf(buf, "%s=\"%s\"", param, tmp);
2420                 g_free(tmp);
2421                 break;
2422
2423         }
2424         
2425         if (buf->str && strlen(buf->str)) {
2426                 tmp = strstr(buf->str, "\n");
2427                 if (tmp)
2428                         len = (tmp - buf->str);
2429                 else
2430                         len = strlen(buf->str);
2431                 if (pdata->len + len > 76) {
2432                         if (fprintf(pdata->fp, ";\n %s", buf->str) < 0)
2433                                 pdata->error = TRUE;
2434                         pdata->len = strlen(buf->str) + 1;
2435                 } else {
2436                         if (fprintf(pdata->fp, "; %s", buf->str) < 0)
2437                                 pdata->error = TRUE;
2438                         pdata->len += strlen(buf->str) + 2;
2439                 }
2440         }
2441         g_string_free(buf, TRUE);
2442 }
2443
2444 #define TRY(func) { \
2445         if (!(func)) { \
2446                 return -1; \
2447         } \
2448 }
2449
2450 int procmime_write_mime_header(MimeInfo *mimeinfo, FILE *fp)
2451 {
2452         struct TypeTable *type_table;
2453         ParametersData *pdata = g_new0(ParametersData, 1);
2454         debug_print("procmime_write_mime_header\n");
2455         
2456         pdata->fp = fp;
2457         pdata->error = FALSE;
2458         for (type_table = mime_type_table; type_table->str != NULL; type_table++)
2459                 if (mimeinfo->type == type_table->type) {
2460                         gchar *buf = g_strdup_printf(
2461                                 "Content-Type: %s/%s", type_table->str, mimeinfo->subtype);
2462                         if (fprintf(fp, "%s", buf) < 0) {
2463                                 g_free(buf);
2464                                 g_free(pdata);
2465                                 return -1;
2466                         }
2467                         pdata->len = strlen(buf);
2468                         g_free(buf);
2469                         break;
2470                 }
2471         g_hash_table_foreach(mimeinfo->typeparameters, write_parameters, pdata);
2472         if (pdata->error == TRUE) {
2473                 g_free(pdata);
2474                 return -1;
2475         }
2476         g_free(pdata);
2477
2478         TRY(fprintf(fp, "\n") >= 0);
2479
2480         if (mimeinfo->encoding_type != ENC_UNKNOWN)
2481                 TRY(fprintf(fp, "Content-Transfer-Encoding: %s\n", procmime_get_encoding_str(mimeinfo->encoding_type)) >= 0);
2482
2483         if (mimeinfo->description != NULL)
2484                 TRY(fprintf(fp, "Content-Description: %s\n", mimeinfo->description) >= 0);
2485
2486         if (mimeinfo->id != NULL)
2487                 TRY(fprintf(fp, "Content-ID: %s\n", mimeinfo->id) >= 0);
2488
2489         if (mimeinfo->location != NULL)
2490                 TRY(fprintf(fp, "Content-Location: %s\n", mimeinfo->location) >= 0);
2491
2492         if (mimeinfo->disposition != DISPOSITIONTYPE_UNKNOWN) {
2493                 ParametersData *pdata = g_new0(ParametersData, 1);
2494                 gchar *buf = NULL;
2495                 if (mimeinfo->disposition == DISPOSITIONTYPE_INLINE)
2496                         buf = g_strdup("Content-Disposition: inline");
2497                 else if (mimeinfo->disposition == DISPOSITIONTYPE_ATTACHMENT)
2498                         buf = g_strdup("Content-Disposition: attachment");
2499                 else
2500                         buf = g_strdup("Content-Disposition: unknown");
2501
2502                 if (fprintf(fp, "%s", buf) < 0) {
2503                         g_free(buf);
2504                         g_free(pdata);
2505                         return -1;
2506                 }
2507                 pdata->len = strlen(buf);
2508                 g_free(buf);
2509
2510                 pdata->fp = fp;
2511                 pdata->error = FALSE;
2512                 g_hash_table_foreach(mimeinfo->dispositionparameters, write_parameters, pdata);
2513                 if (pdata->error == TRUE) {
2514                         g_free(pdata);
2515                         return -1;
2516                 }
2517                 g_free(pdata);
2518                 TRY(fprintf(fp, "\n") >= 0);
2519         }
2520
2521         TRY(fprintf(fp, "\n") >= 0);
2522         
2523         return 0;
2524 }
2525
2526 static gint procmime_write_message_rfc822(MimeInfo *mimeinfo, FILE *fp)
2527 {
2528         FILE *infp;
2529         GNode *childnode;
2530         MimeInfo *child;
2531         gchar buf[BUFFSIZE];
2532         gboolean skip = FALSE;;
2533         size_t len;
2534
2535         debug_print("procmime_write_message_rfc822\n");
2536
2537         /* write header */
2538         switch (mimeinfo->content) {
2539         case MIMECONTENT_FILE:
2540                 if ((infp = procmime_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2541                         FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2542                         return -1;
2543                 }
2544                 if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
2545                         FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
2546                         procmime_fclose(infp);
2547                         return -1;
2548                 }
2549                 while (SC_FGETS(buf, sizeof(buf), infp) == buf) {
2550                         strcrchomp(buf);
2551                         if (buf[0] == '\n' && buf[1] == '\0')
2552                                 break;
2553                         if (skip && (buf[0] == ' ' || buf[0] == '\t'))
2554                                 continue;
2555                         if (g_ascii_strncasecmp(buf, "MIME-Version:", 13) == 0 ||
2556                             g_ascii_strncasecmp(buf, "Content-Type:", 13) == 0 ||
2557                             g_ascii_strncasecmp(buf, "Content-Transfer-Encoding:", 26) == 0 ||
2558                             g_ascii_strncasecmp(buf, "Content-Description:", 20) == 0 ||
2559                             g_ascii_strncasecmp(buf, "Content-ID:", 11) == 0 ||
2560                             g_ascii_strncasecmp(buf, "Content-Location:", 17) == 0 ||
2561                             g_ascii_strncasecmp(buf, "Content-Disposition:", 20) == 0) {
2562                                 skip = TRUE;
2563                                 continue;
2564                         }
2565                         len = strlen(buf);
2566                         if (SC_FWRITE(buf, sizeof(gchar), len, fp) < len) {
2567                                 g_warning("failed to dump %zd bytes from file", len);
2568                                 procmime_fclose(infp);
2569                                 return -1;
2570                         }
2571                         skip = FALSE;
2572                 }
2573                 procmime_fclose(infp);
2574                 break;
2575
2576         case MIMECONTENT_MEM:
2577                 len = strlen(mimeinfo->data.mem);
2578                 if (SC_FWRITE(mimeinfo->data.mem, sizeof(gchar), len, fp) < len) {
2579                         g_warning("failed to dump %zd bytes from mem", len);
2580                         return -1;
2581                 }
2582                 break;
2583
2584         default:
2585                 break;
2586         }
2587
2588         childnode = mimeinfo->node->children;
2589         if (childnode == NULL)
2590                 return -1;
2591
2592         child = (MimeInfo *) childnode->data;
2593         if (fprintf(fp, "MIME-Version: 1.0\n") < 0) {
2594                 g_warning("failed to write mime version");
2595                 return -1;
2596         }
2597         if (procmime_write_mime_header(child, fp) < 0)
2598                 return -1;
2599         return procmime_write_mimeinfo(child, fp);
2600 }
2601
2602 static gint procmime_write_multipart(MimeInfo *mimeinfo, FILE *fp)
2603 {
2604         FILE *infp;
2605         GNode *childnode;
2606         gchar *boundary, *str, *str2;
2607         gchar buf[BUFFSIZE];
2608         gboolean firstboundary;
2609         size_t len;
2610
2611         debug_print("procmime_write_multipart\n");
2612
2613         boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
2614
2615         switch (mimeinfo->content) {
2616         case MIMECONTENT_FILE:
2617                 if ((infp = procmime_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2618                         FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2619                         return -1;
2620                 }
2621                 if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
2622                         FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
2623                         procmime_fclose(infp);
2624                         return -1;
2625                 }
2626                 while (SC_FGETS(buf, sizeof(buf), infp) == buf) {
2627                         if (IS_BOUNDARY(buf, boundary, strlen(boundary)))
2628                                 break;
2629                         len = strlen(buf);
2630                         if (SC_FWRITE(buf, sizeof(gchar), len, fp) < len) {
2631                                 g_warning("failed to write %zd", len);
2632                                 procmime_fclose(infp);
2633                                 return -1;
2634                         }
2635                 }
2636                 procmime_fclose(infp);
2637                 break;
2638
2639         case MIMECONTENT_MEM:
2640                 str = g_strdup(mimeinfo->data.mem);
2641                 if (((str2 = strstr(str, boundary)) != NULL) && ((str2 - str) >= 2) &&
2642                     (*(str2 - 1) == '-') && (*(str2 - 2) == '-'))
2643                         *(str2 - 2) = '\0';
2644                 len = strlen(str);
2645                 if (SC_FWRITE(str, sizeof(gchar), len, fp) < len) {
2646                         g_warning("failed to write %zd from mem", len);
2647                         g_free(str);
2648                         return -1;
2649                 }
2650                 g_free(str);
2651                 break;
2652
2653         default:
2654                 break;
2655         }
2656
2657         childnode = mimeinfo->node->children;
2658         firstboundary = TRUE;
2659         while (childnode != NULL) {
2660                 MimeInfo *child = childnode->data;
2661
2662                 if (firstboundary)
2663                         firstboundary = FALSE;
2664                 else
2665                         TRY(fprintf(fp, "\n") >= 0);
2666                         
2667                 TRY(fprintf(fp, "--%s\n", boundary) >= 0);
2668
2669                 if (procmime_write_mime_header(child, fp) < 0)
2670                         return -1;
2671                 if (procmime_write_mimeinfo(child, fp) < 0)
2672                         return -1;
2673
2674                 childnode = g_node_next_sibling(childnode);
2675         }       
2676         TRY(fprintf(fp, "\n--%s--\n", boundary) >= 0);
2677
2678         return 0;
2679 }
2680
2681 gint procmime_write_mimeinfo(MimeInfo *mimeinfo, FILE *fp)
2682 {
2683         FILE *infp;
2684         size_t len;
2685         debug_print("procmime_write_mimeinfo\n");
2686
2687         if (G_NODE_IS_LEAF(mimeinfo->node)) {
2688                 switch (mimeinfo->content) {
2689                 case MIMECONTENT_FILE:
2690                         if ((infp = procmime_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2691                                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2692                                 return -1;
2693                         }
2694                         copy_file_part_to_fp(infp, mimeinfo->offset, mimeinfo->length, fp);
2695                         procmime_fclose(infp);
2696                         return 0;
2697
2698                 case MIMECONTENT_MEM:
2699                         len = strlen(mimeinfo->data.mem);
2700                         if (SC_FWRITE(mimeinfo->data.mem, sizeof(gchar), len, fp) < len)
2701                                 return -1;
2702                         return 0;
2703
2704                 default:
2705                         return 0;
2706                 }
2707         } else {
2708                 /* Call writer for mime type */
2709                 switch (mimeinfo->type) {
2710                 case MIMETYPE_MESSAGE:
2711                         if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
2712                                 return procmime_write_message_rfc822(mimeinfo, fp);
2713                         }
2714                         break;
2715                         
2716                 case MIMETYPE_MULTIPART:
2717                         return procmime_write_multipart(mimeinfo, fp);
2718                         
2719                 default:
2720                         break;
2721                 }
2722
2723                 return -1;
2724         }
2725
2726         return 0;
2727 }
2728
2729 gchar *procmime_get_part_file_name(MimeInfo *mimeinfo)
2730 {
2731         gchar *base;
2732
2733         if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
2734                 base = g_strdup("mimetmp.html");
2735         else {
2736                 const gchar *basetmp;
2737                 gchar *basename;
2738
2739                 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
2740                 if (basetmp == NULL)
2741                         basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
2742                 if (basetmp == NULL)
2743                         basetmp = "mimetmp";
2744                 basename = g_path_get_basename(basetmp);
2745                 if (*basename == '\0') {
2746                         g_free(basename);
2747                         basename = g_strdup("mimetmp");
2748                 }
2749                 base = conv_filename_from_utf8(basename);
2750                 g_free(basename);
2751                 subst_for_shellsafe_filename(base);
2752         }
2753         
2754         return base;
2755 }
2756