2007-08-18 [colin] 2.10.0cvs130
[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: %d / %d (%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 int procmime_parse_mimepart(MimeInfo *parent,
1787                              gchar *content_type,
1788                              gchar *content_encoding,
1789                              gchar *content_description,
1790                              gchar *content_id,
1791                              gchar *content_disposition,
1792                              gchar *content_location,
1793                              const gchar *filename,
1794                              guint offset,
1795                              guint length,
1796                              gboolean short_scan)
1797 {
1798         MimeInfo *mimeinfo;
1799         int result = 0;
1800         /* Create MimeInfo */
1801         mimeinfo = procmime_mimeinfo_new();
1802         mimeinfo->content = MIMECONTENT_FILE;
1803         if (parent != NULL) {
1804                 if (g_node_depth(parent->node) > 32) {
1805                         /* 32 is an arbitrary value
1806                          * this avoids DOSsing ourselves 
1807                          * with enormous messages
1808                          */
1809                         procmime_mimeinfo_free_all(mimeinfo);
1810                         return -1;                      
1811                 }
1812                 g_node_append(parent->node, mimeinfo->node);
1813         }
1814         mimeinfo->data.filename = g_strdup(filename);
1815         mimeinfo->offset = offset;
1816         mimeinfo->length = length;
1817
1818         if (content_type != NULL) {
1819                 procmime_parse_content_type(content_type, mimeinfo);
1820         } else {
1821                 mimeinfo->type = MIMETYPE_TEXT;
1822                 mimeinfo->subtype = g_strdup("plain");
1823                 if (g_hash_table_lookup(mimeinfo->typeparameters,
1824                                        "charset") == NULL) {
1825                         g_hash_table_insert(mimeinfo->typeparameters,
1826                                     g_strdup("charset"),
1827                                     g_strdup(
1828                                         conv_get_locale_charset_str_no_utf8()));
1829                 }
1830         }
1831
1832         if (content_encoding != NULL) {
1833                 procmime_parse_content_encoding(content_encoding, mimeinfo);
1834         } else {
1835                 mimeinfo->encoding_type = ENC_UNKNOWN;
1836         }
1837
1838         if (content_description != NULL)
1839                 mimeinfo->description = g_strdup(content_description);
1840         else
1841                 mimeinfo->description = NULL;
1842
1843         if (content_id != NULL)
1844                 mimeinfo->id = g_strdup(content_id);
1845         else
1846                 mimeinfo->id = NULL;
1847
1848         if (content_location != NULL)
1849                 mimeinfo->location = g_strdup(content_location);
1850         else
1851                 mimeinfo->location = NULL;
1852
1853         if (content_disposition != NULL) 
1854                 procmime_parse_content_disposition(content_disposition, mimeinfo);
1855         else
1856                 mimeinfo->disposition = DISPOSITIONTYPE_UNKNOWN;
1857
1858         /* Call parser for mime type */
1859         switch (mimeinfo->type) {
1860                 case MIMETYPE_TEXT:
1861                         if (g_ascii_strcasecmp(mimeinfo->subtype, "plain") == 0 && short_scan) {
1862                                 return 1;
1863                         }
1864                         break;
1865
1866                 case MIMETYPE_MESSAGE:
1867                         if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
1868                                 procmime_parse_message_rfc822(mimeinfo, short_scan);
1869                         }
1870                         break;
1871                         
1872                 case MIMETYPE_MULTIPART:
1873                         procmime_parse_multipart(mimeinfo, short_scan);
1874                         break;
1875                         
1876                 default:
1877                         break;
1878         }
1879
1880         return result;
1881 }
1882
1883 static gchar *typenames[] = {
1884     "text",
1885     "image",
1886     "audio",
1887     "video",
1888     "application",
1889     "message",
1890     "multipart",
1891     "unknown",
1892 };
1893
1894 static gboolean output_func(GNode *node, gpointer data)
1895 {
1896         guint i, depth;
1897         MimeInfo *mimeinfo = (MimeInfo *) node->data;
1898
1899         depth = g_node_depth(node);
1900         for (i = 0; i < depth; i++)
1901                 printf("    ");
1902         printf("%s/%s (offset:%d length:%d encoding: %d)\n", typenames[mimeinfo->type], mimeinfo->subtype, mimeinfo->offset, mimeinfo->length, mimeinfo->encoding_type);
1903
1904         return FALSE;
1905 }
1906
1907 static void output_mime_structure(MimeInfo *mimeinfo, int indent)
1908 {
1909         g_node_traverse(mimeinfo->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1, output_func, NULL);
1910 }
1911
1912 static MimeInfo *procmime_scan_file_with_offset(const gchar *filename, int offset, gboolean short_scan)
1913 {
1914         MimeInfo *mimeinfo;
1915         struct stat buf;
1916
1917         stat(filename, &buf);
1918
1919         mimeinfo = procmime_mimeinfo_new();
1920         mimeinfo->content = MIMECONTENT_FILE;
1921         mimeinfo->encoding_type = ENC_UNKNOWN;
1922         mimeinfo->type = MIMETYPE_MESSAGE;
1923         mimeinfo->subtype = g_strdup("rfc822");
1924         mimeinfo->data.filename = g_strdup(filename);
1925         mimeinfo->offset = offset;
1926         mimeinfo->length = buf.st_size - offset;
1927
1928         procmime_parse_message_rfc822(mimeinfo, short_scan);
1929         if (debug_get_mode())
1930                 output_mime_structure(mimeinfo, 0);
1931
1932         return mimeinfo;
1933 }
1934
1935 static MimeInfo *procmime_scan_file_full(const gchar *filename, gboolean short_scan)
1936 {
1937         MimeInfo *mimeinfo;
1938
1939         g_return_val_if_fail(filename != NULL, NULL);
1940
1941         mimeinfo = procmime_scan_file_with_offset(filename, 0, short_scan);
1942
1943         return mimeinfo;
1944 }
1945
1946 MimeInfo *procmime_scan_file(const gchar *filename)
1947 {
1948         return procmime_scan_file_full(filename, FALSE);
1949 }
1950
1951 static MimeInfo *procmime_scan_file_short(const gchar *filename)
1952 {
1953         return procmime_scan_file_full(filename, TRUE);
1954 }
1955
1956 static MimeInfo *procmime_scan_queue_file_full(const gchar *filename, gboolean short_scan)
1957 {
1958         FILE *fp;
1959         MimeInfo *mimeinfo;
1960         gchar buf[BUFFSIZE];
1961         gint offset = 0;
1962
1963         g_return_val_if_fail(filename != NULL, NULL);
1964
1965         /* Open file */
1966         if ((fp = g_fopen(filename, "rb")) == NULL)
1967                 return NULL;
1968         /* Skip queue header */
1969         while (fgets(buf, sizeof(buf), fp) != NULL) {
1970                 /* new way */
1971                 if ((!strncmp(buf, "X-Claws-End-Special-Headers: 1",
1972                         strlen("X-Claws-End-Special-Headers:"))) ||
1973                    (!strncmp(buf, "X-Sylpheed-End-Special-Headers: 1",
1974                         strlen("X-Sylpheed-End-Special-Headers:"))))
1975                         break;
1976                 /* old way */
1977                 if (buf[0] == '\r' || buf[0] == '\n') break;
1978                 /* from other mailers */
1979                 if (!strncmp(buf, "Date: ", 6)
1980                 ||  !strncmp(buf, "To: ", 4)
1981                 ||  !strncmp(buf, "From: ", 6)
1982                 ||  !strncmp(buf, "Subject: ", 9)) {
1983                         rewind(fp);
1984                         break;
1985                 }
1986         }
1987         offset = ftell(fp);
1988         fclose(fp);
1989
1990         mimeinfo = procmime_scan_file_with_offset(filename, offset, short_scan);
1991
1992         return mimeinfo;
1993 }
1994
1995 MimeInfo *procmime_scan_queue_file(const gchar *filename)
1996 {
1997         return procmime_scan_queue_file_full(filename, FALSE);
1998 }
1999
2000 static MimeInfo *procmime_scan_queue_file_short(const gchar *filename)
2001 {
2002         return procmime_scan_queue_file_full(filename, TRUE);
2003 }
2004
2005 typedef enum {
2006     ENC_AS_TOKEN,
2007     ENC_AS_QUOTED_STRING,
2008     ENC_AS_EXTENDED,
2009     ENC_TO_ASCII,
2010 } EncodeAs;
2011
2012 typedef struct _ParametersData {
2013         FILE *fp;
2014         guint len;
2015         guint ascii_only;
2016 } ParametersData;
2017
2018 static void write_parameters(gpointer key, gpointer value, gpointer user_data)
2019 {
2020         gchar *param = key;
2021         gchar *val = value, *valpos, *tmp;
2022         ParametersData *pdata = (ParametersData *)user_data;
2023         GString *buf = g_string_new("");
2024
2025         EncodeAs encas = ENC_AS_TOKEN;
2026
2027         for (valpos = val; *valpos != 0; valpos++) {
2028                 if (!IS_ASCII(*valpos) || *valpos == '"') {
2029                         encas = ENC_AS_EXTENDED;
2030                         break;
2031                 }
2032             
2033                 /* CTLs */
2034                 if (((*valpos >= 0) && (*valpos < 037)) || (*valpos == 0177)) {
2035                         encas = ENC_AS_QUOTED_STRING;
2036                         continue;
2037                 }
2038
2039                 /* tspecials + SPACE */
2040                 switch (*valpos) {
2041                 case ' ':
2042                 case '(': 
2043                 case ')':
2044                 case '<':
2045                 case '>':
2046                 case '@':
2047                 case ',':
2048                 case ';':
2049                 case ':':
2050                 case '\\':
2051                 case '\'':
2052                 case '/':
2053                 case '[':
2054                 case ']':
2055                 case '?':
2056                 case '=':
2057                         encas = ENC_AS_QUOTED_STRING;
2058                         continue;
2059                 }
2060         }
2061         
2062         if (encas == ENC_AS_EXTENDED && pdata->ascii_only == TRUE) 
2063                 encas = ENC_TO_ASCII;
2064
2065         switch (encas) {
2066         case ENC_AS_TOKEN:
2067                 g_string_append_printf(buf, "%s=%s", param, val);
2068                 break;
2069
2070         case ENC_TO_ASCII:
2071                 tmp = g_strdup(val);
2072                 g_strcanon(tmp, 
2073                         " ()<>@,';:\\/[]?=.0123456789"
2074                         "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2075                         "abcdefghijklmnopqrstuvwxyz",
2076                         '_');
2077                 g_string_append_printf(buf, "%s=\"%s\"", param, tmp);
2078                 g_free(tmp);
2079                 break;
2080
2081         case ENC_AS_QUOTED_STRING:
2082                 g_string_append_printf(buf, "%s=\"%s\"", param, val);
2083                 break;
2084
2085         case ENC_AS_EXTENDED:
2086                 if (!g_utf8_validate(val, -1, NULL))
2087                         g_string_append_printf(buf, "%s*=%s''", param,
2088                                 conv_get_locale_charset_str());
2089                 else
2090                         g_string_append_printf(buf, "%s*=%s''", param,
2091                                 CS_INTERNAL);
2092                 for (valpos = val; *valpos != '\0'; valpos++) {
2093                         if (IS_ASCII(*valpos) && isalnum(*valpos)) {
2094                                 g_string_append_printf(buf, "%c", *valpos);
2095                         } else {
2096                                 gchar hexstr[3] = "XX";
2097                                 get_hex_str(hexstr, *valpos);
2098                                 g_string_append_printf(buf, "%%%s", hexstr);
2099                         }
2100                 }
2101                 break;          
2102         }
2103         
2104         if (buf->str && strlen(buf->str)) {
2105                 if (pdata->len + strlen(buf->str) + 2 > 76) {
2106                         fprintf(pdata->fp, ";\n %s", buf->str);
2107                         pdata->len = strlen(buf->str) + 1;
2108                 } else {
2109                         fprintf(pdata->fp, "; %s", buf->str);
2110                         pdata->len += strlen(buf->str) + 2;
2111                 }
2112         }
2113         g_string_free(buf, TRUE);
2114 }
2115
2116 void procmime_write_mime_header(MimeInfo *mimeinfo, FILE *fp)
2117 {
2118         struct TypeTable *type_table;
2119         ParametersData *pdata = g_new0(ParametersData, 1);
2120         debug_print("procmime_write_mime_header\n");
2121         
2122         pdata->fp = fp;
2123         pdata->ascii_only = FALSE;
2124
2125         for (type_table = mime_type_table; type_table->str != NULL; type_table++)
2126                 if (mimeinfo->type == type_table->type) {
2127                         gchar *buf = g_strdup_printf(
2128                                 "Content-Type: %s/%s", type_table->str, mimeinfo->subtype);
2129                         fprintf(fp, "%s", buf);
2130                         pdata->len = strlen(buf);
2131                         pdata->ascii_only = TRUE;
2132                         g_free(buf);
2133                         break;
2134                 }
2135         g_hash_table_foreach(mimeinfo->typeparameters, write_parameters, pdata);
2136         g_free(pdata);
2137
2138         fprintf(fp, "\n");
2139
2140         if (mimeinfo->encoding_type != ENC_UNKNOWN)
2141                 fprintf(fp, "Content-Transfer-Encoding: %s\n", procmime_get_encoding_str(mimeinfo->encoding_type));
2142
2143         if (mimeinfo->description != NULL)
2144                 fprintf(fp, "Content-Description: %s\n", mimeinfo->description);
2145
2146         if (mimeinfo->id != NULL)
2147                 fprintf(fp, "Content-ID: %s\n", mimeinfo->id);
2148
2149         if (mimeinfo->location != NULL)
2150                 fprintf(fp, "Content-Location: %s\n", mimeinfo->location);
2151
2152         if (mimeinfo->disposition != DISPOSITIONTYPE_UNKNOWN) {
2153                 ParametersData *pdata = g_new0(ParametersData, 1);
2154                 gchar *buf = NULL;
2155                 if (mimeinfo->disposition == DISPOSITIONTYPE_INLINE)
2156                         buf = g_strdup("Content-Disposition: inline");
2157                 else if (mimeinfo->disposition == DISPOSITIONTYPE_ATTACHMENT)
2158                         buf = g_strdup("Content-Disposition: attachment");
2159                 else
2160                         buf = g_strdup("Content-Disposition: unknown");
2161
2162                 fprintf(fp, "%s", buf);
2163                 pdata->len = strlen(buf);
2164                 g_free(buf);
2165
2166                 pdata->fp = fp;
2167                 pdata->ascii_only = FALSE;
2168
2169                 g_hash_table_foreach(mimeinfo->dispositionparameters, write_parameters, pdata);
2170                 g_free(pdata);
2171                 fprintf(fp, "\n");
2172         }
2173
2174         fprintf(fp, "\n");
2175 }
2176
2177 static gint procmime_write_message_rfc822(MimeInfo *mimeinfo, FILE *fp)
2178 {
2179         FILE *infp;
2180         GNode *childnode;
2181         MimeInfo *child;
2182         gchar buf[BUFFSIZE];
2183         gboolean skip = FALSE;;
2184
2185         debug_print("procmime_write_message_rfc822\n");
2186
2187         /* write header */
2188         switch (mimeinfo->content) {
2189         case MIMECONTENT_FILE:
2190                 if ((infp = g_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2191                         FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2192                         return -1;
2193                 }
2194                 fseek(infp, mimeinfo->offset, SEEK_SET);
2195                 while (fgets(buf, sizeof(buf), infp) == buf) {
2196                         strcrchomp(buf);
2197                         if (buf[0] == '\n' && buf[1] == '\0')
2198                                 break;
2199                         if (skip && (buf[0] == ' ' || buf[0] == '\t'))
2200                                 continue;
2201                         if (g_ascii_strncasecmp(buf, "Mime-Version:", 13) == 0 ||
2202                             g_ascii_strncasecmp(buf, "Content-Type:", 13) == 0 ||
2203                             g_ascii_strncasecmp(buf, "Content-Transfer-Encoding:", 26) == 0 ||
2204                             g_ascii_strncasecmp(buf, "Content-Description:", 20) == 0 ||
2205                             g_ascii_strncasecmp(buf, "Content-ID:", 11) == 0 ||
2206                             g_ascii_strncasecmp(buf, "Content-Location:", 17) == 0 ||
2207                             g_ascii_strncasecmp(buf, "Content-Disposition:", 20) == 0) {
2208                                 skip = TRUE;
2209                                 continue;
2210                         }
2211                         fwrite(buf, sizeof(gchar), strlen(buf), fp);
2212                         skip = FALSE;
2213                 }
2214                 fclose(infp);
2215                 break;
2216
2217         case MIMECONTENT_MEM:
2218                 fwrite(mimeinfo->data.mem, 
2219                                 sizeof(gchar), 
2220                                 strlen(mimeinfo->data.mem), 
2221                                 fp);
2222                 break;
2223
2224         default:
2225                 break;
2226         }
2227
2228         childnode = mimeinfo->node->children;
2229         if (childnode == NULL)
2230                 return -1;
2231
2232         child = (MimeInfo *) childnode->data;
2233         fprintf(fp, "Mime-Version: 1.0\n");
2234         procmime_write_mime_header(child, fp);
2235         return procmime_write_mimeinfo(child, fp);
2236 }
2237
2238 static gint procmime_write_multipart(MimeInfo *mimeinfo, FILE *fp)
2239 {
2240         FILE *infp;
2241         GNode *childnode;
2242         gchar *boundary, *str, *str2;
2243         gchar buf[BUFFSIZE];
2244         gboolean firstboundary;
2245
2246         debug_print("procmime_write_multipart\n");
2247
2248         boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
2249
2250         switch (mimeinfo->content) {
2251         case MIMECONTENT_FILE:
2252                 if ((infp = g_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2253                         FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2254                         return -1;
2255                 }
2256                 fseek(infp, mimeinfo->offset, SEEK_SET);
2257                 while (fgets(buf, sizeof(buf), infp) == buf) {
2258                         if (IS_BOUNDARY(buf, boundary, strlen(boundary)))
2259                                 break;
2260                         fwrite(buf, sizeof(gchar), strlen(buf), fp);
2261                 }
2262                 fclose(infp);
2263                 break;
2264
2265         case MIMECONTENT_MEM:
2266                 str = g_strdup(mimeinfo->data.mem);
2267                 if (((str2 = strstr(str, boundary)) != NULL) && ((str2 - str) >= 2) &&
2268                     (*(str2 - 1) == '-') && (*(str2 - 2) == '-'))
2269                         *(str2 - 2) = '\0';
2270                 fwrite(str, sizeof(gchar), strlen(str), fp);
2271                 g_free(str);
2272                 break;
2273
2274         default:
2275                 break;
2276         }
2277
2278         childnode = mimeinfo->node->children;
2279         firstboundary = TRUE;
2280         while (childnode != NULL) {
2281                 MimeInfo *child = childnode->data;
2282
2283                 if (firstboundary)
2284                         firstboundary = FALSE;
2285                 else
2286                         fprintf(fp, "\n");
2287                 fprintf(fp, "--%s\n", boundary);
2288
2289                 procmime_write_mime_header(child, fp);
2290                 if (procmime_write_mimeinfo(child, fp) < 0)
2291                         return -1;
2292
2293                 childnode = g_node_next_sibling(childnode);
2294         }       
2295         fprintf(fp, "\n--%s--\n", boundary);
2296
2297         return 0;
2298 }
2299
2300 gint procmime_write_mimeinfo(MimeInfo *mimeinfo, FILE *fp)
2301 {
2302         FILE *infp;
2303
2304         debug_print("procmime_write_mimeinfo\n");
2305
2306         if (G_NODE_IS_LEAF(mimeinfo->node)) {
2307                 switch (mimeinfo->content) {
2308                 case MIMECONTENT_FILE:
2309                         if ((infp = g_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2310                                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2311                                 return -1;
2312                         }
2313                         copy_file_part_to_fp(infp, mimeinfo->offset, mimeinfo->length, fp);
2314                         fclose(infp);
2315                         return 0;
2316
2317                 case MIMECONTENT_MEM:
2318                         fwrite(mimeinfo->data.mem, 
2319                                         sizeof(gchar), 
2320                                         strlen(mimeinfo->data.mem), 
2321                                         fp);
2322                         return 0;
2323
2324                 default:
2325                         return 0;
2326                 }
2327         } else {
2328                 /* Call writer for mime type */
2329                 switch (mimeinfo->type) {
2330                 case MIMETYPE_MESSAGE:
2331                         if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
2332                                 return procmime_write_message_rfc822(mimeinfo, fp);
2333                         }
2334                         break;
2335                         
2336                 case MIMETYPE_MULTIPART:
2337                         return procmime_write_multipart(mimeinfo, fp);
2338                         
2339                 default:
2340                         break;
2341                 }
2342
2343                 return -1;
2344         }
2345
2346         return 0;
2347 }
2348
2349 gchar *procmime_get_part_file_name(MimeInfo *mimeinfo)
2350 {
2351         gchar *base;
2352
2353         if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
2354                 base = g_strdup("mimetmp.html");
2355         else {
2356                 const gchar *basetmp;
2357                 gchar *basename;
2358
2359                 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
2360                 if (basetmp == NULL)
2361                         basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
2362                 if (basetmp == NULL)
2363                         basetmp = "mimetmp";
2364                 basename = g_path_get_basename(basetmp);
2365                 if (*basename == '\0') {
2366                         g_free(basename);
2367                         basename = g_strdup("mimetmp");
2368                 }
2369                 base = conv_filename_from_utf8(basename);
2370                 g_free(basename);
2371                 subst_for_shellsafe_filename(base);
2372         }
2373         
2374         return base;
2375 }
2376