2007-07-26 [colin] 2.10.0cvs68
[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 static void output_mime_structure(MimeInfo *mimeinfo, int indent);
842 /* search the first text part of (multipart) MIME message,
843    decode, convert it and output to outfp. */
844 FILE *procmime_get_first_text_content(MsgInfo *msginfo)
845 {
846         FILE *outfp = NULL;
847         MimeInfo *mimeinfo, *partinfo;
848         START_TIMING("");
849         g_return_val_if_fail(msginfo != NULL, NULL);
850
851         mimeinfo = procmime_scan_message_short(msginfo);
852         if (!mimeinfo) return NULL;
853
854 output_mime_structure(mimeinfo, 0);
855
856         partinfo = mimeinfo;
857         while (partinfo && partinfo->type != MIMETYPE_TEXT) {
858                 partinfo = procmime_mimeinfo_next(partinfo);
859         }
860         if (partinfo)
861                 outfp = procmime_get_text_content(partinfo);
862
863         procmime_mimeinfo_free_all(mimeinfo);
864         END_TIMING();
865         return outfp;
866 }
867
868
869 static gboolean find_encrypted_func(GNode *node, gpointer data)
870 {
871         MimeInfo *mimeinfo = (MimeInfo *) node->data;
872         MimeInfo **encinfo = (MimeInfo **) data;
873         
874         if (privacy_mimeinfo_is_encrypted(mimeinfo)) {
875                 *encinfo = mimeinfo;
876                 return TRUE;
877         }
878         
879         return FALSE;
880 }
881
882 static MimeInfo *find_encrypted_part(MimeInfo *rootinfo)
883 {
884         MimeInfo *encinfo = NULL;
885
886         g_node_traverse(rootinfo->node, G_IN_ORDER, G_TRAVERSE_ALL, -1,
887                 find_encrypted_func, &encinfo);
888         
889         return encinfo;
890 }
891
892 /* search the first encrypted text part of (multipart) MIME message,
893    decode, convert it and output to outfp. */
894 FILE *procmime_get_first_encrypted_text_content(MsgInfo *msginfo)
895 {
896         FILE *outfp = NULL;
897         MimeInfo *mimeinfo, *partinfo, *encinfo;
898
899         g_return_val_if_fail(msginfo != NULL, NULL);
900
901         mimeinfo = procmime_scan_message(msginfo);
902         if (!mimeinfo) {
903                 return NULL;
904         }
905
906         partinfo = mimeinfo;
907         if ((encinfo = find_encrypted_part(partinfo)) != NULL) {
908                 debug_print("decrypting message part\n");
909                 if (privacy_mimeinfo_decrypt(encinfo) < 0) {
910                         alertpanel_error(_("Couldn't decrypt: %s"),
911                                 privacy_get_error());
912                         return NULL;
913                 }
914         }
915         partinfo = mimeinfo;
916         while (partinfo && partinfo->type != MIMETYPE_TEXT) {
917                 partinfo = procmime_mimeinfo_next(partinfo);
918         }
919
920         if (partinfo)
921                 outfp = procmime_get_text_content(partinfo);
922
923         procmime_mimeinfo_free_all(mimeinfo);
924
925         return outfp;
926 }
927
928 gboolean procmime_msginfo_is_encrypted(MsgInfo *msginfo)
929 {
930         MimeInfo *mimeinfo, *partinfo;
931         gboolean result = FALSE;
932
933         g_return_val_if_fail(msginfo != NULL, FALSE);
934
935         mimeinfo = procmime_scan_message(msginfo);
936         if (!mimeinfo) {
937                 return FALSE;
938         }
939
940         partinfo = mimeinfo;
941         result = (find_encrypted_part(partinfo) != NULL);
942         procmime_mimeinfo_free_all(mimeinfo);
943
944         return result;
945 }
946
947 gboolean procmime_find_string_part(MimeInfo *mimeinfo, const gchar *filename,
948                                    const gchar *str, StrFindFunc find_func)
949 {
950         FILE *outfp;
951         gchar buf[BUFFSIZE];
952
953         g_return_val_if_fail(mimeinfo != NULL, FALSE);
954         g_return_val_if_fail(mimeinfo->type == MIMETYPE_TEXT, FALSE);
955         g_return_val_if_fail(str != NULL, FALSE);
956         g_return_val_if_fail(find_func != NULL, FALSE);
957
958         outfp = procmime_get_text_content(mimeinfo);
959
960         if (!outfp)
961                 return FALSE;
962
963         while (fgets(buf, sizeof(buf), outfp) != NULL) {
964                 strretchomp(buf);
965                 if (find_func(buf, str)) {
966                         fclose(outfp);
967                         return TRUE;
968                 }
969         }
970
971         fclose(outfp);
972
973         return FALSE;
974 }
975
976 gboolean procmime_find_string(MsgInfo *msginfo, const gchar *str,
977                               StrFindFunc find_func)
978 {
979         MimeInfo *mimeinfo;
980         MimeInfo *partinfo;
981         gchar *filename;
982         gboolean found = FALSE;
983
984         g_return_val_if_fail(msginfo != NULL, FALSE);
985         g_return_val_if_fail(str != NULL, FALSE);
986         g_return_val_if_fail(find_func != NULL, FALSE);
987
988         filename = procmsg_get_message_file(msginfo);
989         if (!filename) return FALSE;
990         mimeinfo = procmime_scan_message(msginfo);
991
992         for (partinfo = mimeinfo; partinfo != NULL;
993              partinfo = procmime_mimeinfo_next(partinfo)) {
994                 if (partinfo->type == MIMETYPE_TEXT) {
995                         if (procmime_find_string_part
996                                 (partinfo, filename, str, find_func) == TRUE) {
997                                 found = TRUE;
998                                 break;
999                         }
1000                 }
1001         }
1002
1003         procmime_mimeinfo_free_all(mimeinfo);
1004         g_free(filename);
1005
1006         return found;
1007 }
1008
1009 gchar *procmime_get_tmp_file_name(MimeInfo *mimeinfo)
1010 {
1011         static guint32 id = 0;
1012         gchar *base;
1013         gchar *filename;
1014         gchar f_prefix[10];
1015
1016         g_return_val_if_fail(mimeinfo != NULL, NULL);
1017
1018         g_snprintf(f_prefix, sizeof(f_prefix), "%08x.", id++);
1019
1020         if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
1021                 base = g_strdup("mimetmp.html");
1022         else {
1023                 const gchar *basetmp;
1024
1025                 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
1026                 if (basetmp == NULL)
1027                         basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
1028                 if (basetmp == NULL)
1029                         basetmp = "mimetmp";
1030                 basetmp = g_path_get_basename(basetmp);
1031                 if (*basetmp == '\0') 
1032                         basetmp = g_strdup("mimetmp");
1033                 base = conv_filename_from_utf8(basetmp);
1034                 g_free((gchar*)basetmp);
1035                 subst_for_shellsafe_filename(base);
1036         }
1037
1038         filename = g_strconcat(get_mime_tmp_dir(), G_DIR_SEPARATOR_S,
1039                                f_prefix, base, NULL);
1040
1041         g_free(base);
1042         
1043         return filename;
1044 }
1045
1046 static GList *mime_type_list = NULL;
1047
1048 gchar *procmime_get_mime_type(const gchar *filename)
1049 {
1050         static GHashTable *mime_type_table = NULL;
1051         MimeType *mime_type;
1052         const gchar *p;
1053         gchar *ext = NULL;
1054         gchar *base;
1055
1056         if (!mime_type_table) {
1057                 mime_type_table = procmime_get_mime_type_table();
1058                 if (!mime_type_table) return NULL;
1059         }
1060
1061         base = g_path_get_basename(filename);
1062         if ((p = strrchr(base, '.')) != NULL)
1063                 Xstrdup_a(ext, p + 1, p = NULL );
1064         g_free(base);
1065         if (!p) return NULL;
1066
1067         g_strdown(ext);
1068         mime_type = g_hash_table_lookup(mime_type_table, ext);
1069         if (mime_type) {
1070                 gchar *str;
1071
1072                 str = g_strconcat(mime_type->type, "/", mime_type->sub_type,
1073                                   NULL);
1074                 return str;
1075         }
1076
1077         return NULL;
1078 }
1079
1080 static guint procmime_str_hash(gconstpointer gptr)
1081 {
1082         guint hash_result = 0;
1083         const char *str;
1084
1085         for (str = gptr; str && *str; str++) {
1086                 if (isupper(*str)) hash_result += (*str + ' ');
1087                 else hash_result += *str;
1088         }
1089
1090         return hash_result;
1091 }
1092
1093 static gint procmime_str_equal(gconstpointer gptr1, gconstpointer gptr2)
1094 {
1095         const char *str1 = gptr1;
1096         const char *str2 = gptr2;
1097
1098         return !g_utf8_collate(str1, str2);
1099 }
1100
1101 static GHashTable *procmime_get_mime_type_table(void)
1102 {
1103         GHashTable *table = NULL;
1104         GList *cur;
1105         MimeType *mime_type;
1106         gchar **exts;
1107
1108         if (!mime_type_list) {
1109                 mime_type_list = procmime_get_mime_type_list();
1110                 if (!mime_type_list) return NULL;
1111         }
1112
1113         table = g_hash_table_new(procmime_str_hash, procmime_str_equal);
1114
1115         for (cur = mime_type_list; cur != NULL; cur = cur->next) {
1116                 gint i;
1117                 gchar *key;
1118
1119                 mime_type = (MimeType *)cur->data;
1120
1121                 if (!mime_type->extension) continue;
1122
1123                 exts = g_strsplit(mime_type->extension, " ", 16);
1124                 for (i = 0; exts[i] != NULL; i++) {
1125                         /* make the key case insensitive */
1126                         g_strdown(exts[i]);
1127                         /* use previously dup'd key on overwriting */
1128                         if (g_hash_table_lookup(table, exts[i]))
1129                                 key = exts[i];
1130                         else
1131                                 key = g_strdup(exts[i]);
1132                         g_hash_table_insert(table, key, mime_type);
1133                 }
1134                 g_strfreev(exts);
1135         }
1136
1137         return table;
1138 }
1139
1140 GList *procmime_get_mime_type_list(void)
1141 {
1142         GList *list = NULL;
1143         FILE *fp;
1144         gchar buf[BUFFSIZE];
1145         gchar *p;
1146         gchar *delim;
1147         MimeType *mime_type;
1148         gboolean fp_is_glob_file = TRUE;
1149
1150         if (mime_type_list) 
1151                 return mime_type_list;
1152         
1153 #if defined(__NetBSD__)
1154         if ((fp = g_fopen(DATAROOTDIR "/mime/globs", "rb")) == NULL) 
1155 #else
1156         if ((fp = g_fopen("/usr/share/mime/globs", "rb")) == NULL) 
1157 #endif
1158         {
1159                 fp_is_glob_file = FALSE;
1160                 if ((fp = g_fopen("/etc/mime.types", "rb")) == NULL) {
1161                         if ((fp = g_fopen(SYSCONFDIR "/mime.types", "rb")) 
1162                                 == NULL) {
1163                                 FILE_OP_ERROR(SYSCONFDIR "/mime.types", 
1164                                         "fopen");
1165                                 return NULL;
1166                         }
1167                 }
1168         }
1169
1170         while (fgets(buf, sizeof(buf), fp) != NULL) {
1171                 p = strchr(buf, '#');
1172                 if (p) *p = '\0';
1173                 g_strstrip(buf);
1174
1175                 p = buf;
1176                 
1177                 if (fp_is_glob_file) {
1178                         while (*p && !g_ascii_isspace(*p) && (*p!=':')) p++;
1179                 } else {
1180                         while (*p && !g_ascii_isspace(*p)) p++;
1181                 }
1182
1183                 if (*p) {
1184                         *p = '\0';
1185                         p++;
1186                 }
1187                 delim = strchr(buf, '/');
1188                 if (delim == NULL) continue;
1189                 *delim = '\0';
1190
1191                 mime_type = g_new(MimeType, 1);
1192                 mime_type->type = g_strdup(buf);
1193                 mime_type->sub_type = g_strdup(delim + 1);
1194
1195                 if (fp_is_glob_file) {
1196                         while (*p && (g_ascii_isspace(*p)||(*p=='*')||(*p=='.'))) p++;
1197                 } else {
1198                         while (*p && g_ascii_isspace(*p)) p++;
1199                 }
1200
1201                 if (*p)
1202                         mime_type->extension = g_strdup(p);
1203                 else
1204                         mime_type->extension = NULL;
1205
1206                 list = g_list_append(list, mime_type);
1207         }
1208
1209         fclose(fp);
1210
1211         if (!list)
1212                 g_warning("Can't read mime.types\n");
1213
1214         return list;
1215 }
1216
1217 EncodingType procmime_get_encoding_for_charset(const gchar *charset)
1218 {
1219         if (!charset)
1220                 return ENC_8BIT;
1221         else if (!g_ascii_strncasecmp(charset, "ISO-2022-", 9) ||
1222                  !g_ascii_strcasecmp(charset, "US-ASCII"))
1223                 return ENC_7BIT;
1224         else if (!g_ascii_strcasecmp(charset, "ISO-8859-5") ||
1225                  !g_ascii_strncasecmp(charset, "KOI8-", 5) ||
1226                  !g_ascii_strcasecmp(charset, "Windows-1251"))
1227                 return ENC_8BIT;
1228         else if (!g_ascii_strncasecmp(charset, "ISO-8859-", 9))
1229                 return ENC_QUOTED_PRINTABLE;
1230         else if (!g_ascii_strncasecmp(charset, "UTF-8", 5))
1231                 return ENC_QUOTED_PRINTABLE;
1232         else 
1233                 return ENC_8BIT;
1234 }
1235
1236 EncodingType procmime_get_encoding_for_text_file(const gchar *file, gboolean *has_binary)
1237 {
1238         FILE *fp;
1239         guchar buf[BUFFSIZE];
1240         size_t len;
1241         size_t octet_chars = 0;
1242         size_t total_len = 0;
1243         gfloat octet_percentage;
1244         gboolean force_b64 = FALSE;
1245
1246         if ((fp = g_fopen(file, "rb")) == NULL) {
1247                 FILE_OP_ERROR(file, "fopen");
1248                 return ENC_UNKNOWN;
1249         }
1250
1251         while ((len = fread(buf, sizeof(guchar), sizeof(buf), fp)) > 0) {
1252                 guchar *p;
1253                 gint i;
1254
1255                 for (p = buf, i = 0; i < len; ++p, ++i) {
1256                         if (*p & 0x80)
1257                                 ++octet_chars;
1258                         if (*p == '\0') {
1259                                 force_b64 = TRUE;
1260                                 *has_binary = TRUE;
1261                         }
1262                 }
1263                 total_len += len;
1264         }
1265
1266         fclose(fp);
1267         
1268         if (total_len > 0)
1269                 octet_percentage = (gfloat)octet_chars / (gfloat)total_len;
1270         else
1271                 octet_percentage = 0.0;
1272
1273         debug_print("procmime_get_encoding_for_text_file(): "
1274                     "8bit chars: %d / %d (%f%%)\n", octet_chars, total_len,
1275                     100.0 * octet_percentage);
1276
1277         if (octet_percentage > 0.20 || force_b64) {
1278                 debug_print("using BASE64\n");
1279                 return ENC_BASE64;
1280         } else if (octet_chars > 0) {
1281                 debug_print("using quoted-printable\n");
1282                 return ENC_QUOTED_PRINTABLE;
1283         } else {
1284                 debug_print("using 7bit\n");
1285                 return ENC_7BIT;
1286         }
1287 }
1288
1289 struct EncodingTable 
1290 {
1291         gchar *str;
1292         EncodingType enc_type;
1293 };
1294
1295 struct EncodingTable encoding_table[] = {
1296         {"7bit", ENC_7BIT},
1297         {"8bit", ENC_8BIT},
1298         {"binary", ENC_BINARY},
1299         {"quoted-printable", ENC_QUOTED_PRINTABLE},
1300         {"base64", ENC_BASE64},
1301         {"x-uuencode", ENC_UNKNOWN},
1302         {NULL, ENC_UNKNOWN},
1303 };
1304
1305 const gchar *procmime_get_encoding_str(EncodingType encoding)
1306 {
1307         struct EncodingTable *enc_table;
1308         
1309         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1310                 if (enc_table->enc_type == encoding)
1311                         return enc_table->str;
1312         }
1313         return NULL;
1314 }
1315
1316 /* --- NEW MIME STUFF --- */
1317 struct TypeTable
1318 {
1319         gchar *str;
1320         MimeMediaType type;
1321 };
1322
1323 static struct TypeTable mime_type_table[] = {
1324         {"text", MIMETYPE_TEXT},
1325         {"image", MIMETYPE_IMAGE},
1326         {"audio", MIMETYPE_AUDIO},
1327         {"video", MIMETYPE_VIDEO},
1328         {"application", MIMETYPE_APPLICATION},
1329         {"message", MIMETYPE_MESSAGE},
1330         {"multipart", MIMETYPE_MULTIPART},
1331         {NULL, 0},
1332 };
1333
1334 const gchar *procmime_get_media_type_str(MimeMediaType type)
1335 {
1336         struct TypeTable *type_table;
1337         
1338         for (type_table = mime_type_table; type_table->str != NULL; type_table++) {
1339                 if (type_table->type == type)
1340                         return type_table->str;
1341         }
1342         return NULL;
1343 }
1344
1345 MimeMediaType procmime_get_media_type(const gchar *str)
1346 {
1347         struct TypeTable *typetablearray;
1348
1349         for (typetablearray = mime_type_table; typetablearray->str != NULL; typetablearray++)
1350                 if (g_ascii_strncasecmp(str, typetablearray->str, strlen(typetablearray->str)) == 0)
1351                         return typetablearray->type;
1352
1353         return MIMETYPE_UNKNOWN;
1354 }
1355
1356 /*!
1357  *\brief        Safe wrapper for content type string.
1358  *
1359  *\return       const gchar * Pointer to content type string. 
1360  */
1361 gchar *procmime_get_content_type_str(MimeMediaType type,
1362                                            const char *subtype)
1363 {
1364         const gchar *type_str = NULL;
1365
1366         if (subtype == NULL || !(type_str = procmime_get_media_type_str(type)))
1367                 return g_strdup("unknown");
1368         return g_strdup_printf("%s/%s", type_str, subtype);
1369 }
1370
1371 static int procmime_parse_mimepart(MimeInfo *parent,
1372                              gchar *content_type,
1373                              gchar *content_encoding,
1374                              gchar *content_description,
1375                              gchar *content_id,
1376                              gchar *content_disposition,
1377                              gchar *content_location,
1378                              const gchar *filename,
1379                              guint offset,
1380                              guint length,
1381                              gboolean short_scan);
1382
1383 static void procmime_parse_message_rfc822(MimeInfo *mimeinfo, gboolean short_scan)
1384 {
1385         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1386                                 {"Content-Transfer-Encoding:",
1387                                                    NULL, FALSE},
1388                                 {"Content-Description:",
1389                                                    NULL, TRUE},
1390                                 {"Content-ID:",
1391                                                    NULL, TRUE},
1392                                 {"Content-Disposition:",
1393                                                    NULL, TRUE},
1394                                 {"Content-Location:",
1395                                                    NULL, TRUE},
1396                                 {"MIME-Version:",
1397                                                    NULL, TRUE},
1398                                 {NULL,             NULL, FALSE}};
1399         guint content_start, i;
1400         FILE *fp;
1401         gchar *tmp;
1402         gint len = 0;
1403
1404         procmime_decode_content(mimeinfo);
1405
1406         fp = g_fopen(mimeinfo->data.filename, "rb");
1407         if (fp == NULL) {
1408                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1409                 return;
1410         }
1411         fseek(fp, mimeinfo->offset, SEEK_SET);
1412         procheader_get_header_fields(fp, hentry);
1413         if (hentry[0].body != NULL) {
1414                 tmp = conv_unmime_header(hentry[0].body, NULL);
1415                 g_free(hentry[0].body);
1416                 hentry[0].body = tmp;
1417         }                
1418         if (hentry[2].body != NULL) {
1419                 tmp = conv_unmime_header(hentry[2].body, NULL);
1420                 g_free(hentry[2].body);
1421                 hentry[2].body = tmp;
1422         }                
1423         if (hentry[4].body != NULL) {
1424                 tmp = conv_unmime_header(hentry[4].body, NULL);
1425                 g_free(hentry[4].body);
1426                 hentry[4].body = tmp;
1427         }                
1428         if (hentry[5].body != NULL) {
1429                 tmp = conv_unmime_header(hentry[5].body, NULL);
1430                 g_free(hentry[5].body);
1431                 hentry[5].body = tmp;
1432         }                
1433         content_start = ftell(fp);
1434         fclose(fp);
1435         
1436         len = mimeinfo->length - (content_start - mimeinfo->offset);
1437         if (len < 0)
1438                 len = 0;
1439         procmime_parse_mimepart(mimeinfo,
1440                                 hentry[0].body, hentry[1].body,
1441                                 hentry[2].body, hentry[3].body,
1442                                 hentry[4].body, hentry[5].body,
1443                                 mimeinfo->data.filename, content_start,
1444                                 len, short_scan);
1445         
1446         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1447                 g_free(hentry[i].body);
1448                 hentry[i].body = NULL;
1449         }
1450 }
1451
1452 static void procmime_parse_multipart(MimeInfo *mimeinfo, gboolean short_scan)
1453 {
1454         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1455                                 {"Content-Transfer-Encoding:",
1456                                                    NULL, FALSE},
1457                                 {"Content-Description:",
1458                                                    NULL, TRUE},
1459                                 {"Content-ID:",
1460                                                    NULL, TRUE},
1461                                 {"Content-Disposition:",
1462                                                    NULL, TRUE},
1463                                 {"Content-Location:",
1464                                                    NULL, TRUE},
1465                                 {NULL,             NULL, FALSE}};
1466         gchar *p, *tmp;
1467         gchar *boundary;
1468         gint boundary_len = 0, lastoffset = -1, i;
1469         gchar buf[BUFFSIZE];
1470         FILE *fp;
1471         int result = 0;
1472         gboolean done = FALSE;
1473
1474         boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
1475         if (!boundary)
1476                 return;
1477         boundary_len = strlen(boundary);
1478
1479         procmime_decode_content(mimeinfo);
1480
1481         fp = g_fopen(mimeinfo->data.filename, "rb");
1482         if (fp == NULL) {
1483                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1484                 return;
1485         }
1486         fseek(fp, mimeinfo->offset, SEEK_SET);
1487         while ((p = fgets(buf, sizeof(buf), fp)) != NULL && result == 0) {
1488                 if (ftell(fp) - 1 > (mimeinfo->offset + mimeinfo->length))
1489                         break;
1490
1491                 if (IS_BOUNDARY(buf, boundary, boundary_len)) {
1492                         if (lastoffset != -1) {
1493                                 gint len = (ftell(fp) - strlen(buf)) - lastoffset - 1;
1494                                 if (len < 0)
1495                                         len = 0;
1496                                 result = procmime_parse_mimepart(mimeinfo,
1497                                                         hentry[0].body, hentry[1].body,
1498                                                         hentry[2].body, hentry[3].body, 
1499                                                         hentry[4].body, hentry[5].body,
1500                                                         mimeinfo->data.filename, lastoffset,
1501                                                         len, short_scan);
1502                                 if (result == 1 && short_scan) {
1503                                         done = TRUE;
1504                                         break;
1505                                 }
1506                         }
1507                         
1508                         if (buf[2 + boundary_len]     == '-' &&
1509                             buf[2 + boundary_len + 1] == '-')
1510                                 break;
1511
1512                         for (i = 0; i < (sizeof hentry / sizeof hentry[0]) ; i++) {
1513                                 g_free(hentry[i].body);
1514                                 hentry[i].body = NULL;
1515                         }
1516                         procheader_get_header_fields(fp, hentry);
1517                         if (hentry[0].body != NULL) {
1518                                 tmp = conv_unmime_header(hentry[0].body, NULL);
1519                                 g_free(hentry[0].body);
1520                                 hentry[0].body = tmp;
1521                         }                
1522                         if (hentry[2].body != NULL) {
1523                                 tmp = conv_unmime_header(hentry[2].body, NULL);
1524                                 g_free(hentry[2].body);
1525                                 hentry[2].body = tmp;
1526                         }                
1527                         if (hentry[4].body != NULL) {
1528                                 tmp = conv_unmime_header(hentry[4].body, NULL);
1529                                 g_free(hentry[4].body);
1530                                 hentry[4].body = tmp;
1531                         }                
1532                         if (hentry[5].body != NULL) {
1533                                 tmp = conv_unmime_header(hentry[5].body, NULL);
1534                                 g_free(hentry[5].body);
1535                                 hentry[5].body = tmp;
1536                         }                
1537                         lastoffset = ftell(fp);
1538                 }
1539         }
1540         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1541                 g_free(hentry[i].body);
1542                 hentry[i].body = NULL;
1543         }
1544         fclose(fp);
1545 }
1546
1547 static void parse_parameters(const gchar *parameters, GHashTable *table)
1548 {
1549         gchar *params, *param, *next;
1550         GSList *convlist = NULL, *concatlist = NULL, *cur;
1551
1552         params = g_strdup(parameters);
1553         param = params;
1554         next = params;
1555         for (; next != NULL; param = next) {
1556                 gchar *attribute, *value, *tmp;
1557                 gint len;
1558                 gboolean convert = FALSE;
1559
1560                 next = strchr_with_skip_quote(param, '"', ';');
1561                 if (next != NULL) {
1562                         next[0] = '\0';
1563                         next++;
1564                 }
1565
1566                 g_strstrip(param);
1567
1568                 attribute = param;
1569                 value = strchr(attribute, '=');
1570                 if (value == NULL)
1571                         continue;
1572
1573                 value[0] = '\0';
1574                 value++;
1575                 while (value[0] == ' ')
1576                         value++;
1577
1578                 g_strdown(attribute);
1579
1580                 len = strlen(attribute);
1581                 if (attribute[len - 1] == '*') {
1582                         gchar *srcpos, *dstpos, *endpos;
1583
1584                         convert = TRUE;
1585                         attribute[len - 1] = '\0';
1586
1587                         srcpos = value;
1588                         dstpos = value;
1589                         endpos = value + strlen(value);
1590                         while (srcpos < endpos) {
1591                                 if (*srcpos != '%')
1592                                         *dstpos = *srcpos;
1593                                 else {
1594                                         guchar dstvalue;
1595
1596                                         if (!get_hex_value(&dstvalue, srcpos[1], srcpos[2]))
1597                                                 *dstpos = '?';
1598                                         else
1599                                                 *dstpos = dstvalue;
1600                                         srcpos += 2;
1601                                 }
1602                                 srcpos++;
1603                                 dstpos++;
1604                         }
1605                         *dstpos = '\0';
1606                 } else {
1607                         if (value[0] == '"')
1608                                 extract_quote(value, '"');
1609                         else if ((tmp = strchr(value, ' ')) != NULL)
1610                                 *tmp = '\0';
1611                 }
1612
1613                 if (attribute) {
1614                         while (attribute[0] == ' ')
1615                                 attribute++;
1616                         while (attribute[strlen(attribute)-1] == ' ') 
1617                                 attribute[strlen(attribute)-1] = '\0';
1618                 } 
1619                 if (value) {
1620                         while (value[0] == ' ')
1621                                 value++;
1622                         while (value[strlen(value)-1] == ' ') 
1623                                 value[strlen(value)-1] = '\0';
1624                 }               
1625                 if (strrchr(attribute, '*') != NULL) {
1626                         gchar *tmpattr;
1627
1628                         tmpattr = g_strdup(attribute);
1629                         tmp = strrchr(tmpattr, '*');
1630                         tmp[0] = '\0';
1631
1632                         if ((tmp[1] == '0') && (tmp[2] == '\0') && 
1633                             (g_slist_find_custom(concatlist, attribute, g_str_equal) == NULL))
1634                                 concatlist = g_slist_prepend(concatlist, g_strdup(tmpattr));
1635
1636                         if (convert && (g_slist_find_custom(convlist, attribute, g_str_equal) == NULL))
1637                                 convlist = g_slist_prepend(convlist, g_strdup(tmpattr));
1638
1639                         g_free(tmpattr);
1640                 } else if (convert) {
1641                         if (g_slist_find_custom(convlist, attribute, g_str_equal) == NULL)
1642                                 convlist = g_slist_prepend(convlist, g_strdup(attribute));
1643                 }
1644
1645                 if (g_hash_table_lookup(table, attribute) == NULL)
1646                         g_hash_table_insert(table, g_strdup(attribute), g_strdup(value));
1647         }
1648
1649         for (cur = concatlist; cur != NULL; cur = g_slist_next(cur)) {
1650                 gchar *attribute, *attrwnum, *partvalue;
1651                 gint n = 0;
1652                 GString *value;
1653
1654                 attribute = (gchar *) cur->data;
1655                 value = g_string_sized_new(64);
1656
1657                 attrwnum = g_strdup_printf("%s*%d", attribute, n);
1658                 while ((partvalue = g_hash_table_lookup(table, attrwnum)) != NULL) {
1659                         g_string_append(value, partvalue);
1660
1661                         g_free(attrwnum);
1662                         n++;
1663                         attrwnum = g_strdup_printf("%s*%d", attribute, n);
1664                 }
1665                 g_free(attrwnum);
1666
1667                 g_hash_table_insert(table, g_strdup(attribute), g_strdup(value->str));
1668                 g_string_free(value, TRUE);
1669         }
1670         slist_free_strings(concatlist);
1671         g_slist_free(concatlist);
1672
1673         for (cur = convlist; cur != NULL; cur = g_slist_next(cur)) {
1674                 gchar *attribute, *key, *value;
1675                 gchar *charset, *lang, *oldvalue, *newvalue;
1676
1677                 attribute = (gchar *) cur->data;
1678                 if (!g_hash_table_lookup_extended(
1679                         table, attribute, (gpointer *)(gchar *) &key, (gpointer *)(gchar *) &value))
1680                         continue;
1681
1682                 charset = value;
1683                 lang = strchr(charset, '\'');
1684                 if (lang == NULL)
1685                         continue;
1686                 lang[0] = '\0';
1687                 lang++;
1688                 oldvalue = strchr(lang, '\'');
1689                 if (oldvalue == NULL)
1690                         continue;
1691                 oldvalue[0] = '\0';
1692                 oldvalue++;
1693
1694                 newvalue = conv_codeset_strdup(oldvalue, charset, CS_UTF_8);
1695
1696                 g_hash_table_remove(table, attribute);
1697                 g_free(key);
1698                 g_free(value);
1699
1700                 g_hash_table_insert(table, g_strdup(attribute), newvalue);
1701         }
1702         slist_free_strings(convlist);
1703         g_slist_free(convlist);
1704
1705         g_free(params);
1706 }       
1707
1708 static void procmime_parse_content_type(const gchar *content_type, MimeInfo *mimeinfo)
1709 {
1710         g_return_if_fail(content_type != NULL);
1711         g_return_if_fail(mimeinfo != NULL);
1712
1713         /* RFC 2045, page 13 says that the mime subtype is MANDATORY;
1714          * if it's not available we use the default Content-Type */
1715         if ((content_type[0] == '\0') || (strchr(content_type, '/') == NULL)) {
1716                 mimeinfo->type = MIMETYPE_TEXT;
1717                 mimeinfo->subtype = g_strdup("plain");
1718                 if (g_hash_table_lookup(mimeinfo->typeparameters,
1719                                        "charset") == NULL) {
1720                         g_hash_table_insert(mimeinfo->typeparameters,
1721                                     g_strdup("charset"),
1722                                     g_strdup(
1723                                         conv_get_locale_charset_str_no_utf8()));
1724                 }
1725         } else {
1726                 gchar *type, *subtype, *params;
1727
1728                 type = g_strdup(content_type);
1729                 subtype = strchr(type, '/') + 1;
1730                 *(subtype - 1) = '\0';
1731                 if ((params = strchr(subtype, ';')) != NULL) {
1732                         params[0] = '\0';
1733                         params++;
1734                 }
1735
1736                 mimeinfo->type = procmime_get_media_type(type);
1737                 mimeinfo->subtype = g_strdup(subtype);
1738
1739                 /* Get mimeinfo->typeparameters */
1740                 if (params != NULL)
1741                         parse_parameters(params, mimeinfo->typeparameters);
1742
1743                 g_free(type);
1744         }
1745 }
1746
1747 static void procmime_parse_content_disposition(const gchar *content_disposition, MimeInfo *mimeinfo)
1748 {
1749         gchar *tmp, *params;
1750
1751         g_return_if_fail(content_disposition != NULL);
1752         g_return_if_fail(mimeinfo != NULL);
1753
1754         tmp = g_strdup(content_disposition);
1755         if ((params = strchr(tmp, ';')) != NULL) {
1756                 params[0] = '\0';
1757                 params++;
1758         }       
1759         g_strstrip(tmp);
1760
1761         if (!g_ascii_strcasecmp(tmp, "inline")) 
1762                 mimeinfo->disposition = DISPOSITIONTYPE_INLINE;
1763         else if (!g_ascii_strcasecmp(tmp, "attachment"))
1764                 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1765         else
1766                 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1767         
1768         if (params != NULL)
1769                 parse_parameters(params, mimeinfo->dispositionparameters);
1770
1771         g_free(tmp);
1772 }
1773
1774
1775 static void procmime_parse_content_encoding(const gchar *content_encoding, MimeInfo *mimeinfo)
1776 {
1777         struct EncodingTable *enc_table;
1778         
1779         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1780                 if (g_ascii_strcasecmp(enc_table->str, content_encoding) == 0) {
1781                         mimeinfo->encoding_type = enc_table->enc_type;
1782                         return;
1783                 }
1784         }
1785         mimeinfo->encoding_type = ENC_UNKNOWN;
1786         return;
1787 }
1788
1789 static int procmime_parse_mimepart(MimeInfo *parent,
1790                              gchar *content_type,
1791                              gchar *content_encoding,
1792                              gchar *content_description,
1793                              gchar *content_id,
1794                              gchar *content_disposition,
1795                              gchar *content_location,
1796                              const gchar *filename,
1797                              guint offset,
1798                              guint length,
1799                              gboolean short_scan)
1800 {
1801         MimeInfo *mimeinfo;
1802         int result = 0;
1803         /* Create MimeInfo */
1804         mimeinfo = procmime_mimeinfo_new();
1805         mimeinfo->content = MIMECONTENT_FILE;
1806         if (parent != NULL) {
1807                 if (g_node_depth(parent->node) > 32) {
1808                         /* 32 is an arbitrary value
1809                          * this avoids DOSsing ourselves 
1810                          * with enormous messages
1811                          */
1812                         procmime_mimeinfo_free_all(mimeinfo);
1813                         return -1;                      
1814                 }
1815                 g_node_append(parent->node, mimeinfo->node);
1816         }
1817         mimeinfo->data.filename = g_strdup(filename);
1818         mimeinfo->offset = offset;
1819         mimeinfo->length = length;
1820
1821         if (content_type != NULL) {
1822                 procmime_parse_content_type(content_type, mimeinfo);
1823         } else {
1824                 mimeinfo->type = MIMETYPE_TEXT;
1825                 mimeinfo->subtype = g_strdup("plain");
1826                 if (g_hash_table_lookup(mimeinfo->typeparameters,
1827                                        "charset") == NULL) {
1828                         g_hash_table_insert(mimeinfo->typeparameters,
1829                                     g_strdup("charset"),
1830                                     g_strdup(
1831                                         conv_get_locale_charset_str_no_utf8()));
1832                 }
1833         }
1834
1835         if (content_encoding != NULL) {
1836                 procmime_parse_content_encoding(content_encoding, mimeinfo);
1837         } else {
1838                 mimeinfo->encoding_type = ENC_UNKNOWN;
1839         }
1840
1841         if (content_description != NULL)
1842                 mimeinfo->description = g_strdup(content_description);
1843         else
1844                 mimeinfo->description = NULL;
1845
1846         if (content_id != NULL)
1847                 mimeinfo->id = g_strdup(content_id);
1848         else
1849                 mimeinfo->id = NULL;
1850
1851         if (content_location != NULL)
1852                 mimeinfo->location = g_strdup(content_location);
1853         else
1854                 mimeinfo->location = NULL;
1855
1856         if (content_disposition != NULL) 
1857                 procmime_parse_content_disposition(content_disposition, mimeinfo);
1858         else
1859                 mimeinfo->disposition = DISPOSITIONTYPE_UNKNOWN;
1860
1861         /* Call parser for mime type */
1862         switch (mimeinfo->type) {
1863                 case MIMETYPE_TEXT:
1864                         if (g_ascii_strcasecmp(mimeinfo->subtype, "plain") == 0 && short_scan) {
1865                                 return 1;
1866                         }
1867                         break;
1868
1869                 case MIMETYPE_MESSAGE:
1870                         if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
1871                                 procmime_parse_message_rfc822(mimeinfo, short_scan);
1872                         }
1873                         break;
1874                         
1875                 case MIMETYPE_MULTIPART:
1876                         procmime_parse_multipart(mimeinfo, short_scan);
1877                         break;
1878                         
1879                 default:
1880                         break;
1881         }
1882
1883         return result;
1884 }
1885
1886 static gchar *typenames[] = {
1887     "text",
1888     "image",
1889     "audio",
1890     "video",
1891     "application",
1892     "message",
1893     "multipart",
1894     "unknown",
1895 };
1896
1897 static gboolean output_func(GNode *node, gpointer data)
1898 {
1899         guint i, depth;
1900         MimeInfo *mimeinfo = (MimeInfo *) node->data;
1901
1902         depth = g_node_depth(node);
1903         for (i = 0; i < depth; i++)
1904                 printf("    ");
1905         printf("%s/%s (offset:%d length:%d encoding: %d)\n", typenames[mimeinfo->type], mimeinfo->subtype, mimeinfo->offset, mimeinfo->length, mimeinfo->encoding_type);
1906
1907         return FALSE;
1908 }
1909
1910 static void output_mime_structure(MimeInfo *mimeinfo, int indent)
1911 {
1912         g_node_traverse(mimeinfo->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1, output_func, NULL);
1913 }
1914
1915 static MimeInfo *procmime_scan_file_with_offset(const gchar *filename, int offset, gboolean short_scan)
1916 {
1917         MimeInfo *mimeinfo;
1918         struct stat buf;
1919
1920         stat(filename, &buf);
1921
1922         mimeinfo = procmime_mimeinfo_new();
1923         mimeinfo->content = MIMECONTENT_FILE;
1924         mimeinfo->encoding_type = ENC_UNKNOWN;
1925         mimeinfo->type = MIMETYPE_MESSAGE;
1926         mimeinfo->subtype = g_strdup("rfc822");
1927         mimeinfo->data.filename = g_strdup(filename);
1928         mimeinfo->offset = offset;
1929         mimeinfo->length = buf.st_size - offset;
1930
1931         procmime_parse_message_rfc822(mimeinfo, short_scan);
1932         if (debug_get_mode())
1933                 output_mime_structure(mimeinfo, 0);
1934
1935         return mimeinfo;
1936 }
1937
1938 static MimeInfo *procmime_scan_file_full(const gchar *filename, gboolean short_scan)
1939 {
1940         MimeInfo *mimeinfo;
1941
1942         g_return_val_if_fail(filename != NULL, NULL);
1943
1944         mimeinfo = procmime_scan_file_with_offset(filename, 0, short_scan);
1945
1946         return mimeinfo;
1947 }
1948
1949 MimeInfo *procmime_scan_file(const gchar *filename)
1950 {
1951         return procmime_scan_file_full(filename, FALSE);
1952 }
1953
1954 static MimeInfo *procmime_scan_file_short(const gchar *filename)
1955 {
1956         return procmime_scan_file_full(filename, TRUE);
1957 }
1958
1959 static MimeInfo *procmime_scan_queue_file_full(const gchar *filename, gboolean short_scan)
1960 {
1961         FILE *fp;
1962         MimeInfo *mimeinfo;
1963         gchar buf[BUFFSIZE];
1964         gint offset = 0;
1965
1966         g_return_val_if_fail(filename != NULL, NULL);
1967
1968         /* Open file */
1969         if ((fp = g_fopen(filename, "rb")) == NULL)
1970                 return NULL;
1971         /* Skip queue header */
1972         while (fgets(buf, sizeof(buf), fp) != NULL) {
1973                 /* new way */
1974                 if ((!strncmp(buf, "X-Claws-End-Special-Headers: 1",
1975                         strlen("X-Claws-End-Special-Headers:"))) ||
1976                    (!strncmp(buf, "X-Sylpheed-End-Special-Headers: 1",
1977                         strlen("X-Sylpheed-End-Special-Headers:"))))
1978                         break;
1979                 /* old way */
1980                 if (buf[0] == '\r' || buf[0] == '\n') break;
1981                 /* from other mailers */
1982                 if (!strncmp(buf, "Date: ", 6)
1983                 ||  !strncmp(buf, "To: ", 4)
1984                 ||  !strncmp(buf, "From: ", 6)
1985                 ||  !strncmp(buf, "Subject: ", 9)) {
1986                         rewind(fp);
1987                         break;
1988                 }
1989         }
1990         offset = ftell(fp);
1991         fclose(fp);
1992
1993         mimeinfo = procmime_scan_file_with_offset(filename, offset, short_scan);
1994
1995         return mimeinfo;
1996 }
1997
1998 MimeInfo *procmime_scan_queue_file(const gchar *filename)
1999 {
2000         return procmime_scan_queue_file_full(filename, FALSE);
2001 }
2002
2003 static MimeInfo *procmime_scan_queue_file_short(const gchar *filename)
2004 {
2005         return procmime_scan_queue_file_full(filename, TRUE);
2006 }
2007
2008 typedef enum {
2009     ENC_AS_TOKEN,
2010     ENC_AS_QUOTED_STRING,
2011     ENC_AS_EXTENDED,
2012     ENC_TO_ASCII,
2013 } EncodeAs;
2014
2015 typedef struct _ParametersData {
2016         FILE *fp;
2017         guint len;
2018         guint ascii_only;
2019 } ParametersData;
2020
2021 static void write_parameters(gpointer key, gpointer value, gpointer user_data)
2022 {
2023         gchar *param = key;
2024         gchar *val = value, *valpos, *tmp;
2025         ParametersData *pdata = (ParametersData *)user_data;
2026         GString *buf = g_string_new("");
2027
2028         EncodeAs encas = ENC_AS_TOKEN;
2029
2030         for (valpos = val; *valpos != 0; valpos++) {
2031                 if (!IS_ASCII(*valpos) || *valpos == '"') {
2032                         encas = ENC_AS_EXTENDED;
2033                         break;
2034                 }
2035             
2036                 /* CTLs */
2037                 if (((*valpos >= 0) && (*valpos < 037)) || (*valpos == 0177)) {
2038                         encas = ENC_AS_QUOTED_STRING;
2039                         continue;
2040                 }
2041
2042                 /* tspecials + SPACE */
2043                 switch (*valpos) {
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                 case ']':
2058                 case '?':
2059                 case '=':
2060                         encas = ENC_AS_QUOTED_STRING;
2061                         continue;
2062                 }
2063         }
2064         
2065         if (encas == ENC_AS_EXTENDED && pdata->ascii_only == TRUE) 
2066                 encas = ENC_TO_ASCII;
2067
2068         switch (encas) {
2069         case ENC_AS_TOKEN:
2070                 g_string_append_printf(buf, "%s=%s", param, val);
2071                 break;
2072
2073         case ENC_TO_ASCII:
2074                 tmp = g_strdup(val);
2075                 g_strcanon(tmp, 
2076                         " ()<>@,';:\\/[]?=.0123456789"
2077                         "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2078                         "abcdefghijklmnopqrstuvwxyz",
2079                         '_');
2080                 g_string_append_printf(buf, "%s=\"%s\"", param, tmp);
2081                 g_free(tmp);
2082                 break;
2083
2084         case ENC_AS_QUOTED_STRING:
2085                 g_string_append_printf(buf, "%s=\"%s\"", param, val);
2086                 break;
2087
2088         case ENC_AS_EXTENDED:
2089                 if (!g_utf8_validate(val, -1, NULL))
2090                         g_string_append_printf(buf, "%s*=%s''", param,
2091                                 conv_get_locale_charset_str());
2092                 else
2093                         g_string_append_printf(buf, "%s*=%s''", param,
2094                                 CS_INTERNAL);
2095                 for (valpos = val; *valpos != '\0'; valpos++) {
2096                         if (IS_ASCII(*valpos) && isalnum(*valpos)) {
2097                                 g_string_append_printf(buf, "%c", *valpos);
2098                         } else {
2099                                 gchar hexstr[3] = "XX";
2100                                 get_hex_str(hexstr, *valpos);
2101                                 g_string_append_printf(buf, "%%%s", hexstr);
2102                         }
2103                 }
2104                 break;          
2105         }
2106         
2107         if (buf->str && strlen(buf->str)) {
2108                 if (pdata->len + strlen(buf->str) + 2 > 76) {
2109                         fprintf(pdata->fp, ";\n %s", buf->str);
2110                         pdata->len = strlen(buf->str) + 1;
2111                 } else {
2112                         fprintf(pdata->fp, "; %s", buf->str);
2113                         pdata->len += strlen(buf->str) + 2;
2114                 }
2115         }
2116         g_string_free(buf, TRUE);
2117 }
2118
2119 void procmime_write_mime_header(MimeInfo *mimeinfo, FILE *fp)
2120 {
2121         struct TypeTable *type_table;
2122         ParametersData *pdata = g_new0(ParametersData, 1);
2123         debug_print("procmime_write_mime_header\n");
2124         
2125         pdata->fp = fp;
2126         pdata->ascii_only = FALSE;
2127
2128         for (type_table = mime_type_table; type_table->str != NULL; type_table++)
2129                 if (mimeinfo->type == type_table->type) {
2130                         gchar *buf = g_strdup_printf(
2131                                 "Content-Type: %s/%s", type_table->str, mimeinfo->subtype);
2132                         fprintf(fp, "%s", buf);
2133                         pdata->len = strlen(buf);
2134                         pdata->ascii_only = TRUE;
2135                         g_free(buf);
2136                         break;
2137                 }
2138         g_hash_table_foreach(mimeinfo->typeparameters, write_parameters, pdata);
2139         g_free(pdata);
2140
2141         fprintf(fp, "\n");
2142
2143         if (mimeinfo->encoding_type != ENC_UNKNOWN)
2144                 fprintf(fp, "Content-Transfer-Encoding: %s\n", procmime_get_encoding_str(mimeinfo->encoding_type));
2145
2146         if (mimeinfo->description != NULL)
2147                 fprintf(fp, "Content-Description: %s\n", mimeinfo->description);
2148
2149         if (mimeinfo->id != NULL)
2150                 fprintf(fp, "Content-ID: %s\n", mimeinfo->id);
2151
2152         if (mimeinfo->location != NULL)
2153                 fprintf(fp, "Content-Location: %s\n", mimeinfo->location);
2154
2155         if (mimeinfo->disposition != DISPOSITIONTYPE_UNKNOWN) {
2156                 ParametersData *pdata = g_new0(ParametersData, 1);
2157                 gchar *buf = NULL;
2158                 if (mimeinfo->disposition == DISPOSITIONTYPE_INLINE)
2159                         buf = g_strdup("Content-Disposition: inline");
2160                 else if (mimeinfo->disposition == DISPOSITIONTYPE_ATTACHMENT)
2161                         buf = g_strdup("Content-Disposition: attachment");
2162                 else
2163                         buf = g_strdup("Content-Disposition: unknown");
2164
2165                 fprintf(fp, "%s", buf);
2166                 pdata->len = strlen(buf);
2167                 g_free(buf);
2168
2169                 pdata->fp = fp;
2170                 pdata->ascii_only = FALSE;
2171
2172                 g_hash_table_foreach(mimeinfo->dispositionparameters, write_parameters, pdata);
2173                 g_free(pdata);
2174                 fprintf(fp, "\n");
2175         }
2176
2177         fprintf(fp, "\n");
2178 }
2179
2180 static gint procmime_write_message_rfc822(MimeInfo *mimeinfo, FILE *fp)
2181 {
2182         FILE *infp;
2183         GNode *childnode;
2184         MimeInfo *child;
2185         gchar buf[BUFFSIZE];
2186         gboolean skip = FALSE;;
2187
2188         debug_print("procmime_write_message_rfc822\n");
2189
2190         /* write header */
2191         switch (mimeinfo->content) {
2192         case MIMECONTENT_FILE:
2193                 if ((infp = g_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2194                         FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2195                         return -1;
2196                 }
2197                 fseek(infp, mimeinfo->offset, SEEK_SET);
2198                 while (fgets(buf, sizeof(buf), infp) == buf) {
2199                         strcrchomp(buf);
2200                         if (buf[0] == '\n' && buf[1] == '\0')
2201                                 break;
2202                         if (skip && (buf[0] == ' ' || buf[0] == '\t'))
2203                                 continue;
2204                         if (g_ascii_strncasecmp(buf, "Mime-Version:", 13) == 0 ||
2205                             g_ascii_strncasecmp(buf, "Content-Type:", 13) == 0 ||
2206                             g_ascii_strncasecmp(buf, "Content-Transfer-Encoding:", 26) == 0 ||
2207                             g_ascii_strncasecmp(buf, "Content-Description:", 20) == 0 ||
2208                             g_ascii_strncasecmp(buf, "Content-ID:", 11) == 0 ||
2209                             g_ascii_strncasecmp(buf, "Content-Location:", 17) == 0 ||
2210                             g_ascii_strncasecmp(buf, "Content-Disposition:", 20) == 0) {
2211                                 skip = TRUE;
2212                                 continue;
2213                         }
2214                         fwrite(buf, sizeof(gchar), strlen(buf), fp);
2215                         skip = FALSE;
2216                 }
2217                 fclose(infp);
2218                 break;
2219
2220         case MIMECONTENT_MEM:
2221                 fwrite(mimeinfo->data.mem, 
2222                                 sizeof(gchar), 
2223                                 strlen(mimeinfo->data.mem), 
2224                                 fp);
2225                 break;
2226
2227         default:
2228                 break;
2229         }
2230
2231         childnode = mimeinfo->node->children;
2232         if (childnode == NULL)
2233                 return -1;
2234
2235         child = (MimeInfo *) childnode->data;
2236         fprintf(fp, "Mime-Version: 1.0\n");
2237         procmime_write_mime_header(child, fp);
2238         return procmime_write_mimeinfo(child, fp);
2239 }
2240
2241 static gint procmime_write_multipart(MimeInfo *mimeinfo, FILE *fp)
2242 {
2243         FILE *infp;
2244         GNode *childnode;
2245         gchar *boundary, *str, *str2;
2246         gchar buf[BUFFSIZE];
2247         gboolean firstboundary;
2248
2249         debug_print("procmime_write_multipart\n");
2250
2251         boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
2252
2253         switch (mimeinfo->content) {
2254         case MIMECONTENT_FILE:
2255                 if ((infp = g_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2256                         FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2257                         return -1;
2258                 }
2259                 fseek(infp, mimeinfo->offset, SEEK_SET);
2260                 while (fgets(buf, sizeof(buf), infp) == buf) {
2261                         if (IS_BOUNDARY(buf, boundary, strlen(boundary)))
2262                                 break;
2263                         fwrite(buf, sizeof(gchar), strlen(buf), fp);
2264                 }
2265                 fclose(infp);
2266                 break;
2267
2268         case MIMECONTENT_MEM:
2269                 str = g_strdup(mimeinfo->data.mem);
2270                 if (((str2 = strstr(str, boundary)) != NULL) && ((str2 - str) >= 2) &&
2271                     (*(str2 - 1) == '-') && (*(str2 - 2) == '-'))
2272                         *(str2 - 2) = '\0';
2273                 fwrite(str, sizeof(gchar), strlen(str), fp);
2274                 g_free(str);
2275                 break;
2276
2277         default:
2278                 break;
2279         }
2280
2281         childnode = mimeinfo->node->children;
2282         firstboundary = TRUE;
2283         while (childnode != NULL) {
2284                 MimeInfo *child = childnode->data;
2285
2286                 if (firstboundary)
2287                         firstboundary = FALSE;
2288                 else
2289                         fprintf(fp, "\n");
2290                 fprintf(fp, "--%s\n", boundary);
2291
2292                 procmime_write_mime_header(child, fp);
2293                 if (procmime_write_mimeinfo(child, fp) < 0)
2294                         return -1;
2295
2296                 childnode = g_node_next_sibling(childnode);
2297         }       
2298         fprintf(fp, "\n--%s--\n", boundary);
2299
2300         return 0;
2301 }
2302
2303 gint procmime_write_mimeinfo(MimeInfo *mimeinfo, FILE *fp)
2304 {
2305         FILE *infp;
2306
2307         debug_print("procmime_write_mimeinfo\n");
2308
2309         if (G_NODE_IS_LEAF(mimeinfo->node)) {
2310                 switch (mimeinfo->content) {
2311                 case MIMECONTENT_FILE:
2312                         if ((infp = g_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2313                                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2314                                 return -1;
2315                         }
2316                         copy_file_part_to_fp(infp, mimeinfo->offset, mimeinfo->length, fp);
2317                         fclose(infp);
2318                         return 0;
2319
2320                 case MIMECONTENT_MEM:
2321                         fwrite(mimeinfo->data.mem, 
2322                                         sizeof(gchar), 
2323                                         strlen(mimeinfo->data.mem), 
2324                                         fp);
2325                         return 0;
2326
2327                 default:
2328                         return 0;
2329                 }
2330         } else {
2331                 /* Call writer for mime type */
2332                 switch (mimeinfo->type) {
2333                 case MIMETYPE_MESSAGE:
2334                         if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
2335                                 return procmime_write_message_rfc822(mimeinfo, fp);
2336                         }
2337                         break;
2338                         
2339                 case MIMETYPE_MULTIPART:
2340                         return procmime_write_multipart(mimeinfo, fp);
2341                         
2342                 default:
2343                         break;
2344                 }
2345
2346                 return -1;
2347         }
2348
2349         return 0;
2350 }
2351
2352 gchar *procmime_get_part_file_name(MimeInfo *mimeinfo)
2353 {
2354         gchar *base;
2355
2356         if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
2357                 base = g_strdup("mimetmp.html");
2358         else {
2359                 const gchar *basetmp;
2360                 gchar *basename;
2361
2362                 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
2363                 if (basetmp == NULL)
2364                         basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
2365                 if (basetmp == NULL)
2366                         basetmp = "mimetmp";
2367                 basename = g_path_get_basename(basetmp);
2368                 if (*basename == '\0') {
2369                         g_free(basename);
2370                         basename = g_strdup("mimetmp");
2371                 }
2372                 base = conv_filename_from_utf8(basename);
2373                 g_free(basename);
2374                 subst_for_shellsafe_filename(base);
2375         }
2376         
2377         return base;
2378 }
2379