2004-11-13 [paul] 0.9.12cvs146.8
[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         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                 gchar *basename;
818
819                 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
820                 if (basetmp == NULL)
821                         basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
822                 if (basetmp == NULL)
823                         basetmp = "mimetmp";
824                 basename = g_path_get_basename(basetmp);
825                 if (*base == '\0') base = "mimetmp";
826                 Xstrdup_a(base, basename, {g_free(basename); return NULL;});
827                 subst_for_shellsafe_filename(base);
828                 g_free(basename);
829         }
830
831         filename = g_strconcat(get_mime_tmp_dir(), G_DIR_SEPARATOR_S,
832                                f_prefix, base, NULL);
833
834         return filename;
835 }
836
837 static GList *mime_type_list = NULL;
838
839 gchar *procmime_get_mime_type(const gchar *filename)
840 {
841         static GHashTable *mime_type_table = NULL;
842         MimeType *mime_type;
843         const gchar *p;
844         gchar *ext;
845         gchar *base;
846
847         if (!mime_type_table) {
848                 mime_type_table = procmime_get_mime_type_table();
849                 if (!mime_type_table) return NULL;
850         }
851
852         base = g_path_get_basename(filename);
853         p = strrchr(base, '.');
854         g_free(base);
855         if (!p) return NULL;
856
857         Xstrdup_a(ext, p + 1, return NULL);
858         g_strdown(ext);
859         mime_type = g_hash_table_lookup(mime_type_table, ext);
860         if (mime_type) {
861                 gchar *str;
862
863                 str = g_strconcat(mime_type->type, "/", mime_type->sub_type,
864                                   NULL);
865                 return str;
866         }
867
868         return NULL;
869 }
870
871 static guint procmime_str_hash(gconstpointer gptr)
872 {
873         guint hash_result = 0;
874         const char *str;
875
876         for (str = gptr; str && *str; str++) {
877                 if (isupper(*str)) hash_result += (*str + ' ');
878                 else hash_result += *str;
879         }
880
881         return hash_result;
882 }
883
884 static gint procmime_str_equal(gconstpointer gptr1, gconstpointer gptr2)
885 {
886         const char *str1 = gptr1;
887         const char *str2 = gptr2;
888
889         return !g_utf8_collate(str1, str2);
890 }
891
892 static GHashTable *procmime_get_mime_type_table(void)
893 {
894         GHashTable *table = NULL;
895         GList *cur;
896         MimeType *mime_type;
897         gchar **exts;
898
899         if (!mime_type_list) {
900                 mime_type_list = procmime_get_mime_type_list();
901                 if (!mime_type_list) return NULL;
902         }
903
904         table = g_hash_table_new(procmime_str_hash, procmime_str_equal);
905
906         for (cur = mime_type_list; cur != NULL; cur = cur->next) {
907                 gint i;
908                 gchar *key;
909
910                 mime_type = (MimeType *)cur->data;
911
912                 if (!mime_type->extension) continue;
913
914                 exts = g_strsplit(mime_type->extension, " ", 16);
915                 for (i = 0; exts[i] != NULL; i++) {
916                         /* make the key case insensitive */
917                         g_strdown(exts[i]);
918                         /* use previously dup'd key on overwriting */
919                         if (g_hash_table_lookup(table, exts[i]))
920                                 key = exts[i];
921                         else
922                                 key = g_strdup(exts[i]);
923                         g_hash_table_insert(table, key, mime_type);
924                 }
925                 g_strfreev(exts);
926         }
927
928         return table;
929 }
930
931 GList *procmime_get_mime_type_list(void)
932 {
933         GList *list = NULL;
934         FILE *fp;
935         gchar buf[BUFFSIZE];
936         guchar *p;
937         gchar *delim;
938         MimeType *mime_type;
939
940         if (mime_type_list) 
941                 return mime_type_list;
942
943         if ((fp = fopen("/etc/mime.types", "rb")) == NULL) {
944                 if ((fp = fopen(SYSCONFDIR "/mime.types", "rb")) == NULL) {
945                         FILE_OP_ERROR(SYSCONFDIR "/mime.types", "fopen");
946                         return NULL;
947                 }
948         }
949
950         while (fgets(buf, sizeof(buf), fp) != NULL) {
951                 p = strchr(buf, '#');
952                 if (p) *p = '\0';
953                 g_strstrip(buf);
954
955                 p = buf;
956                 while (*p && !isspace(*p)) p++;
957                 if (*p) {
958                         *p = '\0';
959                         p++;
960                 }
961                 delim = strchr(buf, '/');
962                 if (delim == NULL) continue;
963                 *delim = '\0';
964
965                 mime_type = g_new(MimeType, 1);
966                 mime_type->type = g_strdup(buf);
967                 mime_type->sub_type = g_strdup(delim + 1);
968
969                 while (*p && isspace(*p)) p++;
970                 if (*p)
971                         mime_type->extension = g_strdup(p);
972                 else
973                         mime_type->extension = NULL;
974
975                 list = g_list_append(list, mime_type);
976         }
977
978         fclose(fp);
979
980         if (!list)
981                 g_warning("Can't read mime.types\n");
982
983         return list;
984 }
985
986 EncodingType procmime_get_encoding_for_charset(const gchar *charset)
987 {
988         if (!charset)
989                 return ENC_8BIT;
990         else if (!g_ascii_strncasecmp(charset, "ISO-2022-", 9) ||
991                  !g_ascii_strcasecmp(charset, "US-ASCII"))
992                 return ENC_7BIT;
993         else if (!g_ascii_strcasecmp(charset, "ISO-8859-5") ||
994                  !g_ascii_strncasecmp(charset, "KOI8-", 5) ||
995                  !g_ascii_strcasecmp(charset, "Windows-1251"))
996                 return ENC_8BIT;
997         else if (!g_ascii_strncasecmp(charset, "ISO-8859-", 9))
998                 return ENC_QUOTED_PRINTABLE;
999         else
1000                 return ENC_8BIT;
1001 }
1002
1003 EncodingType procmime_get_encoding_for_file(const gchar *file)
1004 {
1005         FILE *fp;
1006         guchar buf[BUFSIZ];
1007         size_t len;
1008
1009         if ((fp = fopen(file, "rb")) == NULL) {
1010                 FILE_OP_ERROR(file, "fopen");
1011                 return ENC_UNKNOWN;
1012         }
1013
1014         while ((len = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
1015                 guchar *p;
1016                 gint i;
1017
1018                 for (p = buf, i = 0; i < len; p++, i++) {
1019                         if (*p & 0x80) {
1020                                 fclose(fp);
1021                                 return ENC_BASE64;
1022                         }
1023                 }
1024         }
1025
1026         fclose(fp);
1027         return ENC_7BIT;
1028 }
1029
1030 struct EncodingTable 
1031 {
1032         gchar *str;
1033         EncodingType enc_type;
1034 };
1035
1036 struct EncodingTable encoding_table[] = {
1037         {"7bit", ENC_7BIT},
1038         {"8bit", ENC_8BIT},
1039         {"binary", ENC_BINARY},
1040         {"quoted-printable", ENC_QUOTED_PRINTABLE},
1041         {"base64", ENC_BASE64},
1042         {"x-uuencode", ENC_UNKNOWN},
1043         {NULL, ENC_UNKNOWN},
1044 };
1045
1046 const gchar *procmime_get_encoding_str(EncodingType encoding)
1047 {
1048         struct EncodingTable *enc_table;
1049         
1050         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1051                 if (enc_table->enc_type == encoding)
1052                         return enc_table->str;
1053         }
1054         return NULL;
1055 }
1056
1057 /* --- NEW MIME STUFF --- */
1058 struct TypeTable
1059 {
1060         gchar *str;
1061         MimeMediaType type;
1062 };
1063
1064 static struct TypeTable mime_type_table[] = {
1065         {"text", MIMETYPE_TEXT},
1066         {"image", MIMETYPE_IMAGE},
1067         {"audio", MIMETYPE_AUDIO},
1068         {"video", MIMETYPE_VIDEO},
1069         {"application", MIMETYPE_APPLICATION},
1070         {"message", MIMETYPE_MESSAGE},
1071         {"multipart", MIMETYPE_MULTIPART},
1072         {NULL, 0},
1073 };
1074
1075 const gchar *procmime_get_media_type_str(MimeMediaType type)
1076 {
1077         struct TypeTable *type_table;
1078         
1079         for (type_table = mime_type_table; type_table->str != NULL; type_table++) {
1080                 if (type_table->type == type)
1081                         return type_table->str;
1082         }
1083         return NULL;
1084 }
1085
1086 MimeMediaType procmime_get_media_type(const gchar *str)
1087 {
1088         struct TypeTable *typetablearray;
1089
1090         for (typetablearray = mime_type_table; typetablearray->str != NULL; typetablearray++)
1091                 if (g_ascii_strncasecmp(str, typetablearray->str, strlen(typetablearray->str)) == 0)
1092                         return typetablearray->type;
1093
1094         return MIMETYPE_UNKNOWN;
1095 }
1096
1097 /*!
1098  *\brief        Safe wrapper for content type string.
1099  *
1100  *\return       const gchar * Pointer to content type string. 
1101  */
1102 gchar *procmime_get_content_type_str(MimeMediaType type,
1103                                            const char *subtype)
1104 {
1105         const gchar *type_str = NULL;
1106
1107         if (subtype == NULL || !(type_str = procmime_get_media_type_str(type)))
1108                 return g_strdup("unknown");
1109         return g_strdup_printf("%s/%s", type_str, subtype);
1110 }
1111
1112 void procmime_parse_mimepart(MimeInfo *parent,
1113                              gchar *content_type,
1114                              gchar *content_encoding,
1115                              gchar *content_description,
1116                              gchar *content_id,
1117                              gchar *content_disposition,
1118                              const gchar *filename,
1119                              guint offset,
1120                              guint length);
1121
1122 void procmime_parse_message_rfc822(MimeInfo *mimeinfo)
1123 {
1124         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1125                                 {"Content-Transfer-Encoding:",
1126                                                    NULL, FALSE},
1127                                 {"Content-Description:",
1128                                                    NULL, TRUE},
1129                                 {"Content-ID:",
1130                                                    NULL, TRUE},
1131                                 {"Content-Disposition:",
1132                                                    NULL, TRUE},
1133                                 {"MIME-Version:",
1134                                                    NULL, TRUE},
1135                                 {NULL,             NULL, FALSE}};
1136         guint content_start, i;
1137         FILE *fp;
1138         gint mime_major, mime_minor;
1139
1140         procmime_decode_content(mimeinfo);
1141
1142         fp = fopen(mimeinfo->data.filename, "rb");
1143         if (fp == NULL) {
1144                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1145                 return;
1146         }
1147         fseek(fp, mimeinfo->offset, SEEK_SET);
1148         procheader_get_header_fields(fp, hentry);
1149         if (hentry[0].body != NULL)
1150                 conv_unmime_header_overwrite(hentry[0].body);
1151         if (hentry[2].body != NULL)
1152                 conv_unmime_header_overwrite(hentry[2].body);
1153         if (hentry[4].body != NULL)
1154                 conv_unmime_header_overwrite(hentry[4].body);
1155         content_start = ftell(fp);
1156         fclose(fp);
1157
1158         if ((hentry[5].body != NULL) &&
1159             (sscanf(hentry[5].body, "%d.%d", &mime_major, &mime_minor) == 2) &&
1160             (mime_major == 1) && (mime_minor == 0)) {
1161                 procmime_parse_mimepart(mimeinfo,
1162                                         hentry[0].body, hentry[1].body,
1163                                         hentry[2].body, hentry[3].body, 
1164                                         hentry[4].body, 
1165                                         mimeinfo->data.filename, content_start,
1166                                         mimeinfo->length - (content_start - mimeinfo->offset));
1167         } else {
1168                 MimeInfo *subinfo;
1169
1170                 subinfo = procmime_mimeinfo_new();
1171                 subinfo->encoding_type = ENC_UNKNOWN;
1172                 subinfo->type = MIMETYPE_TEXT;
1173                 subinfo->subtype = g_strdup("plain");
1174                 subinfo->data.filename = g_strdup(mimeinfo->data.filename);
1175                 subinfo->offset = content_start;
1176                 subinfo->length = mimeinfo->length - (content_start - mimeinfo->offset);
1177
1178                 g_node_append(mimeinfo->node, subinfo->node);
1179         }
1180         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1181                 g_free(hentry[i].body);
1182                 hentry[i].body = NULL;
1183         }
1184 }
1185
1186 void procmime_parse_multipart(MimeInfo *mimeinfo)
1187 {
1188         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1189                                 {"Content-Transfer-Encoding:",
1190                                                    NULL, FALSE},
1191                                 {"Content-Description:",
1192                                                    NULL, TRUE},
1193                                 {"Content-ID:",
1194                                                    NULL, TRUE},
1195                                 {"Content-Disposition:",
1196                                                    NULL, TRUE},
1197                                 {NULL,             NULL, FALSE}};
1198         gchar *p;
1199         gchar *boundary;
1200         gint boundary_len = 0, lastoffset = -1, i;
1201         gchar buf[BUFFSIZE];
1202         FILE *fp;
1203
1204         boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
1205         if (!boundary)
1206                 return;
1207         boundary_len = strlen(boundary);
1208
1209         procmime_decode_content(mimeinfo);
1210
1211         fp = fopen(mimeinfo->data.filename, "rb");
1212         if (fp == NULL) {
1213                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1214                 return;
1215         }
1216         fseek(fp, mimeinfo->offset, SEEK_SET);
1217         while ((p = fgets(buf, sizeof(buf), fp)) != NULL) {
1218                 if (ftell(fp) > (mimeinfo->offset + mimeinfo->length))
1219                         break;
1220
1221                 if (IS_BOUNDARY(buf, boundary, boundary_len)) {
1222                         if (lastoffset != -1) {
1223                                 procmime_parse_mimepart(mimeinfo,
1224                                                         hentry[0].body, hentry[1].body,
1225                                                         hentry[2].body, hentry[3].body, 
1226                                                         hentry[4].body, 
1227                                                         mimeinfo->data.filename, lastoffset,
1228                                                         (ftell(fp) - strlen(buf)) - lastoffset - 1);
1229                         }
1230                         
1231                         if (buf[2 + boundary_len]     == '-' &&
1232                             buf[2 + boundary_len + 1] == '-')
1233                                 break;
1234
1235                         for (i = 0; i < (sizeof hentry / sizeof hentry[0]) ; i++) {
1236                                 g_free(hentry[i].body);
1237                                 hentry[i].body = NULL;
1238                         }
1239                         procheader_get_header_fields(fp, hentry);
1240                         if (hentry[0].body != NULL)
1241                                 conv_unmime_header_overwrite(hentry[0].body);
1242                         if (hentry[2].body != NULL)
1243                                 conv_unmime_header_overwrite(hentry[2].body);
1244                         if (hentry[4].body != NULL)
1245                                 conv_unmime_header_overwrite(hentry[4].body);
1246                         lastoffset = ftell(fp);
1247                 }
1248         }
1249         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1250                 g_free(hentry[i].body);
1251                 hentry[i].body = NULL;
1252         }
1253         fclose(fp);
1254 }
1255
1256 static void parse_parameters(const gchar *parameters, GHashTable *table)
1257 {
1258         gchar *params, *param, *next;
1259         GSList *convlist = NULL, *concatlist = NULL, *cur;
1260
1261         params = g_strdup(parameters);
1262         param = params;
1263         next = params;
1264         for (; next != NULL; param = next) {
1265                 gchar *attribute, *value, *tmp;
1266                 gint len;
1267                 gboolean convert = FALSE;
1268
1269                 next = strchr_with_skip_quote(param, '"', ';');
1270                 if (next != NULL) {
1271                         next[0] = '\0';
1272                         next++;
1273                 }
1274
1275                 g_strstrip(param);
1276
1277                 attribute = param;
1278                 value = strchr(attribute, '=');
1279                 if (value == NULL)
1280                         continue;
1281
1282                 value[0] = '\0';
1283                 value++;
1284
1285                 g_strdown(attribute);
1286
1287                 len = strlen(attribute);
1288                 if (attribute[len - 1] == '*') {
1289                         gchar *srcpos, *dstpos, *endpos;
1290
1291                         convert = TRUE;
1292                         attribute[len - 1] = '\0';
1293
1294                         srcpos = value;
1295                         dstpos = value;
1296                         endpos = value + strlen(value);
1297                         while (srcpos < endpos) {
1298                                 if (*srcpos != '%')
1299                                         *dstpos = *srcpos;
1300                                 else {
1301                                         guchar dstvalue;
1302
1303                                         if (!get_hex_value(&dstvalue, srcpos[1], srcpos[2]))
1304                                                 *dstpos = '?';
1305                                         else
1306                                                 *dstpos = dstvalue;
1307                                         srcpos += 2;
1308                                 }
1309                                 srcpos++;
1310                                 dstpos++;
1311                         }
1312                         *dstpos = '\0';
1313                 } else {
1314                         if (value[0] == '"')
1315                                 extract_quote(value, '"');
1316                         else if ((tmp = strchr(value, ' ')) != NULL)
1317                                 *tmp = '\0';
1318                 }
1319
1320                 if (strrchr(attribute, '*') != NULL) {
1321                         gchar *tmpattr;
1322
1323                         tmpattr = g_strdup(attribute);
1324                         tmp = strrchr(tmpattr, '*');
1325                         tmp[0] = '\0';
1326
1327                         if ((tmp[1] == '0') && (tmp[2] == '\0') && 
1328                             (g_slist_find_custom(concatlist, attribute, g_str_equal) == NULL))
1329                                 concatlist = g_slist_prepend(concatlist, g_strdup(tmpattr));
1330
1331                         if (convert && (g_slist_find_custom(convlist, attribute, g_str_equal) == NULL))
1332                                 convlist = g_slist_prepend(convlist, g_strdup(tmpattr));
1333
1334                         g_free(tmpattr);
1335                 } else if (convert) {
1336                         if (g_slist_find_custom(convlist, attribute, g_str_equal) == NULL)
1337                                 convlist = g_slist_prepend(convlist, g_strdup(attribute));
1338                 }
1339
1340                 if (g_hash_table_lookup(table, attribute) == NULL)
1341                         g_hash_table_insert(table, g_strdup(attribute), g_strdup(value));
1342         }
1343
1344         for (cur = concatlist; cur != NULL; cur = g_slist_next(cur)) {
1345                 gchar *attribute, *attrwnum, *partvalue;
1346                 gint n = 0;
1347                 GString *value;
1348
1349                 attribute = (gchar *) cur->data;
1350                 value = g_string_sized_new(64);
1351
1352                 attrwnum = g_strdup_printf("%s*%d", attribute, n);
1353                 while ((partvalue = g_hash_table_lookup(table, attrwnum)) != NULL) {
1354                         g_string_append(value, partvalue);
1355
1356                         g_free(attrwnum);
1357                         n++;
1358                         attrwnum = g_strdup_printf("%s*%d", attribute, n);
1359                 }
1360                 g_free(attrwnum);
1361
1362                 g_hash_table_insert(table, g_strdup(attribute), g_strdup(value->str));
1363                 g_string_free(value, TRUE);
1364         }
1365         slist_free_strings(concatlist);
1366         g_slist_free(concatlist);
1367
1368         for (cur = convlist; cur != NULL; cur = g_slist_next(cur)) {
1369                 gchar *attribute, *key, *value;
1370                 gchar *charset, *lang, *oldvalue, *newvalue;
1371
1372                 attribute = (gchar *) cur->data;
1373                 if (!g_hash_table_lookup_extended(table, attribute, (gpointer *) &key, (gpointer *) &value))
1374                         continue;
1375
1376                 charset = value;
1377                 lang = strchr(charset, '\'');
1378                 if (lang == NULL)
1379                         continue;
1380                 lang[0] = '\0';
1381                 lang++;
1382                 oldvalue = strchr(lang, '\'');
1383                 if (oldvalue == NULL)
1384                         continue;
1385                 oldvalue[0] = '\0';
1386                 oldvalue++;
1387
1388                 newvalue = conv_codeset_strdup(oldvalue, charset, CS_UTF_8);
1389
1390                 g_hash_table_remove(table, attribute);
1391                 g_free(key);
1392                 g_free(value);
1393
1394                 g_hash_table_insert(table, g_strdup(attribute), newvalue);
1395         }
1396         slist_free_strings(convlist);
1397         g_slist_free(convlist);
1398
1399         g_free(params);
1400 }       
1401
1402 static void procmime_parse_content_type(const gchar *content_type, MimeInfo *mimeinfo)
1403 {
1404         g_return_if_fail(content_type != NULL);
1405         g_return_if_fail(mimeinfo != NULL);
1406
1407         /* RFC 2045, page 13 says that the mime subtype is MANDATORY;
1408          * if it's not available we use the default Content-Type */
1409         if ((content_type[0] == '\0') || (strchr(content_type, '/') == NULL)) {
1410                 mimeinfo->type = MIMETYPE_TEXT;
1411                 mimeinfo->subtype = g_strdup("plain");
1412                 if (g_hash_table_lookup(mimeinfo->typeparameters,
1413                                        "charset") == NULL)
1414                         g_hash_table_insert(mimeinfo->typeparameters,
1415                                             g_strdup("charset"),
1416                                             g_strdup("us-ascii"));
1417         } else {
1418                 gchar *type, *subtype, *params;
1419
1420                 type = g_strdup(content_type);
1421                 subtype = strchr(type, '/') + 1;
1422                 *(subtype - 1) = '\0';
1423                 if ((params = strchr(subtype, ';')) != NULL) {
1424                         params[0] = '\0';
1425                         params++;
1426                 }
1427
1428                 mimeinfo->type = procmime_get_media_type(type);
1429                 mimeinfo->subtype = g_strdup(subtype);
1430
1431                 /* Get mimeinfo->typeparameters */
1432                 if (params != NULL)
1433                         parse_parameters(params, mimeinfo->typeparameters);
1434
1435                 g_free(type);
1436         }
1437 }
1438
1439 static void procmime_parse_content_disposition(const gchar *content_disposition, MimeInfo *mimeinfo)
1440 {
1441         gchar *tmp, *params;
1442
1443         g_return_if_fail(content_disposition != NULL);
1444         g_return_if_fail(mimeinfo != NULL);
1445
1446         tmp = g_strdup(content_disposition);
1447         if ((params = strchr(tmp, ';')) != NULL) {
1448                 params[0] = '\0';
1449                 params++;
1450         }       
1451         g_strstrip(tmp);
1452
1453         if (!g_ascii_strcasecmp(tmp, "inline")) 
1454                 mimeinfo->disposition = DISPOSITIONTYPE_INLINE;
1455         else if (!g_ascii_strcasecmp(tmp, "attachment"))
1456                 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1457         else
1458                 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1459         
1460         if (params != NULL)
1461                 parse_parameters(params, mimeinfo->dispositionparameters);
1462
1463         g_free(tmp);
1464 }
1465
1466
1467 static void procmime_parse_content_encoding(const gchar *content_encoding, MimeInfo *mimeinfo)
1468 {
1469         struct EncodingTable *enc_table;
1470         
1471         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1472                 if (g_ascii_strcasecmp(enc_table->str, content_encoding) == 0) {
1473                         mimeinfo->encoding_type = enc_table->enc_type;
1474                         return;
1475                 }
1476         }
1477         mimeinfo->encoding_type = ENC_UNKNOWN;
1478         return;
1479 }
1480
1481 void procmime_parse_mimepart(MimeInfo *parent,
1482                              gchar *content_type,
1483                              gchar *content_encoding,
1484                              gchar *content_description,
1485                              gchar *content_id,
1486                              gchar *content_disposition,
1487                              const gchar *filename,
1488                              guint offset,
1489                              guint length)
1490 {
1491         MimeInfo *mimeinfo;
1492
1493         /* Create MimeInfo */
1494         mimeinfo = procmime_mimeinfo_new();
1495         mimeinfo->content = MIMECONTENT_FILE;
1496         if (parent != NULL)
1497                 g_node_append(parent->node, mimeinfo->node);
1498         mimeinfo->data.filename = g_strdup(filename);
1499         mimeinfo->offset = offset;
1500         mimeinfo->length = length;
1501
1502         if (content_type != NULL) {
1503                 procmime_parse_content_type(content_type, mimeinfo);
1504         } else {
1505                 mimeinfo->type = MIMETYPE_TEXT;
1506                 mimeinfo->subtype = g_strdup("plain");
1507                 if (g_hash_table_lookup(mimeinfo->typeparameters,
1508                                        "charset") == NULL)
1509                         g_hash_table_insert(mimeinfo->typeparameters, g_strdup("charset"), g_strdup("us-ascii"));
1510         }
1511
1512         if (content_encoding != NULL) {
1513                 procmime_parse_content_encoding(content_encoding, mimeinfo);
1514         } else {
1515                 mimeinfo->encoding_type = ENC_UNKNOWN;
1516         }
1517
1518         if (content_description != NULL)
1519                 mimeinfo->description = g_strdup(content_description);
1520         else
1521                 mimeinfo->description = NULL;
1522
1523         if (content_id != NULL)
1524                 mimeinfo->id = g_strdup(content_id);
1525         else
1526                 mimeinfo->id = NULL;
1527
1528         if (content_disposition != NULL) 
1529                 procmime_parse_content_disposition(content_disposition, mimeinfo);
1530         else
1531                 mimeinfo->disposition = DISPOSITIONTYPE_UNKNOWN;
1532
1533         /* Call parser for mime type */
1534         switch (mimeinfo->type) {
1535                 case MIMETYPE_MESSAGE:
1536                         if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
1537                                 procmime_parse_message_rfc822(mimeinfo);
1538                         }
1539                         break;
1540                         
1541                 case MIMETYPE_MULTIPART:
1542                         procmime_parse_multipart(mimeinfo);
1543                         break;
1544                         
1545                 default:
1546                         break;
1547         }
1548 }
1549
1550 static gchar *typenames[] = {
1551     "text",
1552     "image",
1553     "audio",
1554     "video",
1555     "application",
1556     "message",
1557     "multipart",
1558     "unknown",
1559 };
1560
1561 static gboolean output_func(GNode *node, gpointer data)
1562 {
1563         guint i, depth;
1564         MimeInfo *mimeinfo = (MimeInfo *) node->data;
1565
1566         depth = g_node_depth(node);
1567         for (i = 0; i < depth; i++)
1568                 printf("    ");
1569         printf("%s/%s (offset:%d length:%d encoding: %d)\n", typenames[mimeinfo->type], mimeinfo->subtype, mimeinfo->offset, mimeinfo->length, mimeinfo->encoding_type);
1570
1571         return FALSE;
1572 }
1573
1574 static void output_mime_structure(MimeInfo *mimeinfo, int indent)
1575 {
1576         g_node_traverse(mimeinfo->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1, output_func, NULL);
1577 }
1578
1579 MimeInfo *procmime_scan_file_with_offset(const gchar *filename, int offset)
1580 {
1581         MimeInfo *mimeinfo;
1582         struct stat buf;
1583
1584         stat(filename, &buf);
1585
1586         mimeinfo = procmime_mimeinfo_new();
1587         mimeinfo->content = MIMECONTENT_FILE;
1588         mimeinfo->encoding_type = ENC_UNKNOWN;
1589         mimeinfo->type = MIMETYPE_MESSAGE;
1590         mimeinfo->subtype = g_strdup("rfc822");
1591         mimeinfo->data.filename = g_strdup(filename);
1592         mimeinfo->offset = offset;
1593         mimeinfo->length = buf.st_size - offset;
1594
1595         procmime_parse_message_rfc822(mimeinfo);
1596         if (debug_get_mode())
1597                 output_mime_structure(mimeinfo, 0);
1598
1599         return mimeinfo;
1600 }
1601
1602 MimeInfo *procmime_scan_file(const gchar *filename)
1603 {
1604         MimeInfo *mimeinfo;
1605
1606         g_return_val_if_fail(filename != NULL, NULL);
1607
1608         mimeinfo = procmime_scan_file_with_offset(filename, 0);
1609
1610         return mimeinfo;
1611 }
1612
1613 MimeInfo *procmime_scan_queue_file(const gchar *filename)
1614 {
1615         FILE *fp;
1616         MimeInfo *mimeinfo;
1617         gchar buf[BUFFSIZE];
1618         gint offset = 0;
1619
1620         g_return_val_if_fail(filename != NULL, NULL);
1621
1622         /* Open file */
1623         if ((fp = fopen(filename, "rb")) == NULL)
1624                 return NULL;
1625         /* Skip queue header */
1626         while (fgets(buf, sizeof(buf), fp) != NULL)
1627                 if (buf[0] == '\r' || buf[0] == '\n') break;
1628         offset = ftell(fp);
1629         fclose(fp);
1630
1631         mimeinfo = procmime_scan_file_with_offset(filename, offset);
1632
1633         return mimeinfo;
1634 }
1635
1636 typedef enum {
1637     ENC_AS_TOKEN,
1638     ENC_AS_QUOTED_STRING,
1639     ENC_AS_EXTENDED,
1640 } EncodeAs;
1641
1642 static void write_parameters(gpointer key, gpointer value, gpointer user_data)
1643 {
1644         gchar *param = key;
1645         gchar *val = value, *valpos;
1646         FILE *fp = user_data;
1647         EncodeAs encas = ENC_AS_TOKEN;
1648
1649         for (valpos = val; *valpos != 0; valpos++) {
1650                 if (!IS_ASCII(*valpos)) {
1651                         encas = ENC_AS_EXTENDED;
1652                         break;
1653                 }
1654             
1655                 /* CTLs */
1656                 if (((*valpos >= 0) && (*valpos < 037)) || (*valpos == 0177)) {
1657                         encas = ENC_AS_QUOTED_STRING;
1658                         continue;
1659                 }
1660
1661                 /* tspecials + SPACE */
1662                 switch (*valpos) {
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                 case '[':
1676                 case ']':
1677                 case '?':
1678                 case '=':
1679                         encas = ENC_AS_QUOTED_STRING;
1680                         continue;
1681                 }
1682         }
1683
1684         switch (encas) {
1685         case ENC_AS_TOKEN:
1686                 fprintf(fp, "; %s=", param);
1687                 fprintf(fp, "%s", val);
1688                 break;
1689
1690         case ENC_AS_QUOTED_STRING:
1691                 fprintf(fp, "; %s=", param);
1692                 fprintf(fp, "\"%s\"", val);
1693                 break;
1694
1695         case ENC_AS_EXTENDED:
1696                 fprintf(fp, "; %s*=", param);
1697                 fprintf(fp, "%s''", conv_get_current_charset_str());
1698                 for (valpos = val; *valpos != '\0'; valpos++) {
1699                         if (IS_ASCII(*valpos) && isalnum(*valpos))
1700                                 fprintf(fp, "%c", *valpos);
1701                         else {
1702                                 gchar hexstr[3] = "XX";
1703                                 get_hex_str(hexstr, *valpos);
1704                                 fprintf(fp, "%%%s", hexstr);
1705                         }
1706                 }
1707                 break;
1708         }
1709 }
1710
1711 void procmime_write_mime_header(MimeInfo *mimeinfo, FILE *fp)
1712 {
1713         struct TypeTable *type_table;
1714
1715         debug_print("procmime_write_mime_header\n");
1716
1717         for (type_table = mime_type_table; type_table->str != NULL; type_table++)
1718                 if (mimeinfo->type == type_table->type) {
1719                         fprintf(fp, "Content-Type: %s/%s", type_table->str, mimeinfo->subtype);
1720                         break;
1721                 }
1722         g_hash_table_foreach(mimeinfo->typeparameters, write_parameters, fp);
1723         fprintf(fp, "\n");
1724
1725         if (mimeinfo->encoding_type != ENC_UNKNOWN)
1726                 fprintf(fp, "Content-Transfer-Encoding: %s\n", procmime_get_encoding_str(mimeinfo->encoding_type));
1727
1728         if (mimeinfo->description != NULL)
1729                 fprintf(fp, "Content-Description: %s\n", mimeinfo->description);
1730
1731         if (mimeinfo->id != NULL)
1732                 fprintf(fp, "Content-ID: %s\n", mimeinfo->id);
1733
1734         if (mimeinfo->disposition != DISPOSITIONTYPE_UNKNOWN) {
1735                 fprintf(fp, "Content-Disposition: ");
1736                 if (mimeinfo->disposition == DISPOSITIONTYPE_INLINE)
1737                         fprintf(fp, "inline");
1738                 else if (mimeinfo->disposition == DISPOSITIONTYPE_ATTACHMENT)
1739                         fprintf(fp, "attachment");
1740                 else
1741                         fprintf(fp, "unknown");
1742
1743                 /* FIXME: linebreaks after too many parameters */
1744                 g_hash_table_foreach(mimeinfo->dispositionparameters, write_parameters, fp);
1745                 fprintf(fp, "\n");
1746         }
1747
1748         fprintf(fp, "\n");
1749 }
1750
1751 gint procmime_write_message_rfc822(MimeInfo *mimeinfo, FILE *fp)
1752 {
1753         FILE *infp;
1754         GNode *childnode;
1755         MimeInfo *child;
1756         gchar buf[BUFFSIZE];
1757         gboolean skip = FALSE;;
1758
1759         debug_print("procmime_write_message_rfc822\n");
1760
1761         /* write header */
1762         switch (mimeinfo->content) {
1763         case MIMECONTENT_FILE:
1764                 if ((infp = fopen(mimeinfo->data.filename, "rb")) == NULL) {
1765                         FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1766                         return -1;
1767                 }
1768                 fseek(infp, mimeinfo->offset, SEEK_SET);
1769                 while (fgets(buf, sizeof(buf), infp) == buf) {
1770                         if (buf[0] == '\n' && buf[1] == '\0')
1771                                 break;
1772                         if (skip && (buf[0] == ' ' || buf[0] == '\t'))
1773                                 continue;
1774                         if (g_ascii_strncasecmp(buf, "Mime-Version:", 13) == 0 ||
1775                             g_ascii_strncasecmp(buf, "Content-Type:", 13) == 0 ||
1776                             g_ascii_strncasecmp(buf, "Content-Transfer-Encoding:", 26) == 0 ||
1777                             g_ascii_strncasecmp(buf, "Content-Description:", 20) == 0 ||
1778                             g_ascii_strncasecmp(buf, "Content-ID:", 11) == 0 ||
1779                             g_ascii_strncasecmp(buf, "Content-Disposition:", 20) == 0) {
1780                                 skip = TRUE;
1781                                 continue;
1782                         }
1783                         fwrite(buf, sizeof(gchar), strlen(buf), fp);
1784                         skip = FALSE;
1785                 }
1786                 fclose(infp);
1787                 break;
1788
1789         case MIMECONTENT_MEM:
1790                 fwrite(mimeinfo->data.mem, strlen(mimeinfo->data.mem), sizeof(gchar), fp);
1791                 break;
1792
1793         default:
1794                 break;
1795         }
1796
1797         childnode = mimeinfo->node->children;
1798         if (childnode == NULL)
1799                 return -1;
1800
1801         child = (MimeInfo *) childnode->data;
1802         fprintf(fp, "Mime-Version: 1.0\n");
1803         procmime_write_mime_header(child, fp);
1804         return procmime_write_mimeinfo(child, fp);
1805 }
1806
1807 gint procmime_write_multipart(MimeInfo *mimeinfo, FILE *fp)
1808 {
1809         FILE *infp;
1810         GNode *childnode;
1811         gchar *boundary, *str, *str2;
1812         gchar buf[BUFFSIZE];
1813         gboolean firstboundary;
1814
1815         debug_print("procmime_write_multipart\n");
1816
1817         boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
1818
1819         switch (mimeinfo->content) {
1820         case MIMECONTENT_FILE:
1821                 if ((infp = fopen(mimeinfo->data.filename, "rb")) == NULL) {
1822                         FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1823                         return -1;
1824                 }
1825                 fseek(infp, mimeinfo->offset, SEEK_SET);
1826                 while (fgets(buf, sizeof(buf), infp) == buf) {
1827                         if (IS_BOUNDARY(buf, boundary, strlen(boundary)))
1828                                 break;
1829                         fwrite(buf, sizeof(gchar), strlen(buf), fp);
1830                 }
1831                 fclose(infp);
1832                 break;
1833
1834         case MIMECONTENT_MEM:
1835                 str = g_strdup(mimeinfo->data.mem);
1836                 if (((str2 = strstr(str, boundary)) != NULL) && ((str2 - str) >= 2) &&
1837                     (*(str2 - 1) == '-') && (*(str2 - 2) == '-'))
1838                         *(str2 - 2) = '\0';
1839                 fwrite(str, strlen(str), sizeof(gchar), fp);
1840                 g_free(str);
1841                 break;
1842
1843         default:
1844                 break;
1845         }
1846
1847         childnode = mimeinfo->node->children;
1848         firstboundary = TRUE;
1849         while (childnode != NULL) {
1850                 MimeInfo *child = childnode->data;
1851
1852                 if (firstboundary)
1853                         firstboundary = FALSE;
1854                 else
1855                         fprintf(fp, "\n");
1856                 fprintf(fp, "--%s\n", boundary);
1857
1858                 procmime_write_mime_header(child, fp);
1859                 if (procmime_write_mimeinfo(child, fp) < 0)
1860                         return -1;
1861
1862                 childnode = g_node_next_sibling(childnode);
1863         }       
1864         fprintf(fp, "\n--%s--\n", boundary);
1865
1866         return 0;
1867 }
1868
1869 gint procmime_write_mimeinfo(MimeInfo *mimeinfo, FILE *fp)
1870 {
1871         FILE *infp;
1872
1873         debug_print("procmime_write_mimeinfo\n");
1874
1875         if (G_NODE_IS_LEAF(mimeinfo->node)) {
1876                 switch (mimeinfo->content) {
1877                 case MIMECONTENT_FILE:
1878                         if ((infp = fopen(mimeinfo->data.filename, "rb")) == NULL) {
1879                                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1880                                 return -1;
1881                         }
1882                         copy_file_part_to_fp(infp, mimeinfo->offset, mimeinfo->length, fp);
1883                         fclose(infp);
1884                         return 0;
1885
1886                 case MIMECONTENT_MEM:
1887                         fwrite(mimeinfo->data.mem, strlen(mimeinfo->data.mem), sizeof(gchar), fp);
1888                         return 0;
1889
1890                 default:
1891                         return 0;
1892                 }
1893         } else {
1894                 /* Call writer for mime type */
1895                 switch (mimeinfo->type) {
1896                 case MIMETYPE_MESSAGE:
1897                         if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0)
1898                                 return procmime_write_message_rfc822(mimeinfo, fp);
1899                         break;
1900                         
1901                 case MIMETYPE_MULTIPART:
1902                         return procmime_write_multipart(mimeinfo, fp);
1903                         
1904                 default:
1905                         break;
1906                 }
1907
1908                 return -1;
1909         }
1910
1911         return 0;
1912 }