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