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