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