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