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