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