2004-11-05 [colin] 0.9.12cvs139.1
[claws.git] / src / procmime.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2004 Hiroyuki Yamamoto & The Sylpheed-Claws 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 2 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, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
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 <stdio.h>
29 #include <string.h>
30 #include <locale.h>
31 #include <ctype.h>
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <unistd.h>
35
36 #include "intl.h"
37 #include "procmime.h"
38 #include "procheader.h"
39 #include "base64.h"
40 #include "quoted-printable.h"
41 #include "uuencode.h"
42 #include "unmime.h"
43 #include "html.h"
44 #include "enriched.h"
45 #include "codeconv.h"
46 #include "utils.h"
47 #include "prefs_common.h"
48
49 #include "prefs_gtk.h"
50
51 static GHashTable *procmime_get_mime_type_table (void);
52
53 MimeInfo *procmime_mimeinfo_new(void)
54 {
55         MimeInfo *mimeinfo;
56
57         mimeinfo = g_new0(MimeInfo, 1);
58         mimeinfo->content        = MIMECONTENT_EMPTY;
59         mimeinfo->data.filename  = NULL;
60
61         mimeinfo->type           = MIMETYPE_UNKNOWN;
62         mimeinfo->encoding_type  = ENC_UNKNOWN;
63         mimeinfo->typeparameters = g_hash_table_new(g_str_hash, g_str_equal);
64
65         mimeinfo->disposition    = DISPOSITIONTYPE_UNKNOWN;
66         mimeinfo->dispositionparameters 
67                                  = g_hash_table_new(g_str_hash, g_str_equal);
68
69         mimeinfo->node           = g_node_new(mimeinfo);
70         
71         return mimeinfo;
72 }
73
74 static gboolean procmime_mimeinfo_parameters_destroy(gpointer key, gpointer value, gpointer user_data)
75 {
76         g_free(key);
77         g_free(value);
78         
79         return TRUE;
80 }
81
82 static gchar *forced_charset = NULL;
83
84 void procmime_force_charset(const gchar *str)
85 {
86         g_free(forced_charset);
87         forced_charset = NULL;
88         if (str)
89                 forced_charset = g_strdup(str);
90 }
91
92 static EncodingType forced_encoding = 0;
93
94 void procmime_force_encoding(EncodingType encoding)
95 {
96         forced_encoding = encoding;
97 }
98
99 static gboolean free_func(GNode *node, gpointer data)
100 {
101         MimeInfo *mimeinfo = (MimeInfo *) node->data;
102
103         switch (mimeinfo->content) {
104         case MIMECONTENT_FILE:
105                 if (mimeinfo->tmp)
106                         unlink(mimeinfo->data.filename);
107                 g_free(mimeinfo->data.filename);
108                 break;
109
110         case MIMECONTENT_MEM:
111                 if (mimeinfo->tmp)
112                         g_free(mimeinfo->data.mem);
113         default:
114                 break;
115         }
116
117         g_free(mimeinfo->subtype);
118         g_free(mimeinfo->description);
119         g_free(mimeinfo->id);
120
121         g_hash_table_foreach_remove(mimeinfo->typeparameters,
122                 procmime_mimeinfo_parameters_destroy, NULL);
123         g_hash_table_destroy(mimeinfo->typeparameters);
124         g_hash_table_foreach_remove(mimeinfo->dispositionparameters,
125                 procmime_mimeinfo_parameters_destroy, NULL);
126         g_hash_table_destroy(mimeinfo->dispositionparameters);
127
128         if (mimeinfo->privacy)
129                 privacy_free_privacydata(mimeinfo->privacy);
130
131         g_free(mimeinfo);
132
133         return FALSE;
134 }
135
136 void procmime_mimeinfo_free_all(MimeInfo *mimeinfo)
137 {
138         GNode *node;
139
140         if (!mimeinfo)
141                 return;
142
143         node = mimeinfo->node;
144         g_node_traverse(node, G_IN_ORDER, G_TRAVERSE_ALL, -1, free_func, NULL);
145
146         g_node_destroy(node);
147 }
148
149 #if 0 /* UNUSED */
150 MimeInfo *procmime_mimeinfo_insert(MimeInfo *parent, MimeInfo *mimeinfo)
151 {
152         MimeInfo *child = parent->children;
153
154         if (!child)
155                 parent->children = mimeinfo;
156         else {
157                 while (child->next != NULL)
158                         child = child->next;
159
160                 child->next = mimeinfo;
161         }
162
163         mimeinfo->parent = parent;
164         mimeinfo->level = parent->level + 1;
165
166         return mimeinfo;
167 }
168
169 void procmime_mimeinfo_replace(MimeInfo *old, MimeInfo *new)
170 {
171         MimeInfo *parent = old->parent;
172         MimeInfo *child;
173
174         g_return_if_fail(parent != NULL);
175         g_return_if_fail(new->next == NULL);
176
177         for (child = parent->children; child && child != old;
178              child = child->next)
179                 ;
180         if (!child) {
181                 g_warning("oops: parent can't find it's own child");
182                 return;
183         }
184         procmime_mimeinfo_free_all(old);
185
186         if (child == parent->children) {
187                 new->next = parent->children->next;
188                 parent->children = new;
189         } else {
190                 new->next = child->next;
191                 child = new;
192         }
193 }
194 #endif
195
196 MimeInfo *procmime_mimeinfo_parent(MimeInfo *mimeinfo)
197 {
198         g_return_val_if_fail(mimeinfo != NULL, NULL);
199         g_return_val_if_fail(mimeinfo->node != NULL, NULL);
200
201         if (mimeinfo->node->parent == NULL)
202                 return NULL;
203         return (MimeInfo *) mimeinfo->node->parent->data;
204 }
205
206 MimeInfo *procmime_mimeinfo_next(MimeInfo *mimeinfo)
207 {
208         g_return_val_if_fail(mimeinfo != NULL, NULL);
209         g_return_val_if_fail(mimeinfo->node != NULL, NULL);
210
211         if (mimeinfo->node->children)
212                 return (MimeInfo *) mimeinfo->node->children->data;
213         if (mimeinfo->node->next)
214                 return (MimeInfo *) mimeinfo->node->next->data;
215
216         if (mimeinfo->node->parent == NULL)
217                 return NULL;
218
219         while (mimeinfo->node->parent != NULL) {
220                 mimeinfo = (MimeInfo *) mimeinfo->node->parent->data;
221                 if (mimeinfo->node->next)
222                         return (MimeInfo *) mimeinfo->node->next->data;
223         }
224
225         return NULL;
226 }
227
228 MimeInfo *procmime_scan_message(MsgInfo *msginfo)
229 {
230         gchar *filename;
231         MimeInfo *mimeinfo;
232
233         filename = procmsg_get_message_file(msginfo);
234         if (!filename)
235                 return NULL;
236         if (msginfo->folder->stype != F_QUEUE && 
237             msginfo->folder->stype != F_DRAFT)
238                 mimeinfo = procmime_scan_file(filename);
239         else
240                 mimeinfo = procmime_scan_queue_file(filename);
241         g_free(filename);
242
243         return mimeinfo;
244 }
245
246 enum
247 {
248         H_CONTENT_TRANSFER_ENCODING = 0,
249         H_CONTENT_TYPE              = 1,
250         H_CONTENT_DISPOSITION       = 2,
251         H_CONTENT_DESCRIPTION       = 3,
252         H_SUBJECT                   = 4
253 };
254
255 const gchar *procmime_mimeinfo_get_parameter(MimeInfo *mimeinfo, const gchar *name)
256 {
257         const gchar *value;
258
259         g_return_val_if_fail(mimeinfo != NULL, NULL);
260         g_return_val_if_fail(name != NULL, NULL);
261
262         value = g_hash_table_lookup(mimeinfo->dispositionparameters, name);
263         if (value == NULL)
264                 value = g_hash_table_lookup(mimeinfo->typeparameters, name);
265         
266         return value;
267 }
268
269 gboolean procmime_decode_content(MimeInfo *mimeinfo)
270 {
271         gchar buf[BUFFSIZE];
272         gint readend;
273         gchar *tmpfilename;
274         FILE *outfp, *infp;
275         struct stat statbuf;
276
277         EncodingType encoding = forced_encoding 
278                                 ? forced_encoding
279                                 : mimeinfo->encoding_type;
280                    
281         g_return_val_if_fail(mimeinfo != NULL, FALSE);
282
283         if (encoding == ENC_UNKNOWN ||
284             encoding == ENC_BINARY)
285                 return TRUE;
286
287         infp = fopen(mimeinfo->data.filename, "rb");
288         if (!infp) {
289                 perror("fopen");
290                 return FALSE;
291         }
292         fseek(infp, mimeinfo->offset, SEEK_SET);
293
294         outfp = get_tmpfile_in_dir(get_mime_tmp_dir(), &tmpfilename);
295         if (!outfp) {
296                 perror("tmpfile");
297                 return FALSE;
298         }
299
300         readend = mimeinfo->offset + mimeinfo->length;
301
302         if (encoding == ENC_QUOTED_PRINTABLE) {
303                 while ((ftell(infp) < readend) && (fgets(buf, sizeof(buf), infp) != NULL)) {
304                         gint len;
305                         len = qp_decode_line(buf);
306                         fwrite(buf, len, 1, outfp);
307                 }
308         } else if (encoding == ENC_BASE64) {
309                 gchar outbuf[BUFFSIZE];
310                 gint len;
311                 Base64Decoder *decoder;
312
313                 decoder = base64_decoder_new();
314                 while ((ftell(infp) < readend) && (fgets(buf, sizeof(buf), infp) != NULL)) {
315                         len = base64_decoder_decode(decoder, buf, outbuf);
316                         if (len < 0) {
317                                 g_warning("Bad BASE64 content\n");
318                                 break;
319                         }
320                         fwrite(outbuf, sizeof(gchar), len, outfp);
321                 }
322                 base64_decoder_free(decoder);
323         } else if (encoding == ENC_X_UUENCODE) {
324                 gchar outbuf[BUFFSIZE];
325                 gint len;
326                 gboolean flag = FALSE;
327
328                 while ((ftell(infp) < readend) && (fgets(buf, sizeof(buf), infp) != NULL)) {
329                         if (!flag && strncmp(buf,"begin ", 6)) continue;
330
331                         if (flag) {
332                                 len = fromuutobits(outbuf, buf);
333                                 if (len <= 0) {
334                                         if (len < 0) 
335                                                 g_warning("Bad UUENCODE content(%d)\n", len);
336                                         break;
337                                 }
338                                 fwrite(outbuf, sizeof(gchar), len, outfp);
339                         } else
340                                 flag = TRUE;
341                 }
342         } else {
343                 while ((ftell(infp) < readend) && (fgets(buf, sizeof(buf), infp) != NULL)) {
344                         fputs(buf, outfp);
345                 }
346         }
347
348         fclose(outfp);
349         fclose(infp);
350
351         stat(tmpfilename, &statbuf);
352         if (mimeinfo->tmp && (mimeinfo->data.filename != NULL))
353                 unlink(mimeinfo->data.filename);
354         if (mimeinfo->data.filename != NULL)
355                 g_free(mimeinfo->data.filename);
356         mimeinfo->data.filename = tmpfilename;
357         mimeinfo->tmp = TRUE;
358         mimeinfo->offset = 0;
359         mimeinfo->length = statbuf.st_size;
360         mimeinfo->encoding_type = ENC_BINARY;
361
362         return TRUE;
363 }
364
365 #define B64_LINE_SIZE           57
366 #define B64_BUFFSIZE            77
367
368 gboolean procmime_encode_content(MimeInfo *mimeinfo, EncodingType encoding)
369 {
370         FILE *infp, *outfp;
371         gint len;
372         gchar *tmpfilename, *tmpout;
373         struct stat statbuf;
374
375         if (mimeinfo->encoding_type != ENC_UNKNOWN &&
376             mimeinfo->encoding_type != ENC_BINARY &&
377             mimeinfo->encoding_type != ENC_7BIT &&
378             mimeinfo->encoding_type != ENC_8BIT)
379                 if(!procmime_decode_content(mimeinfo))
380                         return FALSE;
381
382         outfp = get_tmpfile_in_dir(get_mime_tmp_dir(), &tmpfilename);
383         if (!outfp) {
384                 perror("tmpfile");
385                 return FALSE;
386         }
387
388         if (mimeinfo->content == MIMECONTENT_MEM) {
389                 infp = get_tmpfile_in_dir(get_mime_tmp_dir(), &tmpout);
390                 if (infp)
391                         fclose(infp);
392                 else
393                         return FALSE;
394
395                 str_write_to_file(mimeinfo->data.mem, tmpout);
396                 g_free(mimeinfo->data.mem);
397                 mimeinfo->tmp = TRUE;
398                 mimeinfo->data.filename = tmpout;
399         }
400
401         if ((infp = fopen(mimeinfo->data.filename, "rb")) == NULL) {
402                 g_warning("Can't open file %s\n", mimeinfo->data.filename);
403                 if (mimeinfo->content == MIMECONTENT_MEM) {
404                         unlink(mimeinfo->data.filename);
405                         g_free(mimeinfo->data.filename);
406                         mimeinfo->data.filename = NULL;
407                 }
408                 return FALSE;
409         }
410
411         if (encoding == ENC_BASE64) {
412                 gchar inbuf[B64_LINE_SIZE], outbuf[B64_BUFFSIZE];
413
414                 while ((len = fread(inbuf, sizeof(gchar),
415                                     B64_LINE_SIZE, infp))
416                        == B64_LINE_SIZE) {
417                         base64_encode(outbuf, inbuf, B64_LINE_SIZE);
418                         fputs(outbuf, outfp);
419                         fputc('\n', outfp);
420                 }
421                 if (len > 0 && feof(infp)) {
422                         base64_encode(outbuf, inbuf, len);
423                         fputs(outbuf, outfp);
424                         fputc('\n', outfp);
425                 }
426         } else if (encoding == ENC_QUOTED_PRINTABLE) {
427                 gchar inbuf[BUFFSIZE], outbuf[BUFFSIZE * 4];
428
429                 while (fgets(inbuf, sizeof(inbuf), infp) != NULL) {
430                         qp_encode_line(outbuf, inbuf);
431                         fputs(outbuf, outfp);
432                 }
433         } else {
434                 gchar buf[BUFFSIZE];
435
436                 while (fgets(buf, sizeof(buf), infp) != NULL) {
437                         strcrchomp(buf);
438                         fputs(buf, outfp);
439                 }
440         }
441
442         fclose(outfp);
443         fclose(infp);
444
445         stat(tmpfilename, &statbuf);
446         if (mimeinfo->tmp && (mimeinfo->data.filename != NULL))
447                 unlink(mimeinfo->data.filename);
448         g_free(mimeinfo->data.filename);
449         mimeinfo->data.filename = tmpfilename;
450         mimeinfo->tmp = TRUE;
451         mimeinfo->offset = 0;
452         mimeinfo->length = statbuf.st_size;
453         mimeinfo->encoding_type = encoding;
454         mimeinfo->content = MIMECONTENT_FILE;
455
456         return TRUE;
457 }
458
459 gint procmime_get_part(const gchar *outfile, MimeInfo *mimeinfo)
460 {
461         FILE *infp, *outfp;
462         gchar buf[BUFFSIZE];
463         gint restlength, readlength;
464
465         g_return_val_if_fail(outfile != NULL, -1);
466         g_return_val_if_fail(mimeinfo != NULL, -1);
467
468         if (mimeinfo->encoding_type != ENC_BINARY && !procmime_decode_content(mimeinfo))
469                 return -1;
470
471         if ((infp = fopen(mimeinfo->data.filename, "rb")) == NULL) {
472                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
473                 return -1;
474         }
475         if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
476                 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
477                 fclose(infp);
478                 return -1;
479         }
480         if ((outfp = fopen(outfile, "wb")) == NULL) {
481                 FILE_OP_ERROR(outfile, "fopen");
482                 fclose(infp);
483                 return -1;
484         }
485
486         restlength = mimeinfo->length;
487
488         while ((restlength > 0) && ((readlength = fread(buf, 1, restlength > BUFFSIZE ? BUFFSIZE : restlength, infp)) > 0)) {
489                 fwrite(buf, 1, readlength, outfp);
490                 restlength -= readlength;
491         }
492
493         fclose(infp);
494         if (fclose(outfp) == EOF) {
495                 FILE_OP_ERROR(outfile, "fclose");
496                 unlink(outfile);
497                 return -1;
498         }
499
500         return 0;
501 }
502
503 struct ContentRenderer {
504         char * content_type;
505         char * renderer;
506 };
507
508 static GList * renderer_list = NULL;
509
510 static struct ContentRenderer *
511 content_renderer_new(char * content_type, char * renderer)
512 {
513         struct ContentRenderer * cr;
514
515         cr = g_new(struct ContentRenderer, 1);
516         if (cr == NULL)
517                 return NULL;
518
519         cr->content_type = g_strdup(content_type);
520         cr->renderer = g_strdup(renderer);
521
522         return cr;
523 }
524
525 static void content_renderer_free(struct ContentRenderer * cr)
526 {
527         g_free(cr->content_type);
528         g_free(cr->renderer);
529         g_free(cr);
530 }
531
532 void renderer_read_config(void)
533 {
534         gchar buf[BUFFSIZE];
535         FILE * f;
536         gchar * rcpath;
537
538         g_list_foreach(renderer_list, (GFunc) content_renderer_free, NULL);
539         renderer_list = NULL;
540
541         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, RENDERER_RC, NULL);
542         f = fopen(rcpath, "rb");
543         g_free(rcpath);
544         
545         if (f == NULL)
546                 return;
547
548         while (fgets(buf, BUFFSIZE, f)) {
549                 char * p;
550                 struct ContentRenderer * cr;
551
552                 strretchomp(buf);
553                 p = strchr(buf, ' ');
554                 if (p == NULL)
555                         continue;
556                 * p = 0;
557
558                 cr = content_renderer_new(buf, p + 1);
559                 if (cr == NULL)
560                         continue;
561
562                 renderer_list = g_list_append(renderer_list, cr);
563         }
564
565         fclose(f);
566 }
567
568 void renderer_write_config(void)
569 {
570         gchar * rcpath;
571         PrefFile *pfile;
572         GList * cur;
573
574         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, RENDERER_RC, NULL);
575         
576         if ((pfile = prefs_write_open(rcpath)) == NULL) {
577                 g_warning("failed to write configuration to file\n");
578                 g_free(rcpath);
579                 return;
580         }
581
582         g_free(rcpath);
583
584         for (cur = renderer_list ; cur != NULL ; cur = cur->next) {
585                 struct ContentRenderer * renderer;
586                 renderer = cur->data;
587                 fprintf(pfile->fp, "%s %s\n", renderer->content_type,
588                         renderer->renderer);
589         }
590
591         if (prefs_file_close(pfile) < 0) {
592                 g_warning("failed to write configuration to file\n");
593                 return;
594         }
595 }
596
597 FILE *procmime_get_text_content(MimeInfo *mimeinfo)
598 {
599         FILE *tmpfp, *outfp;
600         const gchar *src_codeset;
601         gboolean conv_fail = FALSE;
602         gchar buf[BUFFSIZE];
603         gchar *str;
604         struct ContentRenderer * renderer;
605         GList * cur;
606         gchar *tmpfile, *content_type;
607     
608         g_return_val_if_fail(mimeinfo != NULL, NULL);
609
610         if (!procmime_decode_content(mimeinfo))
611                 return NULL;
612
613         tmpfile = procmime_get_tmp_file_name(mimeinfo);
614         if (tmpfile == NULL)
615                 return NULL;
616
617         if (procmime_get_part(tmpfile, mimeinfo) < 0) {
618                 g_free(tmpfile);
619                 return NULL;
620         }
621
622         tmpfp = fopen(tmpfile, "rb");
623         if (tmpfp == NULL) {
624                 g_free(tmpfile);
625                 return NULL;
626         }
627
628         if ((outfp = my_tmpfile()) == NULL) {
629                 perror("tmpfile");
630                 fclose(tmpfp);
631                 g_free(tmpfile);
632                 return NULL;
633         }
634
635         src_codeset = forced_charset
636                       ? forced_charset : 
637                       procmime_mimeinfo_get_parameter(mimeinfo, "charset");
638
639         renderer = NULL;
640
641         content_type = procmime_get_content_type_str(mimeinfo->type,
642                                                      mimeinfo->subtype);
643         for (cur = renderer_list ; cur != NULL ; cur = cur->next) {
644                 struct ContentRenderer * cr;
645
646                 cr = cur->data;
647                 if (g_ascii_strcasecmp(cr->content_type, content_type) == 0) {
648                         renderer = cr;
649                         break;
650                 }
651         }
652         g_free(content_type);
653
654         if (renderer != NULL) {
655                 FILE * p;
656                 int oldout;
657                 
658                 oldout = dup(1);
659                 
660                 dup2(fileno(outfp), 1);
661                 
662                 p = popen(renderer->renderer, "w");
663                 if (p != NULL) {
664                         size_t count;
665                         
666                         while ((count =
667                                 fread(buf, sizeof(char), sizeof(buf),
668                                       tmpfp)) > 0)
669                                 fwrite(buf, sizeof(char), count, p);
670                         pclose(p);
671                 }
672                 
673                 dup2(oldout, 1);
674 #warning FIXME_GTK2 HTML/RTF not yet utf8
675 /* CodeConverter seems to have no effect here */
676         } else if (mimeinfo->type == MIMETYPE_TEXT && !g_ascii_strcasecmp(mimeinfo->subtype, "html")) {
677                 HTMLParser *parser;
678                 CodeConverter *conv;
679
680                 conv = conv_code_converter_new(src_codeset);
681                 parser = html_parser_new(tmpfp, conv);
682                 while ((str = html_parse(parser)) != NULL) {
683                         fputs(str, outfp);
684                 }
685                 html_parser_destroy(parser);
686                 conv_code_converter_destroy(conv);
687         } else if (mimeinfo->type == MIMETYPE_TEXT && !g_ascii_strcasecmp(mimeinfo->subtype, "enriched")) {
688                 ERTFParser *parser;
689                 CodeConverter *conv;
690
691                 conv = conv_code_converter_new(src_codeset);
692                 parser = ertf_parser_new(tmpfp, conv);
693                 while ((str = ertf_parse(parser)) != NULL) {
694                         fputs(str, outfp);
695                 }
696                 ertf_parser_destroy(parser);
697                 conv_code_converter_destroy(conv);
698         } else if (mimeinfo->type == MIMETYPE_TEXT) {
699                 while (fgets(buf, sizeof(buf), tmpfp) != NULL) {
700                         str = conv_codeset_strdup(buf, src_codeset, CS_UTF_8);
701                         if (str) {
702                                 fputs(str, outfp);
703                                 g_free(str);
704                         } else {
705                                 conv_fail = TRUE;
706                                 fputs(buf, outfp);
707                         }
708                 }
709         }
710
711         if (conv_fail)
712                 g_warning("procmime_get_text_content(): Code conversion failed.\n");
713
714         fclose(tmpfp);
715         rewind(outfp);
716         unlink(tmpfile);
717         g_free(tmpfile);
718
719         return outfp;
720 }
721
722 /* search the first text part of (multipart) MIME message,
723    decode, convert it and output to outfp. */
724 FILE *procmime_get_first_text_content(MsgInfo *msginfo)
725 {
726         FILE *outfp = NULL;
727         MimeInfo *mimeinfo, *partinfo;
728
729         g_return_val_if_fail(msginfo != NULL, NULL);
730
731         mimeinfo = procmime_scan_message(msginfo);
732         if (!mimeinfo) return NULL;
733
734         partinfo = mimeinfo;
735         while (partinfo && partinfo->type != MIMETYPE_TEXT)
736                 partinfo = procmime_mimeinfo_next(partinfo);
737
738         if (partinfo)
739                 outfp = procmime_get_text_content(partinfo);
740
741         procmime_mimeinfo_free_all(mimeinfo);
742
743         return outfp;
744 }
745
746 gboolean procmime_find_string_part(MimeInfo *mimeinfo, const gchar *filename,
747                                    const gchar *str, gboolean case_sens)
748 {
749         FILE *outfp;
750         gchar buf[BUFFSIZE];
751         gchar *(* StrFindFunc) (const gchar *haystack, const gchar *needle);
752
753         g_return_val_if_fail(mimeinfo != NULL, FALSE);
754         g_return_val_if_fail(mimeinfo->type == MIMETYPE_TEXT, FALSE);
755         g_return_val_if_fail(str != NULL, FALSE);
756
757         outfp = procmime_get_text_content(mimeinfo);
758
759         if (!outfp)
760                 return FALSE;
761
762         if (case_sens)
763                 StrFindFunc = strstr;
764         else
765                 StrFindFunc = strcasestr;
766
767         while (fgets(buf, sizeof(buf), outfp) != NULL) {
768                 if (StrFindFunc(buf, str) != NULL) {
769                         fclose(outfp);
770                         return TRUE;
771                 }
772         }
773
774         fclose(outfp);
775
776         return FALSE;
777 }
778
779 gboolean procmime_find_string(MsgInfo *msginfo, const gchar *str,
780                               gboolean case_sens)
781 {
782         MimeInfo *mimeinfo;
783         MimeInfo *partinfo;
784         gchar *filename;
785         gboolean found = FALSE;
786
787         g_return_val_if_fail(msginfo != NULL, FALSE);
788         g_return_val_if_fail(str != NULL, FALSE);
789
790         filename = procmsg_get_message_file(msginfo);
791         if (!filename) return FALSE;
792         mimeinfo = procmime_scan_message(msginfo);
793
794         for (partinfo = mimeinfo; partinfo != NULL;
795              partinfo = procmime_mimeinfo_next(partinfo)) {
796                 if (partinfo->type == MIMETYPE_TEXT) {
797                         if (procmime_find_string_part
798                                 (partinfo, filename, str, case_sens) == TRUE) {
799                                 found = TRUE;
800                                 break;
801                         }
802                 }
803         }
804
805         procmime_mimeinfo_free_all(mimeinfo);
806         g_free(filename);
807
808         return found;
809 }
810
811 gchar *procmime_get_tmp_file_name(MimeInfo *mimeinfo)
812 {
813         static guint32 id = 0;
814         const gchar *base;
815         gchar *filename;
816         gchar f_prefix[10];
817
818         g_return_val_if_fail(mimeinfo != NULL, NULL);
819
820         g_snprintf(f_prefix, sizeof(f_prefix), "%08x.", id++);
821
822         if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
823                 base = "mimetmp.html";
824         else {
825                 const gchar *basetmp;
826
827                 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
828                 if (basetmp == NULL)
829                         basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
830                 if (basetmp == NULL)
831                         basetmp = "mimetmp";
832                 base = g_basename(basetmp);
833                 if (*base == '\0') base = "mimetmp";
834                 Xstrdup_a(base, base, return NULL);
835                 subst_for_shellsafe_filename(base);
836         }
837
838         filename = g_strconcat(get_mime_tmp_dir(), G_DIR_SEPARATOR_S,
839                                f_prefix, base, NULL);
840
841         return filename;
842 }
843
844 static GList *mime_type_list = NULL;
845
846 gchar *procmime_get_mime_type(const gchar *filename)
847 {
848         static GHashTable *mime_type_table = NULL;
849         MimeType *mime_type;
850         const gchar *p;
851         gchar *ext;
852
853         if (!mime_type_table) {
854                 mime_type_table = procmime_get_mime_type_table();
855                 if (!mime_type_table) return NULL;
856         }
857
858         filename = g_basename(filename);
859         p = strrchr(filename, '.');
860         if (!p) return NULL;
861
862         Xstrdup_a(ext, p + 1, return NULL);
863         g_strdown(ext);
864         mime_type = g_hash_table_lookup(mime_type_table, ext);
865         if (mime_type) {
866                 gchar *str;
867
868                 str = g_strconcat(mime_type->type, "/", mime_type->sub_type,
869                                   NULL);
870                 return str;
871         }
872
873         return NULL;
874 }
875
876 static guint procmime_str_hash(gconstpointer gptr)
877 {
878         guint hash_result = 0;
879         const char *str;
880
881         for (str = gptr; str && *str; str++) {
882                 if (isupper(*str)) hash_result += (*str + ' ');
883                 else hash_result += *str;
884         }
885
886         return hash_result;
887 }
888
889 static gint procmime_str_equal(gconstpointer gptr1, gconstpointer gptr2)
890 {
891         const char *str1 = gptr1;
892         const char *str2 = gptr2;
893
894         return !g_utf8_collate(str1, str2);
895 }
896
897 static GHashTable *procmime_get_mime_type_table(void)
898 {
899         GHashTable *table = NULL;
900         GList *cur;
901         MimeType *mime_type;
902         gchar **exts;
903
904         if (!mime_type_list) {
905                 mime_type_list = procmime_get_mime_type_list();
906                 if (!mime_type_list) return NULL;
907         }
908
909         table = g_hash_table_new(procmime_str_hash, procmime_str_equal);
910
911         for (cur = mime_type_list; cur != NULL; cur = cur->next) {
912                 gint i;
913                 gchar *key;
914
915                 mime_type = (MimeType *)cur->data;
916
917                 if (!mime_type->extension) continue;
918
919                 exts = g_strsplit(mime_type->extension, " ", 16);
920                 for (i = 0; exts[i] != NULL; i++) {
921                         /* make the key case insensitive */
922                         g_strdown(exts[i]);
923                         /* use previously dup'd key on overwriting */
924                         if (g_hash_table_lookup(table, exts[i]))
925                                 key = exts[i];
926                         else
927                                 key = g_strdup(exts[i]);
928                         g_hash_table_insert(table, key, mime_type);
929                 }
930                 g_strfreev(exts);
931         }
932
933         return table;
934 }
935
936 GList *procmime_get_mime_type_list(void)
937 {
938         GList *list = NULL;
939         FILE *fp;
940         gchar buf[BUFFSIZE];
941         guchar *p;
942         gchar *delim;
943         MimeType *mime_type;
944
945         if (mime_type_list) 
946                 return mime_type_list;
947
948         if ((fp = fopen("/etc/mime.types", "rb")) == NULL) {
949                 if ((fp = fopen(SYSCONFDIR "/mime.types", "rb")) == NULL) {
950                         FILE_OP_ERROR(SYSCONFDIR "/mime.types", "fopen");
951                         return NULL;
952                 }
953         }
954
955         while (fgets(buf, sizeof(buf), fp) != NULL) {
956                 p = strchr(buf, '#');
957                 if (p) *p = '\0';
958                 g_strstrip(buf);
959
960                 p = buf;
961                 while (*p && !isspace(*p)) p++;
962                 if (*p) {
963                         *p = '\0';
964                         p++;
965                 }
966                 delim = strchr(buf, '/');
967                 if (delim == NULL) continue;
968                 *delim = '\0';
969
970                 mime_type = g_new(MimeType, 1);
971                 mime_type->type = g_strdup(buf);
972                 mime_type->sub_type = g_strdup(delim + 1);
973
974                 while (*p && isspace(*p)) p++;
975                 if (*p)
976                         mime_type->extension = g_strdup(p);
977                 else
978                         mime_type->extension = NULL;
979
980                 list = g_list_append(list, mime_type);
981         }
982
983         fclose(fp);
984
985         if (!list)
986                 g_warning("Can't read mime.types\n");
987
988         return list;
989 }
990
991 EncodingType procmime_get_encoding_for_charset(const gchar *charset)
992 {
993         if (!charset)
994                 return ENC_8BIT;
995         else if (!g_ascii_strncasecmp(charset, "ISO-2022-", 9) ||
996                  !g_ascii_strcasecmp(charset, "US-ASCII"))
997                 return ENC_7BIT;
998         else if (!g_ascii_strcasecmp(charset, "ISO-8859-5") ||
999                  !g_ascii_strncasecmp(charset, "KOI8-", 5) ||
1000                  !g_ascii_strcasecmp(charset, "Windows-1251"))
1001                 return ENC_8BIT;
1002         else if (!g_ascii_strncasecmp(charset, "ISO-8859-", 9))
1003                 return ENC_QUOTED_PRINTABLE;
1004         else
1005                 return ENC_8BIT;
1006 }
1007
1008 EncodingType procmime_get_encoding_for_file(const gchar *file)
1009 {
1010         FILE *fp;
1011         guchar buf[BUFSIZ];
1012         size_t len;
1013
1014         if ((fp = fopen(file, "rb")) == NULL) {
1015                 FILE_OP_ERROR(file, "fopen");
1016                 return ENC_UNKNOWN;
1017         }
1018
1019         while ((len = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
1020                 guchar *p;
1021                 gint i;
1022
1023                 for (p = buf, i = 0; i < len; p++, i++) {
1024                         if (*p & 0x80) {
1025                                 fclose(fp);
1026                                 return ENC_BASE64;
1027                         }
1028                 }
1029         }
1030
1031         fclose(fp);
1032         return ENC_7BIT;
1033 }
1034
1035 struct EncodingTable 
1036 {
1037         gchar *str;
1038         EncodingType enc_type;
1039 };
1040
1041 struct EncodingTable encoding_table[] = {
1042         {"7bit", ENC_7BIT},
1043         {"8bit", ENC_8BIT},
1044         {"binary", ENC_BINARY},
1045         {"quoted-printable", ENC_QUOTED_PRINTABLE},
1046         {"base64", ENC_BASE64},
1047         {"x-uuencode", ENC_UNKNOWN},
1048         {NULL, ENC_UNKNOWN},
1049 };
1050
1051 const gchar *procmime_get_encoding_str(EncodingType encoding)
1052 {
1053         struct EncodingTable *enc_table;
1054         
1055         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1056                 if (enc_table->enc_type == encoding)
1057                         return enc_table->str;
1058         }
1059         return NULL;
1060 }
1061
1062 /* --- NEW MIME STUFF --- */
1063 struct TypeTable
1064 {
1065         gchar *str;
1066         MimeMediaType type;
1067 };
1068
1069 static struct TypeTable mime_type_table[] = {
1070         {"text", MIMETYPE_TEXT},
1071         {"image", MIMETYPE_IMAGE},
1072         {"audio", MIMETYPE_AUDIO},
1073         {"video", MIMETYPE_VIDEO},
1074         {"application", MIMETYPE_APPLICATION},
1075         {"message", MIMETYPE_MESSAGE},
1076         {"multipart", MIMETYPE_MULTIPART},
1077         {NULL, 0},
1078 };
1079
1080 const gchar *procmime_get_media_type_str(MimeMediaType type)
1081 {
1082         struct TypeTable *type_table;
1083         
1084         for (type_table = mime_type_table; type_table->str != NULL; type_table++) {
1085                 if (type_table->type == type)
1086                         return type_table->str;
1087         }
1088         return NULL;
1089 }
1090
1091 MimeMediaType procmime_get_media_type(const gchar *str)
1092 {
1093         struct TypeTable *typetablearray;
1094
1095         for (typetablearray = mime_type_table; typetablearray->str != NULL; typetablearray++)
1096                 if (g_ascii_strncasecmp(str, typetablearray->str, strlen(typetablearray->str)) == 0)
1097                         return typetablearray->type;
1098
1099         return MIMETYPE_UNKNOWN;
1100 }
1101
1102 /*!
1103  *\brief        Safe wrapper for content type string.
1104  *
1105  *\return       const gchar * Pointer to content type string. 
1106  */
1107 gchar *procmime_get_content_type_str(MimeMediaType type,
1108                                            const char *subtype)
1109 {
1110         const gchar *type_str = NULL;
1111
1112         if (subtype == NULL || !(type_str = procmime_get_media_type_str(type)))
1113                 return g_strdup("unknown");
1114         return g_strdup_printf("%s/%s", type_str, subtype);
1115 }
1116
1117 void procmime_parse_mimepart(MimeInfo *parent,
1118                              gchar *content_type,
1119                              gchar *content_encoding,
1120                              gchar *content_description,
1121                              gchar *content_id,
1122                              gchar *content_disposition,
1123                              const gchar *filename,
1124                              guint offset,
1125                              guint length);
1126
1127 void procmime_parse_message_rfc822(MimeInfo *mimeinfo)
1128 {
1129         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1130                                 {"Content-Transfer-Encoding:",
1131                                                    NULL, FALSE},
1132                                 {"Content-Description:",
1133                                                    NULL, TRUE},
1134                                 {"Content-ID:",
1135                                                    NULL, TRUE},
1136                                 {"Content-Disposition:",
1137                                                    NULL, TRUE},
1138                                 {"MIME-Version:",
1139                                                    NULL, TRUE},
1140                                 {NULL,             NULL, FALSE}};
1141         guint content_start, i;
1142         FILE *fp;
1143         gint mime_major, mime_minor;
1144
1145         procmime_decode_content(mimeinfo);
1146
1147         fp = fopen(mimeinfo->data.filename, "rb");
1148         if (fp == NULL) {
1149                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1150                 return;
1151         }
1152         fseek(fp, mimeinfo->offset, SEEK_SET);
1153         procheader_get_header_fields(fp, hentry);
1154         if (hentry[0].body != NULL)
1155                 conv_unmime_header_overwrite(hentry[0].body);
1156         if (hentry[2].body != NULL)
1157                 conv_unmime_header_overwrite(hentry[2].body);
1158         if (hentry[4].body != NULL)
1159                 conv_unmime_header_overwrite(hentry[4].body);
1160         content_start = ftell(fp);
1161         fclose(fp);
1162
1163         if ((hentry[5].body != NULL) &&
1164             (sscanf(hentry[5].body, "%d.%d", &mime_major, &mime_minor) == 2) &&
1165             (mime_major == 1) && (mime_minor == 0)) {
1166                 procmime_parse_mimepart(mimeinfo,
1167                                         hentry[0].body, hentry[1].body,
1168                                         hentry[2].body, hentry[3].body, 
1169                                         hentry[4].body, 
1170                                         mimeinfo->data.filename, content_start,
1171                                         mimeinfo->length - (content_start - mimeinfo->offset));
1172         } else {
1173                 MimeInfo *subinfo;
1174
1175                 subinfo = procmime_mimeinfo_new();
1176                 subinfo->encoding_type = ENC_UNKNOWN;
1177                 subinfo->type = MIMETYPE_TEXT;
1178                 subinfo->subtype = g_strdup("plain");
1179                 subinfo->data.filename = g_strdup(mimeinfo->data.filename);
1180                 subinfo->offset = content_start;
1181                 subinfo->length = mimeinfo->length - (content_start - mimeinfo->offset);
1182
1183                 g_node_append(mimeinfo->node, subinfo->node);
1184         }
1185         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1186                 g_free(hentry[i].body);
1187                 hentry[i].body = NULL;
1188         }
1189 }
1190
1191 void procmime_parse_multipart(MimeInfo *mimeinfo)
1192 {
1193         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1194                                 {"Content-Transfer-Encoding:",
1195                                                    NULL, FALSE},
1196                                 {"Content-Description:",
1197                                                    NULL, TRUE},
1198                                 {"Content-ID:",
1199                                                    NULL, TRUE},
1200                                 {"Content-Disposition:",
1201                                                    NULL, TRUE},
1202                                 {NULL,             NULL, FALSE}};
1203         gchar *p;
1204         gchar *boundary;
1205         gint boundary_len = 0, lastoffset = -1, i;
1206         gchar buf[BUFFSIZE];
1207         FILE *fp;
1208
1209         boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
1210         if (!boundary)
1211                 return;
1212         boundary_len = strlen(boundary);
1213
1214         procmime_decode_content(mimeinfo);
1215
1216         fp = fopen(mimeinfo->data.filename, "rb");
1217         if (fp == NULL) {
1218                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1219                 return;
1220         }
1221         fseek(fp, mimeinfo->offset, SEEK_SET);
1222         while ((p = fgets(buf, sizeof(buf), fp)) != NULL) {
1223                 if (ftell(fp) > (mimeinfo->offset + mimeinfo->length))
1224                         break;
1225
1226                 if (IS_BOUNDARY(buf, boundary, boundary_len)) {
1227                         if (lastoffset != -1) {
1228                                 procmime_parse_mimepart(mimeinfo,
1229                                                         hentry[0].body, hentry[1].body,
1230                                                         hentry[2].body, hentry[3].body, 
1231                                                         hentry[4].body, 
1232                                                         mimeinfo->data.filename, lastoffset,
1233                                                         (ftell(fp) - strlen(buf)) - lastoffset - 1);
1234                         }
1235                         
1236                         if (buf[2 + boundary_len]     == '-' &&
1237                             buf[2 + boundary_len + 1] == '-')
1238                                 break;
1239
1240                         for (i = 0; i < (sizeof hentry / sizeof hentry[0]) ; i++) {
1241                                 g_free(hentry[i].body);
1242                                 hentry[i].body = NULL;
1243                         }
1244                         procheader_get_header_fields(fp, hentry);
1245                         if (hentry[0].body != NULL)
1246                                 conv_unmime_header_overwrite(hentry[0].body);
1247                         if (hentry[2].body != NULL)
1248                                 conv_unmime_header_overwrite(hentry[2].body);
1249                         if (hentry[4].body != NULL)
1250                                 conv_unmime_header_overwrite(hentry[4].body);
1251                         lastoffset = ftell(fp);
1252                 }
1253         }
1254         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1255                 g_free(hentry[i].body);
1256                 hentry[i].body = NULL;
1257         }
1258         fclose(fp);
1259 }
1260
1261 static void parse_parameters(const gchar *parameters, GHashTable *table)
1262 {
1263         gchar *params, *param, *next;
1264         GSList *convlist = NULL, *concatlist = NULL, *cur;
1265
1266         params = g_strdup(parameters);
1267         param = params;
1268         next = params;
1269         for (; next != NULL; param = next) {
1270                 gchar *attribute, *value, *tmp;
1271                 gint len;
1272                 gboolean convert = FALSE;
1273
1274                 next = strchr_with_skip_quote(param, '"', ';');
1275                 if (next != NULL) {
1276                         next[0] = '\0';
1277                         next++;
1278                 }
1279
1280                 g_strstrip(param);
1281
1282                 attribute = param;
1283                 value = strchr(attribute, '=');
1284                 if (value == NULL)
1285                         continue;
1286
1287                 value[0] = '\0';
1288                 value++;
1289
1290                 g_strdown(attribute);
1291
1292                 len = strlen(attribute);
1293                 if (attribute[len - 1] == '*') {
1294                         gchar *srcpos, *dstpos, *endpos;
1295
1296                         convert = TRUE;
1297                         attribute[len - 1] = '\0';
1298
1299                         srcpos = value;
1300                         dstpos = value;
1301                         endpos = value + strlen(value);
1302                         while (srcpos < endpos) {
1303                                 if (*srcpos != '%')
1304                                         *dstpos = *srcpos;
1305                                 else {
1306                                         guchar dstvalue;
1307
1308                                         if (!get_hex_value(&dstvalue, srcpos[1], srcpos[2]))
1309                                                 *dstpos = '?';
1310                                         else
1311                                                 *dstpos = dstvalue;
1312                                         srcpos += 2;
1313                                 }
1314                                 srcpos++;
1315                                 dstpos++;
1316                         }
1317                         *dstpos = '\0';
1318                 } else {
1319                         if (value[0] == '"')
1320                                 extract_quote(value, '"');
1321                         else if ((tmp = strchr(value, ' ')) != NULL)
1322                                 *tmp = '\0';
1323                 }
1324
1325                 if (strrchr(attribute, '*') != NULL) {
1326                         gchar *tmpattr;
1327
1328                         tmpattr = g_strdup(attribute);
1329                         tmp = strrchr(tmpattr, '*');
1330                         tmp[0] = '\0';
1331
1332                         if ((tmp[1] == '0') && (tmp[2] == '\0') && 
1333                             (g_slist_find_custom(concatlist, attribute, g_str_equal) == NULL))
1334                                 concatlist = g_slist_prepend(concatlist, g_strdup(tmpattr));
1335
1336                         if (convert && (g_slist_find_custom(convlist, attribute, g_str_equal) == NULL))
1337                                 convlist = g_slist_prepend(convlist, g_strdup(tmpattr));
1338
1339                         g_free(tmpattr);
1340                 } else if (convert) {
1341                         if (g_slist_find_custom(convlist, attribute, g_str_equal) == NULL)
1342                                 convlist = g_slist_prepend(convlist, g_strdup(attribute));
1343                 }
1344
1345                 if (g_hash_table_lookup(table, attribute) == NULL)
1346                         g_hash_table_insert(table, g_strdup(attribute), g_strdup(value));
1347         }
1348
1349         for (cur = concatlist; cur != NULL; cur = g_slist_next(cur)) {
1350                 gchar *attribute, *attrwnum, *partvalue;
1351                 gint n = 0;
1352                 GString *value;
1353
1354                 attribute = (gchar *) cur->data;
1355                 value = g_string_sized_new(64);
1356
1357                 attrwnum = g_strdup_printf("%s*%d", attribute, n);
1358                 while ((partvalue = g_hash_table_lookup(table, attrwnum)) != NULL) {
1359                         g_string_append(value, partvalue);
1360
1361                         g_free(attrwnum);
1362                         n++;
1363                         attrwnum = g_strdup_printf("%s*%d", attribute, n);
1364                 }
1365                 g_free(attrwnum);
1366
1367                 g_hash_table_insert(table, g_strdup(attribute), g_strdup(value->str));
1368                 g_string_free(value, TRUE);
1369         }
1370         slist_free_strings(concatlist);
1371         g_slist_free(concatlist);
1372
1373         for (cur = convlist; cur != NULL; cur = g_slist_next(cur)) {
1374                 gchar *attribute, *key, *value;
1375                 gchar *charset, *lang, *oldvalue, *newvalue;
1376
1377                 attribute = (gchar *) cur->data;
1378                 if (!g_hash_table_lookup_extended(table, attribute, (gpointer *) &key, (gpointer *) &value))
1379                         continue;
1380
1381                 charset = value;
1382                 lang = strchr(charset, '\'');
1383                 if (lang == NULL)
1384                         continue;
1385                 lang[0] = '\0';
1386                 lang++;
1387                 oldvalue = strchr(lang, '\'');
1388                 if (oldvalue == NULL)
1389                         continue;
1390                 oldvalue[0] = '\0';
1391                 oldvalue++;
1392
1393                 newvalue = conv_codeset_strdup(oldvalue, charset, CS_UTF_8);
1394
1395                 g_hash_table_remove(table, attribute);
1396                 g_free(key);
1397                 g_free(value);
1398
1399                 g_hash_table_insert(table, g_strdup(attribute), newvalue);
1400         }
1401         slist_free_strings(convlist);
1402         g_slist_free(convlist);
1403
1404         g_free(params);
1405 }       
1406
1407 static void procmime_parse_content_type(const gchar *content_type, MimeInfo *mimeinfo)
1408 {
1409         g_return_if_fail(content_type != NULL);
1410         g_return_if_fail(mimeinfo != NULL);
1411
1412         /* RFC 2045, page 13 says that the mime subtype is MANDATORY;
1413          * if it's not available we use the default Content-Type */
1414         if ((content_type[0] == '\0') || (strchr(content_type, '/') == NULL)) {
1415                 mimeinfo->type = MIMETYPE_TEXT;
1416                 mimeinfo->subtype = g_strdup("plain");
1417                 if (g_hash_table_lookup(mimeinfo->typeparameters,
1418                                        "charset") == NULL)
1419                         g_hash_table_insert(mimeinfo->typeparameters,
1420                                             g_strdup("charset"),
1421                                             g_strdup("us-ascii"));
1422         } else {
1423                 gchar *type, *subtype, *params;
1424
1425                 type = g_strdup(content_type);
1426                 subtype = strchr(type, '/') + 1;
1427                 *(subtype - 1) = '\0';
1428                 if ((params = strchr(subtype, ';')) != NULL) {
1429                         params[0] = '\0';
1430                         params++;
1431                 }
1432
1433                 mimeinfo->type = procmime_get_media_type(type);
1434                 mimeinfo->subtype = g_strdup(subtype);
1435
1436                 /* Get mimeinfo->typeparameters */
1437                 if (params != NULL)
1438                         parse_parameters(params, mimeinfo->typeparameters);
1439
1440                 g_free(type);
1441         }
1442 }
1443
1444 static void procmime_parse_content_disposition(const gchar *content_disposition, MimeInfo *mimeinfo)
1445 {
1446         gchar *tmp, *params;
1447
1448         g_return_if_fail(content_disposition != NULL);
1449         g_return_if_fail(mimeinfo != NULL);
1450
1451         tmp = g_strdup(content_disposition);
1452         if ((params = strchr(tmp, ';')) != NULL) {
1453                 params[0] = '\0';
1454                 params++;
1455         }       
1456         g_strstrip(tmp);
1457
1458         if (!g_ascii_strcasecmp(tmp, "inline")) 
1459                 mimeinfo->disposition = DISPOSITIONTYPE_INLINE;
1460         else if (!g_ascii_strcasecmp(tmp, "attachment"))
1461                 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1462         else
1463                 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1464         
1465         if (params != NULL)
1466                 parse_parameters(params, mimeinfo->dispositionparameters);
1467
1468         g_free(tmp);
1469 }
1470
1471
1472 static void procmime_parse_content_encoding(const gchar *content_encoding, MimeInfo *mimeinfo)
1473 {
1474         struct EncodingTable *enc_table;
1475         
1476         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1477                 if (g_ascii_strcasecmp(enc_table->str, content_encoding) == 0) {
1478                         mimeinfo->encoding_type = enc_table->enc_type;
1479                         return;
1480                 }
1481         }
1482         mimeinfo->encoding_type = ENC_UNKNOWN;
1483         return;
1484 }
1485
1486 void procmime_parse_mimepart(MimeInfo *parent,
1487                              gchar *content_type,
1488                              gchar *content_encoding,
1489                              gchar *content_description,
1490                              gchar *content_id,
1491                              gchar *content_disposition,
1492                              const gchar *filename,
1493                              guint offset,
1494                              guint length)
1495 {
1496         MimeInfo *mimeinfo;
1497
1498         /* Create MimeInfo */
1499         mimeinfo = procmime_mimeinfo_new();
1500         mimeinfo->content = MIMECONTENT_FILE;
1501         if (parent != NULL)
1502                 g_node_append(parent->node, mimeinfo->node);
1503         mimeinfo->data.filename = g_strdup(filename);
1504         mimeinfo->offset = offset;
1505         mimeinfo->length = length;
1506
1507         if (content_type != NULL) {
1508                 procmime_parse_content_type(content_type, mimeinfo);
1509         } else {
1510                 mimeinfo->type = MIMETYPE_TEXT;
1511                 mimeinfo->subtype = g_strdup("plain");
1512                 if (g_hash_table_lookup(mimeinfo->typeparameters,
1513                                        "charset") == NULL)
1514                         g_hash_table_insert(mimeinfo->typeparameters, g_strdup("charset"), g_strdup("us-ascii"));
1515         }
1516
1517         if (content_encoding != NULL) {
1518                 procmime_parse_content_encoding(content_encoding, mimeinfo);
1519         } else {
1520                 mimeinfo->encoding_type = ENC_UNKNOWN;
1521         }
1522
1523         if (content_description != NULL)
1524                 mimeinfo->description = g_strdup(content_description);
1525         else
1526                 mimeinfo->description = NULL;
1527
1528         if (content_id != NULL)
1529                 mimeinfo->id = g_strdup(content_id);
1530         else
1531                 mimeinfo->id = NULL;
1532
1533         if (content_disposition != NULL) 
1534                 procmime_parse_content_disposition(content_disposition, mimeinfo);
1535         else
1536                 mimeinfo->disposition = DISPOSITIONTYPE_UNKNOWN;
1537
1538         /* Call parser for mime type */
1539         switch (mimeinfo->type) {
1540                 case MIMETYPE_MESSAGE:
1541                         if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
1542                                 procmime_parse_message_rfc822(mimeinfo);
1543                         }
1544                         break;
1545                         
1546                 case MIMETYPE_MULTIPART:
1547                         procmime_parse_multipart(mimeinfo);
1548                         break;
1549                         
1550                 default:
1551                         break;
1552         }
1553 }
1554
1555 static gchar *typenames[] = {
1556     "text",
1557     "image",
1558     "audio",
1559     "video",
1560     "application",
1561     "message",
1562     "multipart",
1563     "unknown",
1564 };
1565
1566 static gboolean output_func(GNode *node, gpointer data)
1567 {
1568         guint i, depth;
1569         MimeInfo *mimeinfo = (MimeInfo *) node->data;
1570
1571         depth = g_node_depth(node);
1572         for (i = 0; i < depth; i++)
1573                 printf("    ");
1574         printf("%s/%s (offset:%d length:%d encoding: %d)\n", typenames[mimeinfo->type], mimeinfo->subtype, mimeinfo->offset, mimeinfo->length, mimeinfo->encoding_type);
1575
1576         return FALSE;
1577 }
1578
1579 static void output_mime_structure(MimeInfo *mimeinfo, int indent)
1580 {
1581         g_node_traverse(mimeinfo->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1, output_func, NULL);
1582 }
1583
1584 MimeInfo *procmime_scan_file_with_offset(const gchar *filename, int offset)
1585 {
1586         MimeInfo *mimeinfo;
1587         struct stat buf;
1588
1589         stat(filename, &buf);
1590
1591         mimeinfo = procmime_mimeinfo_new();
1592         mimeinfo->content = MIMECONTENT_FILE;
1593         mimeinfo->encoding_type = ENC_UNKNOWN;
1594         mimeinfo->type = MIMETYPE_MESSAGE;
1595         mimeinfo->subtype = g_strdup("rfc822");
1596         mimeinfo->data.filename = g_strdup(filename);
1597         mimeinfo->offset = offset;
1598         mimeinfo->length = buf.st_size - offset;
1599
1600         procmime_parse_message_rfc822(mimeinfo);
1601         if (debug_get_mode())
1602                 output_mime_structure(mimeinfo, 0);
1603
1604         return mimeinfo;
1605 }
1606
1607 MimeInfo *procmime_scan_file(const gchar *filename)
1608 {
1609         MimeInfo *mimeinfo;
1610
1611         g_return_val_if_fail(filename != NULL, NULL);
1612
1613         mimeinfo = procmime_scan_file_with_offset(filename, 0);
1614
1615         return mimeinfo;
1616 }
1617
1618 MimeInfo *procmime_scan_queue_file(const gchar *filename)
1619 {
1620         FILE *fp;
1621         MimeInfo *mimeinfo;
1622         gchar buf[BUFFSIZE];
1623         gint offset = 0;
1624
1625         g_return_val_if_fail(filename != NULL, NULL);
1626
1627         /* Open file */
1628         if ((fp = fopen(filename, "rb")) == NULL)
1629                 return NULL;
1630         /* Skip queue header */
1631         while (fgets(buf, sizeof(buf), fp) != NULL)
1632                 if (buf[0] == '\r' || buf[0] == '\n') break;
1633         offset = ftell(fp);
1634         fclose(fp);
1635
1636         mimeinfo = procmime_scan_file_with_offset(filename, offset);
1637
1638         return mimeinfo;
1639 }
1640
1641 typedef enum {
1642     ENC_AS_TOKEN,
1643     ENC_AS_QUOTED_STRING,
1644     ENC_AS_EXTENDED,
1645 } EncodeAs;
1646
1647 static void write_parameters(gpointer key, gpointer value, gpointer user_data)
1648 {
1649         gchar *param = key;
1650         gchar *val = value, *valpos;
1651         FILE *fp = user_data;
1652         EncodeAs encas = ENC_AS_TOKEN;
1653
1654         for (valpos = val; *valpos != 0; valpos++) {
1655                 if (!IS_ASCII(*valpos)) {
1656                         encas = ENC_AS_EXTENDED;
1657                         break;
1658                 }
1659             
1660                 /* CTLs */
1661                 if (((*valpos >= 0) && (*valpos < 037)) || (*valpos == 0177)) {
1662                         encas = ENC_AS_QUOTED_STRING;
1663                         continue;
1664                 }
1665
1666                 /* tspecials + SPACE */
1667                 switch (*valpos) {
1668                 case ' ':
1669                 case '(': 
1670                 case ')':
1671                 case '<':
1672                 case '>':
1673                 case '@':
1674                 case ',':
1675                 case ';':
1676                 case ':':
1677                 case '\\':
1678                 case '"':
1679                 case '/':
1680                 case '[':
1681                 case ']':
1682                 case '?':
1683                 case '=':
1684                         encas = ENC_AS_QUOTED_STRING;
1685                         continue;
1686                 }
1687         }
1688
1689         switch (encas) {
1690         case ENC_AS_TOKEN:
1691                 fprintf(fp, "; %s=", param);
1692                 fprintf(fp, "%s", val);
1693                 break;
1694
1695         case ENC_AS_QUOTED_STRING:
1696                 fprintf(fp, "; %s=", param);
1697                 fprintf(fp, "\"%s\"", val);
1698                 break;
1699
1700         case ENC_AS_EXTENDED:
1701                 fprintf(fp, "; %s*=", param);
1702                 fprintf(fp, "%s''", conv_get_current_charset_str());
1703                 for (valpos = val; *valpos != '\0'; valpos++) {
1704                         if (IS_ASCII(*valpos) && isalnum(*valpos))
1705                                 fprintf(fp, "%c", *valpos);
1706                         else {
1707                                 gchar hexstr[3] = "XX";
1708                                 get_hex_str(hexstr, *valpos);
1709                                 fprintf(fp, "%%%s", hexstr);
1710                         }
1711                 }
1712                 break;
1713         }
1714 }
1715
1716 void procmime_write_mime_header(MimeInfo *mimeinfo, FILE *fp)
1717 {
1718         struct TypeTable *type_table;
1719
1720         debug_print("procmime_write_mime_header\n");
1721
1722         for (type_table = mime_type_table; type_table->str != NULL; type_table++)
1723                 if (mimeinfo->type == type_table->type) {
1724                         fprintf(fp, "Content-Type: %s/%s", type_table->str, mimeinfo->subtype);
1725                         break;
1726                 }
1727         g_hash_table_foreach(mimeinfo->typeparameters, write_parameters, fp);
1728         fprintf(fp, "\n");
1729
1730         if (mimeinfo->encoding_type != ENC_UNKNOWN)
1731                 fprintf(fp, "Content-Transfer-Encoding: %s\n", procmime_get_encoding_str(mimeinfo->encoding_type));
1732
1733         if (mimeinfo->description != NULL)
1734                 fprintf(fp, "Content-Description: %s\n", mimeinfo->description);
1735
1736         if (mimeinfo->id != NULL)
1737                 fprintf(fp, "Content-ID: %s\n", mimeinfo->id);
1738
1739         if (mimeinfo->disposition != DISPOSITIONTYPE_UNKNOWN) {
1740                 fprintf(fp, "Content-Disposition: ");
1741                 if (mimeinfo->disposition == DISPOSITIONTYPE_INLINE)
1742                         fprintf(fp, "inline");
1743                 else if (mimeinfo->disposition == DISPOSITIONTYPE_ATTACHMENT)
1744                         fprintf(fp, "attachment");
1745                 else
1746                         fprintf(fp, "unknown");
1747
1748                 /* FIXME: linebreaks after too many parameters */
1749                 g_hash_table_foreach(mimeinfo->dispositionparameters, write_parameters, fp);
1750                 fprintf(fp, "\n");
1751         }
1752
1753         fprintf(fp, "\n");
1754 }
1755
1756 gint procmime_write_message_rfc822(MimeInfo *mimeinfo, FILE *fp)
1757 {
1758         FILE *infp;
1759         GNode *childnode;
1760         MimeInfo *child;
1761         gchar buf[BUFFSIZE];
1762         gboolean skip = FALSE;;
1763
1764         debug_print("procmime_write_message_rfc822\n");
1765
1766         /* write header */
1767         switch (mimeinfo->content) {
1768         case MIMECONTENT_FILE:
1769                 if ((infp = fopen(mimeinfo->data.filename, "rb")) == NULL) {
1770                         FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1771                         return -1;
1772                 }
1773                 fseek(infp, mimeinfo->offset, SEEK_SET);
1774                 while (fgets(buf, sizeof(buf), infp) == buf) {
1775                         if (buf[0] == '\n' && buf[1] == '\0')
1776                                 break;
1777                         if (skip && (buf[0] == ' ' || buf[0] == '\t'))
1778                                 continue;
1779                         if (g_ascii_strncasecmp(buf, "Mime-Version:", 13) == 0 ||
1780                             g_ascii_strncasecmp(buf, "Content-Type:", 13) == 0 ||
1781                             g_ascii_strncasecmp(buf, "Content-Transfer-Encoding:", 26) == 0 ||
1782                             g_ascii_strncasecmp(buf, "Content-Description:", 20) == 0 ||
1783                             g_ascii_strncasecmp(buf, "Content-ID:", 11) == 0 ||
1784                             g_ascii_strncasecmp(buf, "Content-Disposition:", 20) == 0) {
1785                                 skip = TRUE;
1786                                 continue;
1787                         }
1788                         fwrite(buf, sizeof(gchar), strlen(buf), fp);
1789                         skip = FALSE;
1790                 }
1791                 fclose(infp);
1792                 break;
1793
1794         case MIMECONTENT_MEM:
1795                 fwrite(mimeinfo->data.mem, strlen(mimeinfo->data.mem), sizeof(gchar), fp);
1796                 break;
1797
1798         default:
1799                 break;
1800         }
1801
1802         childnode = mimeinfo->node->children;
1803         if (childnode == NULL)
1804                 return -1;
1805
1806         child = (MimeInfo *) childnode->data;
1807         fprintf(fp, "Mime-Version: 1.0\n");
1808         procmime_write_mime_header(child, fp);
1809         return procmime_write_mimeinfo(child, fp);
1810 }
1811
1812 gint procmime_write_multipart(MimeInfo *mimeinfo, FILE *fp)
1813 {
1814         FILE *infp;
1815         GNode *childnode;
1816         gchar *boundary, *str, *str2;
1817         gchar buf[BUFFSIZE];
1818         gboolean firstboundary;
1819
1820         debug_print("procmime_write_multipart\n");
1821
1822         boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
1823
1824         switch (mimeinfo->content) {
1825         case MIMECONTENT_FILE:
1826                 if ((infp = fopen(mimeinfo->data.filename, "rb")) == NULL) {
1827                         FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1828                         return -1;
1829                 }
1830                 fseek(infp, mimeinfo->offset, SEEK_SET);
1831                 while (fgets(buf, sizeof(buf), infp) == buf) {
1832                         if (IS_BOUNDARY(buf, boundary, strlen(boundary)))
1833                                 break;
1834                         fwrite(buf, sizeof(gchar), strlen(buf), fp);
1835                 }
1836                 fclose(infp);
1837                 break;
1838
1839         case MIMECONTENT_MEM:
1840                 str = g_strdup(mimeinfo->data.mem);
1841                 if (((str2 = strstr(str, boundary)) != NULL) && ((str2 - str) >= 2) &&
1842                     (*(str2 - 1) == '-') && (*(str2 - 2) == '-'))
1843                         *(str2 - 2) = '\0';
1844                 fwrite(str, strlen(str), sizeof(gchar), fp);
1845                 g_free(str);
1846                 break;
1847
1848         default:
1849                 break;
1850         }
1851
1852         childnode = mimeinfo->node->children;
1853         firstboundary = TRUE;
1854         while (childnode != NULL) {
1855                 MimeInfo *child = childnode->data;
1856
1857                 if (firstboundary)
1858                         firstboundary = FALSE;
1859                 else
1860                         fprintf(fp, "\n");
1861                 fprintf(fp, "--%s\n", boundary);
1862
1863                 procmime_write_mime_header(child, fp);
1864                 if (procmime_write_mimeinfo(child, fp) < 0)
1865                         return -1;
1866
1867                 childnode = g_node_next_sibling(childnode);
1868         }       
1869         fprintf(fp, "\n--%s--\n", boundary);
1870
1871         return 0;
1872 }
1873
1874 gint procmime_write_mimeinfo(MimeInfo *mimeinfo, FILE *fp)
1875 {
1876         FILE *infp;
1877
1878         debug_print("procmime_write_mimeinfo\n");
1879
1880         if (G_NODE_IS_LEAF(mimeinfo->node)) {
1881                 switch (mimeinfo->content) {
1882                 case MIMECONTENT_FILE:
1883                         if ((infp = fopen(mimeinfo->data.filename, "rb")) == NULL) {
1884                                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1885                                 return -1;
1886                         }
1887                         copy_file_part_to_fp(infp, mimeinfo->offset, mimeinfo->length, fp);
1888                         fclose(infp);
1889                         return 0;
1890
1891                 case MIMECONTENT_MEM:
1892                         fwrite(mimeinfo->data.mem, strlen(mimeinfo->data.mem), sizeof(gchar), fp);
1893                         return 0;
1894
1895                 default:
1896                         return 0;
1897                 }
1898         } else {
1899                 /* Call writer for mime type */
1900                 switch (mimeinfo->type) {
1901                 case MIMETYPE_MESSAGE:
1902                         if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0)
1903                                 return procmime_write_message_rfc822(mimeinfo, fp);
1904                         break;
1905                         
1906                 case MIMETYPE_MULTIPART:
1907                         return procmime_write_multipart(mimeinfo, fp);
1908                         
1909                 default:
1910                         break;
1911                 }
1912
1913                 return -1;
1914         }
1915
1916         return 0;
1917 }