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