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