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