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