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