2004-11-17 [paul] 0.9.12cvs155.1
[claws.git] / src / procmime.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2004 Hiroyuki Yamamoto & The Sylpheed-Claws Team
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include "defs.h"
25
26 #include <stdio.h>
27 #include <glib.h>
28 #include <stdio.h>
29 #include <string.h>
30 #include <locale.h>
31 #include <ctype.h>
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <unistd.h>
35
36 #include "intl.h"
37 #include "procmime.h"
38 #include "procheader.h"
39 #include "base64.h"
40 #include "quoted-printable.h"
41 #include "uuencode.h"
42 #include "unmime.h"
43 #include "html.h"
44 #include "enriched.h"
45 #include "codeconv.h"
46 #include "utils.h"
47 #include "prefs_common.h"
48
49 #include "prefs_gtk.h"
50
51 static GHashTable *procmime_get_mime_type_table (void);
52
53 MimeInfo *procmime_mimeinfo_new(void)
54 {
55         MimeInfo *mimeinfo;
56
57         mimeinfo = g_new0(MimeInfo, 1);
58         mimeinfo->content        = MIMECONTENT_EMPTY;
59         mimeinfo->data.filename  = NULL;
60
61         mimeinfo->type           = MIMETYPE_UNKNOWN;
62         mimeinfo->encoding_type  = ENC_UNKNOWN;
63         mimeinfo->typeparameters = g_hash_table_new(g_str_hash, g_str_equal);
64
65         mimeinfo->disposition    = DISPOSITIONTYPE_UNKNOWN;
66         mimeinfo->dispositionparameters 
67                                  = g_hash_table_new(g_str_hash, g_str_equal);
68
69         mimeinfo->node           = g_node_new(mimeinfo);
70         
71         return mimeinfo;
72 }
73
74 static gboolean procmime_mimeinfo_parameters_destroy(gpointer key, gpointer value, gpointer user_data)
75 {
76         g_free(key);
77         g_free(value);
78         
79         return TRUE;
80 }
81
82 static gchar *forced_charset = NULL;
83
84 void procmime_force_charset(const gchar *str)
85 {
86         g_free(forced_charset);
87         forced_charset = NULL;
88         if (str)
89                 forced_charset = g_strdup(str);
90 }
91
92 static EncodingType forced_encoding = 0;
93
94 void procmime_force_encoding(EncodingType encoding)
95 {
96         forced_encoding = encoding;
97 }
98
99 static gboolean free_func(GNode *node, gpointer data)
100 {
101         MimeInfo *mimeinfo = (MimeInfo *) node->data;
102
103         switch (mimeinfo->content) {
104         case MIMECONTENT_FILE:
105                 if (mimeinfo->tmp)
106                         unlink(mimeinfo->data.filename);
107                 g_free(mimeinfo->data.filename);
108                 break;
109
110         case MIMECONTENT_MEM:
111                 if (mimeinfo->tmp)
112                         g_free(mimeinfo->data.mem);
113         default:
114                 break;
115         }
116
117         g_free(mimeinfo->subtype);
118         g_free(mimeinfo->description);
119         g_free(mimeinfo->id);
120
121         g_hash_table_foreach_remove(mimeinfo->typeparameters,
122                 procmime_mimeinfo_parameters_destroy, NULL);
123         g_hash_table_destroy(mimeinfo->typeparameters);
124         g_hash_table_foreach_remove(mimeinfo->dispositionparameters,
125                 procmime_mimeinfo_parameters_destroy, NULL);
126         g_hash_table_destroy(mimeinfo->dispositionparameters);
127
128         if (mimeinfo->privacy)
129                 privacy_free_privacydata(mimeinfo->privacy);
130
131         g_free(mimeinfo);
132
133         return FALSE;
134 }
135
136 void procmime_mimeinfo_free_all(MimeInfo *mimeinfo)
137 {
138         GNode *node;
139
140         if (!mimeinfo)
141                 return;
142
143         node = mimeinfo->node;
144         g_node_traverse(node, G_IN_ORDER, G_TRAVERSE_ALL, -1, free_func, NULL);
145
146         g_node_destroy(node);
147 }
148
149 #if 0 /* UNUSED */
150 MimeInfo *procmime_mimeinfo_insert(MimeInfo *parent, MimeInfo *mimeinfo)
151 {
152         MimeInfo *child = parent->children;
153
154         if (!child)
155                 parent->children = mimeinfo;
156         else {
157                 while (child->next != NULL)
158                         child = child->next;
159
160                 child->next = mimeinfo;
161         }
162
163         mimeinfo->parent = parent;
164         mimeinfo->level = parent->level + 1;
165
166         return mimeinfo;
167 }
168
169 void procmime_mimeinfo_replace(MimeInfo *old, MimeInfo *new)
170 {
171         MimeInfo *parent = old->parent;
172         MimeInfo *child;
173
174         g_return_if_fail(parent != NULL);
175         g_return_if_fail(new->next == NULL);
176
177         for (child = parent->children; child && child != old;
178              child = child->next)
179                 ;
180         if (!child) {
181                 g_warning("oops: parent can't find it's own child");
182                 return;
183         }
184         procmime_mimeinfo_free_all(old);
185
186         if (child == parent->children) {
187                 new->next = parent->children->next;
188                 parent->children = new;
189         } else {
190                 new->next = child->next;
191                 child = new;
192         }
193 }
194 #endif
195
196 MimeInfo *procmime_mimeinfo_parent(MimeInfo *mimeinfo)
197 {
198         g_return_val_if_fail(mimeinfo != NULL, NULL);
199         g_return_val_if_fail(mimeinfo->node != NULL, NULL);
200
201         if (mimeinfo->node->parent == NULL)
202                 return NULL;
203         return (MimeInfo *) mimeinfo->node->parent->data;
204 }
205
206 MimeInfo *procmime_mimeinfo_next(MimeInfo *mimeinfo)
207 {
208         g_return_val_if_fail(mimeinfo != NULL, NULL);
209         g_return_val_if_fail(mimeinfo->node != NULL, NULL);
210
211         if (mimeinfo->node->children)
212                 return (MimeInfo *) mimeinfo->node->children->data;
213         if (mimeinfo->node->next)
214                 return (MimeInfo *) mimeinfo->node->next->data;
215
216         if (mimeinfo->node->parent == NULL)
217                 return NULL;
218
219         while (mimeinfo->node->parent != NULL) {
220                 mimeinfo = (MimeInfo *) mimeinfo->node->parent->data;
221                 if (mimeinfo->node->next)
222                         return (MimeInfo *) mimeinfo->node->next->data;
223         }
224
225         return NULL;
226 }
227
228 MimeInfo *procmime_scan_message(MsgInfo *msginfo)
229 {
230         gchar *filename;
231         MimeInfo *mimeinfo;
232
233         filename = procmsg_get_message_file(msginfo);
234         if (!filename)
235                 return NULL;
236         if (msginfo->folder->stype != F_QUEUE && 
237             msginfo->folder->stype != F_DRAFT)
238                 mimeinfo = procmime_scan_file(filename);
239         else
240                 mimeinfo = procmime_scan_queue_file(filename);
241         g_free(filename);
242
243         return mimeinfo;
244 }
245
246 enum
247 {
248         H_CONTENT_TRANSFER_ENCODING = 0,
249         H_CONTENT_TYPE              = 1,
250         H_CONTENT_DISPOSITION       = 2,
251         H_CONTENT_DESCRIPTION       = 3,
252         H_SUBJECT                   = 4
253 };
254
255 const gchar *procmime_mimeinfo_get_parameter(MimeInfo *mimeinfo, const gchar *name)
256 {
257         const gchar *value;
258
259         g_return_val_if_fail(mimeinfo != NULL, NULL);
260         g_return_val_if_fail(name != NULL, NULL);
261
262         value = g_hash_table_lookup(mimeinfo->dispositionparameters, name);
263         if (value == NULL)
264                 value = g_hash_table_lookup(mimeinfo->typeparameters, name);
265         
266         return value;
267 }
268
269 gboolean procmime_decode_content(MimeInfo *mimeinfo)
270 {
271         gchar buf[BUFFSIZE];
272         gint readend;
273         gchar *tmpfilename;
274         FILE *outfp, *infp;
275         struct stat statbuf;
276
277         EncodingType encoding = forced_encoding 
278                                 ? forced_encoding
279                                 : mimeinfo->encoding_type;
280                    
281         g_return_val_if_fail(mimeinfo != NULL, FALSE);
282
283         if (encoding == ENC_UNKNOWN ||
284             encoding == ENC_BINARY)
285                 return TRUE;
286
287         infp = fopen(mimeinfo->data.filename, "rb");
288         if (!infp) {
289                 perror("fopen");
290                 return FALSE;
291         }
292         fseek(infp, mimeinfo->offset, SEEK_SET);
293
294         outfp = get_tmpfile_in_dir(get_mime_tmp_dir(), &tmpfilename);
295         if (!outfp) {
296                 perror("tmpfile");
297                 return FALSE;
298         }
299
300         readend = mimeinfo->offset + mimeinfo->length;
301
302         if (encoding == ENC_QUOTED_PRINTABLE) {
303                 while ((ftell(infp) < readend) && (fgets(buf, sizeof(buf), infp) != NULL)) {
304                         gint len;
305                         len = qp_decode_line(buf);
306                         fwrite(buf, len, 1, outfp);
307                 }
308         } else if (encoding == ENC_BASE64) {
309                 gchar outbuf[BUFFSIZE];
310                 gint len;
311                 Base64Decoder *decoder;
312
313                 decoder = base64_decoder_new();
314                 while ((ftell(infp) < readend) && (fgets(buf, sizeof(buf), infp) != NULL)) {
315                         len = base64_decoder_decode(decoder, buf, outbuf);
316                         if (len < 0) {
317                                 g_warning("Bad BASE64 content\n");
318                                 break;
319                         }
320                         fwrite(outbuf, sizeof(gchar), len, outfp);
321                 }
322                 base64_decoder_free(decoder);
323         } else if (encoding == ENC_X_UUENCODE) {
324                 gchar outbuf[BUFFSIZE];
325                 gint len;
326                 gboolean flag = FALSE;
327
328                 while ((ftell(infp) < readend) && (fgets(buf, sizeof(buf), infp) != NULL)) {
329                         if (!flag && strncmp(buf,"begin ", 6)) continue;
330
331                         if (flag) {
332                                 len = fromuutobits(outbuf, buf);
333                                 if (len <= 0) {
334                                         if (len < 0) 
335                                                 g_warning("Bad UUENCODE content(%d)\n", len);
336                                         break;
337                                 }
338                                 fwrite(outbuf, sizeof(gchar), len, outfp);
339                         } else
340                                 flag = TRUE;
341                 }
342         } else {
343                 while ((ftell(infp) < readend) && (fgets(buf, sizeof(buf), infp) != NULL)) {
344                         fputs(buf, outfp);
345                 }
346         }
347
348         fclose(outfp);
349         fclose(infp);
350
351         stat(tmpfilename, &statbuf);
352         if (mimeinfo->tmp && (mimeinfo->data.filename != NULL))
353                 unlink(mimeinfo->data.filename);
354         if (mimeinfo->data.filename != NULL)
355                 g_free(mimeinfo->data.filename);
356         mimeinfo->data.filename = tmpfilename;
357         mimeinfo->tmp = TRUE;
358         mimeinfo->offset = 0;
359         mimeinfo->length = statbuf.st_size;
360         mimeinfo->encoding_type = ENC_BINARY;
361
362         return TRUE;
363 }
364
365 #define B64_LINE_SIZE           57
366 #define B64_BUFFSIZE            77
367
368 gboolean procmime_encode_content(MimeInfo *mimeinfo, EncodingType encoding)
369 {
370         FILE *infp, *outfp;
371         gint len;
372         gchar *tmpfilename;
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_text_file(const gchar *file)
1004 {
1005         FILE *fp;
1006         guchar buf[BUFFSIZE];
1007         size_t len;
1008         size_t octet_chars = 0;
1009         size_t total_len = 0;
1010         gfloat octet_percentage;
1011
1012         if ((fp = fopen(file, "rb")) == NULL) {
1013                 FILE_OP_ERROR(file, "fopen");
1014                 return ENC_UNKNOWN;
1015         }
1016
1017         while ((len = fread(buf, sizeof(guchar), sizeof(buf), fp)) > 0) {
1018                 guchar *p;
1019                 gint i;
1020
1021                 for (p = buf, i = 0; i < len; ++p, ++i) {
1022                         if (*p & 0x80)
1023                                 ++octet_chars;
1024                 }
1025                 total_len += len;
1026         }
1027
1028         fclose(fp);
1029         
1030         if (total_len > 0)
1031                 octet_percentage = (gfloat)octet_chars / (gfloat)total_len;
1032         else
1033                 octet_percentage = 0.0;
1034
1035         debug_print("procmime_get_encoding_for_text_file(): "
1036                     "8bit chars: %d / %d (%f%%)\n", octet_chars, total_len,
1037                     100.0 * octet_percentage);
1038
1039         if (octet_percentage > 0.20) {
1040                 debug_print("using BASE64\n");
1041                 return ENC_BASE64;
1042         } else if (octet_chars > 0) {
1043                 debug_print("using quoted-printable\n");
1044                 return ENC_QUOTED_PRINTABLE;
1045         } else {
1046                 debug_print("using 7bit\n");
1047                 return ENC_7BIT;
1048         }
1049 }
1050
1051 struct EncodingTable 
1052 {
1053         gchar *str;
1054         EncodingType enc_type;
1055 };
1056
1057 struct EncodingTable encoding_table[] = {
1058         {"7bit", ENC_7BIT},
1059         {"8bit", ENC_8BIT},
1060         {"binary", ENC_BINARY},
1061         {"quoted-printable", ENC_QUOTED_PRINTABLE},
1062         {"base64", ENC_BASE64},
1063         {"x-uuencode", ENC_UNKNOWN},
1064         {NULL, ENC_UNKNOWN},
1065 };
1066
1067 const gchar *procmime_get_encoding_str(EncodingType encoding)
1068 {
1069         struct EncodingTable *enc_table;
1070         
1071         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1072                 if (enc_table->enc_type == encoding)
1073                         return enc_table->str;
1074         }
1075         return NULL;
1076 }
1077
1078 /* --- NEW MIME STUFF --- */
1079 struct TypeTable
1080 {
1081         gchar *str;
1082         MimeMediaType type;
1083 };
1084
1085 static struct TypeTable mime_type_table[] = {
1086         {"text", MIMETYPE_TEXT},
1087         {"image", MIMETYPE_IMAGE},
1088         {"audio", MIMETYPE_AUDIO},
1089         {"video", MIMETYPE_VIDEO},
1090         {"application", MIMETYPE_APPLICATION},
1091         {"message", MIMETYPE_MESSAGE},
1092         {"multipart", MIMETYPE_MULTIPART},
1093         {NULL, 0},
1094 };
1095
1096 const gchar *procmime_get_media_type_str(MimeMediaType type)
1097 {
1098         struct TypeTable *type_table;
1099         
1100         for (type_table = mime_type_table; type_table->str != NULL; type_table++) {
1101                 if (type_table->type == type)
1102                         return type_table->str;
1103         }
1104         return NULL;
1105 }
1106
1107 MimeMediaType procmime_get_media_type(const gchar *str)
1108 {
1109         struct TypeTable *typetablearray;
1110
1111         for (typetablearray = mime_type_table; typetablearray->str != NULL; typetablearray++)
1112                 if (g_ascii_strncasecmp(str, typetablearray->str, strlen(typetablearray->str)) == 0)
1113                         return typetablearray->type;
1114
1115         return MIMETYPE_UNKNOWN;
1116 }
1117
1118 /*!
1119  *\brief        Safe wrapper for content type string.
1120  *
1121  *\return       const gchar * Pointer to content type string. 
1122  */
1123 gchar *procmime_get_content_type_str(MimeMediaType type,
1124                                            const char *subtype)
1125 {
1126         const gchar *type_str = NULL;
1127
1128         if (subtype == NULL || !(type_str = procmime_get_media_type_str(type)))
1129                 return g_strdup("unknown");
1130         return g_strdup_printf("%s/%s", type_str, subtype);
1131 }
1132
1133 void procmime_parse_mimepart(MimeInfo *parent,
1134                              gchar *content_type,
1135                              gchar *content_encoding,
1136                              gchar *content_description,
1137                              gchar *content_id,
1138                              gchar *content_disposition,
1139                              const gchar *filename,
1140                              guint offset,
1141                              guint length);
1142
1143 void procmime_parse_message_rfc822(MimeInfo *mimeinfo)
1144 {
1145         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1146                                 {"Content-Transfer-Encoding:",
1147                                                    NULL, FALSE},
1148                                 {"Content-Description:",
1149                                                    NULL, TRUE},
1150                                 {"Content-ID:",
1151                                                    NULL, TRUE},
1152                                 {"Content-Disposition:",
1153                                                    NULL, TRUE},
1154                                 {"MIME-Version:",
1155                                                    NULL, TRUE},
1156                                 {NULL,             NULL, FALSE}};
1157         guint content_start, i;
1158         FILE *fp;
1159         gint mime_major, mime_minor;
1160
1161         procmime_decode_content(mimeinfo);
1162
1163         fp = fopen(mimeinfo->data.filename, "rb");
1164         if (fp == NULL) {
1165                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1166                 return;
1167         }
1168         fseek(fp, mimeinfo->offset, SEEK_SET);
1169         procheader_get_header_fields(fp, hentry);
1170         if (hentry[0].body != NULL)
1171                 conv_unmime_header_overwrite(hentry[0].body);
1172         if (hentry[2].body != NULL)
1173                 conv_unmime_header_overwrite(hentry[2].body);
1174         if (hentry[4].body != NULL)
1175                 conv_unmime_header_overwrite(hentry[4].body);
1176         content_start = ftell(fp);
1177         fclose(fp);
1178
1179         if ((hentry[5].body != NULL) &&
1180             (sscanf(hentry[5].body, "%d.%d", &mime_major, &mime_minor) == 2) &&
1181             (mime_major == 1) && (mime_minor == 0)) {
1182                 procmime_parse_mimepart(mimeinfo,
1183                                         hentry[0].body, hentry[1].body,
1184                                         hentry[2].body, hentry[3].body, 
1185                                         hentry[4].body, 
1186                                         mimeinfo->data.filename, content_start,
1187                                         mimeinfo->length - (content_start - mimeinfo->offset));
1188         } else {
1189                 MimeInfo *subinfo;
1190
1191                 subinfo = procmime_mimeinfo_new();
1192                 subinfo->encoding_type = ENC_UNKNOWN;
1193                 subinfo->type = MIMETYPE_TEXT;
1194                 subinfo->subtype = g_strdup("plain");
1195                 subinfo->data.filename = g_strdup(mimeinfo->data.filename);
1196                 subinfo->offset = content_start;
1197                 subinfo->length = mimeinfo->length - (content_start - mimeinfo->offset);
1198
1199                 g_node_append(mimeinfo->node, subinfo->node);
1200         }
1201         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1202                 g_free(hentry[i].body);
1203                 hentry[i].body = NULL;
1204         }
1205 }
1206
1207 void procmime_parse_multipart(MimeInfo *mimeinfo)
1208 {
1209         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1210                                 {"Content-Transfer-Encoding:",
1211                                                    NULL, FALSE},
1212                                 {"Content-Description:",
1213                                                    NULL, TRUE},
1214                                 {"Content-ID:",
1215                                                    NULL, TRUE},
1216                                 {"Content-Disposition:",
1217                                                    NULL, TRUE},
1218                                 {NULL,             NULL, FALSE}};
1219         gchar *p;
1220         gchar *boundary;
1221         gint boundary_len = 0, lastoffset = -1, i;
1222         gchar buf[BUFFSIZE];
1223         FILE *fp;
1224
1225         boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
1226         if (!boundary)
1227                 return;
1228         boundary_len = strlen(boundary);
1229
1230         procmime_decode_content(mimeinfo);
1231
1232         fp = fopen(mimeinfo->data.filename, "rb");
1233         if (fp == NULL) {
1234                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1235                 return;
1236         }
1237         fseek(fp, mimeinfo->offset, SEEK_SET);
1238         while ((p = fgets(buf, sizeof(buf), fp)) != NULL) {
1239                 if (ftell(fp) > (mimeinfo->offset + mimeinfo->length))
1240                         break;
1241
1242                 if (IS_BOUNDARY(buf, boundary, boundary_len)) {
1243                         if (lastoffset != -1) {
1244                                 procmime_parse_mimepart(mimeinfo,
1245                                                         hentry[0].body, hentry[1].body,
1246                                                         hentry[2].body, hentry[3].body, 
1247                                                         hentry[4].body, 
1248                                                         mimeinfo->data.filename, lastoffset,
1249                                                         (ftell(fp) - strlen(buf)) - lastoffset - 1);
1250                         }
1251                         
1252                         if (buf[2 + boundary_len]     == '-' &&
1253                             buf[2 + boundary_len + 1] == '-')
1254                                 break;
1255
1256                         for (i = 0; i < (sizeof hentry / sizeof hentry[0]) ; i++) {
1257                                 g_free(hentry[i].body);
1258                                 hentry[i].body = NULL;
1259                         }
1260                         procheader_get_header_fields(fp, hentry);
1261                         if (hentry[0].body != NULL)
1262                                 conv_unmime_header_overwrite(hentry[0].body);
1263                         if (hentry[2].body != NULL)
1264                                 conv_unmime_header_overwrite(hentry[2].body);
1265                         if (hentry[4].body != NULL)
1266                                 conv_unmime_header_overwrite(hentry[4].body);
1267                         lastoffset = ftell(fp);
1268                 }
1269         }
1270         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1271                 g_free(hentry[i].body);
1272                 hentry[i].body = NULL;
1273         }
1274         fclose(fp);
1275 }
1276
1277 static void parse_parameters(const gchar *parameters, GHashTable *table)
1278 {
1279         gchar *params, *param, *next;
1280         GSList *convlist = NULL, *concatlist = NULL, *cur;
1281
1282         params = g_strdup(parameters);
1283         param = params;
1284         next = params;
1285         for (; next != NULL; param = next) {
1286                 gchar *attribute, *value, *tmp;
1287                 gint len;
1288                 gboolean convert = FALSE;
1289
1290                 next = strchr_with_skip_quote(param, '"', ';');
1291                 if (next != NULL) {
1292                         next[0] = '\0';
1293                         next++;
1294                 }
1295
1296                 g_strstrip(param);
1297
1298                 attribute = param;
1299                 value = strchr(attribute, '=');
1300                 if (value == NULL)
1301                         continue;
1302
1303                 value[0] = '\0';
1304                 value++;
1305
1306                 g_strdown(attribute);
1307
1308                 len = strlen(attribute);
1309                 if (attribute[len - 1] == '*') {
1310                         gchar *srcpos, *dstpos, *endpos;
1311
1312                         convert = TRUE;
1313                         attribute[len - 1] = '\0';
1314
1315                         srcpos = value;
1316                         dstpos = value;
1317                         endpos = value + strlen(value);
1318                         while (srcpos < endpos) {
1319                                 if (*srcpos != '%')
1320                                         *dstpos = *srcpos;
1321                                 else {
1322                                         guchar dstvalue;
1323
1324                                         if (!get_hex_value(&dstvalue, srcpos[1], srcpos[2]))
1325                                                 *dstpos = '?';
1326                                         else
1327                                                 *dstpos = dstvalue;
1328                                         srcpos += 2;
1329                                 }
1330                                 srcpos++;
1331                                 dstpos++;
1332                         }
1333                         *dstpos = '\0';
1334                 } else {
1335                         if (value[0] == '"')
1336                                 extract_quote(value, '"');
1337                         else if ((tmp = strchr(value, ' ')) != NULL)
1338                                 *tmp = '\0';
1339                 }
1340
1341                 if (strrchr(attribute, '*') != NULL) {
1342                         gchar *tmpattr;
1343
1344                         tmpattr = g_strdup(attribute);
1345                         tmp = strrchr(tmpattr, '*');
1346                         tmp[0] = '\0';
1347
1348                         if ((tmp[1] == '0') && (tmp[2] == '\0') && 
1349                             (g_slist_find_custom(concatlist, attribute, g_str_equal) == NULL))
1350                                 concatlist = g_slist_prepend(concatlist, g_strdup(tmpattr));
1351
1352                         if (convert && (g_slist_find_custom(convlist, attribute, g_str_equal) == NULL))
1353                                 convlist = g_slist_prepend(convlist, g_strdup(tmpattr));
1354
1355                         g_free(tmpattr);
1356                 } else if (convert) {
1357                         if (g_slist_find_custom(convlist, attribute, g_str_equal) == NULL)
1358                                 convlist = g_slist_prepend(convlist, g_strdup(attribute));
1359                 }
1360
1361                 if (g_hash_table_lookup(table, attribute) == NULL)
1362                         g_hash_table_insert(table, g_strdup(attribute), g_strdup(value));
1363         }
1364
1365         for (cur = concatlist; cur != NULL; cur = g_slist_next(cur)) {
1366                 gchar *attribute, *attrwnum, *partvalue;
1367                 gint n = 0;
1368                 GString *value;
1369
1370                 attribute = (gchar *) cur->data;
1371                 value = g_string_sized_new(64);
1372
1373                 attrwnum = g_strdup_printf("%s*%d", attribute, n);
1374                 while ((partvalue = g_hash_table_lookup(table, attrwnum)) != NULL) {
1375                         g_string_append(value, partvalue);
1376
1377                         g_free(attrwnum);
1378                         n++;
1379                         attrwnum = g_strdup_printf("%s*%d", attribute, n);
1380                 }
1381                 g_free(attrwnum);
1382
1383                 g_hash_table_insert(table, g_strdup(attribute), g_strdup(value->str));
1384                 g_string_free(value, TRUE);
1385         }
1386         slist_free_strings(concatlist);
1387         g_slist_free(concatlist);
1388
1389         for (cur = convlist; cur != NULL; cur = g_slist_next(cur)) {
1390                 gchar *attribute, *key, *value;
1391                 gchar *charset, *lang, *oldvalue, *newvalue;
1392
1393                 attribute = (gchar *) cur->data;
1394                 if (!g_hash_table_lookup_extended(table, attribute, (gpointer *) &key, (gpointer *) &value))
1395                         continue;
1396
1397                 charset = value;
1398                 lang = strchr(charset, '\'');
1399                 if (lang == NULL)
1400                         continue;
1401                 lang[0] = '\0';
1402                 lang++;
1403                 oldvalue = strchr(lang, '\'');
1404                 if (oldvalue == NULL)
1405                         continue;
1406                 oldvalue[0] = '\0';
1407                 oldvalue++;
1408
1409                 newvalue = conv_codeset_strdup(oldvalue, charset, CS_UTF_8);
1410
1411                 g_hash_table_remove(table, attribute);
1412                 g_free(key);
1413                 g_free(value);
1414
1415                 g_hash_table_insert(table, g_strdup(attribute), newvalue);
1416         }
1417         slist_free_strings(convlist);
1418         g_slist_free(convlist);
1419
1420         g_free(params);
1421 }       
1422
1423 static void procmime_parse_content_type(const gchar *content_type, MimeInfo *mimeinfo)
1424 {
1425         g_return_if_fail(content_type != NULL);
1426         g_return_if_fail(mimeinfo != NULL);
1427
1428         /* RFC 2045, page 13 says that the mime subtype is MANDATORY;
1429          * if it's not available we use the default Content-Type */
1430         if ((content_type[0] == '\0') || (strchr(content_type, '/') == NULL)) {
1431                 mimeinfo->type = MIMETYPE_TEXT;
1432                 mimeinfo->subtype = g_strdup("plain");
1433                 if (g_hash_table_lookup(mimeinfo->typeparameters,
1434                                        "charset") == NULL)
1435                         g_hash_table_insert(mimeinfo->typeparameters,
1436                                             g_strdup("charset"),
1437                                             g_strdup("us-ascii"));
1438         } else {
1439                 gchar *type, *subtype, *params;
1440
1441                 type = g_strdup(content_type);
1442                 subtype = strchr(type, '/') + 1;
1443                 *(subtype - 1) = '\0';
1444                 if ((params = strchr(subtype, ';')) != NULL) {
1445                         params[0] = '\0';
1446                         params++;
1447                 }
1448
1449                 mimeinfo->type = procmime_get_media_type(type);
1450                 mimeinfo->subtype = g_strdup(subtype);
1451
1452                 /* Get mimeinfo->typeparameters */
1453                 if (params != NULL)
1454                         parse_parameters(params, mimeinfo->typeparameters);
1455
1456                 g_free(type);
1457         }
1458 }
1459
1460 static void procmime_parse_content_disposition(const gchar *content_disposition, MimeInfo *mimeinfo)
1461 {
1462         gchar *tmp, *params;
1463
1464         g_return_if_fail(content_disposition != NULL);
1465         g_return_if_fail(mimeinfo != NULL);
1466
1467         tmp = g_strdup(content_disposition);
1468         if ((params = strchr(tmp, ';')) != NULL) {
1469                 params[0] = '\0';
1470                 params++;
1471         }       
1472         g_strstrip(tmp);
1473
1474         if (!g_ascii_strcasecmp(tmp, "inline")) 
1475                 mimeinfo->disposition = DISPOSITIONTYPE_INLINE;
1476         else if (!g_ascii_strcasecmp(tmp, "attachment"))
1477                 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1478         else
1479                 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1480         
1481         if (params != NULL)
1482                 parse_parameters(params, mimeinfo->dispositionparameters);
1483
1484         g_free(tmp);
1485 }
1486
1487
1488 static void procmime_parse_content_encoding(const gchar *content_encoding, MimeInfo *mimeinfo)
1489 {
1490         struct EncodingTable *enc_table;
1491         
1492         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1493                 if (g_ascii_strcasecmp(enc_table->str, content_encoding) == 0) {
1494                         mimeinfo->encoding_type = enc_table->enc_type;
1495                         return;
1496                 }
1497         }
1498         mimeinfo->encoding_type = ENC_UNKNOWN;
1499         return;
1500 }
1501
1502 void procmime_parse_mimepart(MimeInfo *parent,
1503                              gchar *content_type,
1504                              gchar *content_encoding,
1505                              gchar *content_description,
1506                              gchar *content_id,
1507                              gchar *content_disposition,
1508                              const gchar *filename,
1509                              guint offset,
1510                              guint length)
1511 {
1512         MimeInfo *mimeinfo;
1513
1514         /* Create MimeInfo */
1515         mimeinfo = procmime_mimeinfo_new();
1516         mimeinfo->content = MIMECONTENT_FILE;
1517         if (parent != NULL)
1518                 g_node_append(parent->node, mimeinfo->node);
1519         mimeinfo->data.filename = g_strdup(filename);
1520         mimeinfo->offset = offset;
1521         mimeinfo->length = length;
1522
1523         if (content_type != NULL) {
1524                 procmime_parse_content_type(content_type, mimeinfo);
1525         } else {
1526                 mimeinfo->type = MIMETYPE_TEXT;
1527                 mimeinfo->subtype = g_strdup("plain");
1528                 if (g_hash_table_lookup(mimeinfo->typeparameters,
1529                                        "charset") == NULL)
1530                         g_hash_table_insert(mimeinfo->typeparameters, g_strdup("charset"), g_strdup("us-ascii"));
1531         }
1532
1533         if (content_encoding != NULL) {
1534                 procmime_parse_content_encoding(content_encoding, mimeinfo);
1535         } else {
1536                 mimeinfo->encoding_type = ENC_UNKNOWN;
1537         }
1538
1539         if (content_description != NULL)
1540                 mimeinfo->description = g_strdup(content_description);
1541         else
1542                 mimeinfo->description = NULL;
1543
1544         if (content_id != NULL)
1545                 mimeinfo->id = g_strdup(content_id);
1546         else
1547                 mimeinfo->id = NULL;
1548
1549         if (content_disposition != NULL) 
1550                 procmime_parse_content_disposition(content_disposition, mimeinfo);
1551         else
1552                 mimeinfo->disposition = DISPOSITIONTYPE_UNKNOWN;
1553
1554         /* Call parser for mime type */
1555         switch (mimeinfo->type) {
1556                 case MIMETYPE_MESSAGE:
1557                         if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
1558                                 procmime_parse_message_rfc822(mimeinfo);
1559                         }
1560                         break;
1561                         
1562                 case MIMETYPE_MULTIPART:
1563                         procmime_parse_multipart(mimeinfo);
1564                         break;
1565                         
1566                 default:
1567                         break;
1568         }
1569 }
1570
1571 static gchar *typenames[] = {
1572     "text",
1573     "image",
1574     "audio",
1575     "video",
1576     "application",
1577     "message",
1578     "multipart",
1579     "unknown",
1580 };
1581
1582 static gboolean output_func(GNode *node, gpointer data)
1583 {
1584         guint i, depth;
1585         MimeInfo *mimeinfo = (MimeInfo *) node->data;
1586
1587         depth = g_node_depth(node);
1588         for (i = 0; i < depth; i++)
1589                 printf("    ");
1590         printf("%s/%s (offset:%d length:%d encoding: %d)\n", typenames[mimeinfo->type], mimeinfo->subtype, mimeinfo->offset, mimeinfo->length, mimeinfo->encoding_type);
1591
1592         return FALSE;
1593 }
1594
1595 static void output_mime_structure(MimeInfo *mimeinfo, int indent)
1596 {
1597         g_node_traverse(mimeinfo->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1, output_func, NULL);
1598 }
1599
1600 MimeInfo *procmime_scan_file_with_offset(const gchar *filename, int offset)
1601 {
1602         MimeInfo *mimeinfo;
1603         struct stat buf;
1604
1605         stat(filename, &buf);
1606
1607         mimeinfo = procmime_mimeinfo_new();
1608         mimeinfo->content = MIMECONTENT_FILE;
1609         mimeinfo->encoding_type = ENC_UNKNOWN;
1610         mimeinfo->type = MIMETYPE_MESSAGE;
1611         mimeinfo->subtype = g_strdup("rfc822");
1612         mimeinfo->data.filename = g_strdup(filename);
1613         mimeinfo->offset = offset;
1614         mimeinfo->length = buf.st_size - offset;
1615
1616         procmime_parse_message_rfc822(mimeinfo);
1617         if (debug_get_mode())
1618                 output_mime_structure(mimeinfo, 0);
1619
1620         return mimeinfo;
1621 }
1622
1623 MimeInfo *procmime_scan_file(const gchar *filename)
1624 {
1625         MimeInfo *mimeinfo;
1626
1627         g_return_val_if_fail(filename != NULL, NULL);
1628
1629         mimeinfo = procmime_scan_file_with_offset(filename, 0);
1630
1631         return mimeinfo;
1632 }
1633
1634 MimeInfo *procmime_scan_queue_file(const gchar *filename)
1635 {
1636         FILE *fp;
1637         MimeInfo *mimeinfo;
1638         gchar buf[BUFFSIZE];
1639         gint offset = 0;
1640
1641         g_return_val_if_fail(filename != NULL, NULL);
1642
1643         /* Open file */
1644         if ((fp = fopen(filename, "rb")) == NULL)
1645                 return NULL;
1646         /* Skip queue header */
1647         while (fgets(buf, sizeof(buf), fp) != NULL)
1648                 if (buf[0] == '\r' || buf[0] == '\n') break;
1649         offset = ftell(fp);
1650         fclose(fp);
1651
1652         mimeinfo = procmime_scan_file_with_offset(filename, offset);
1653
1654         return mimeinfo;
1655 }
1656
1657 typedef enum {
1658     ENC_AS_TOKEN,
1659     ENC_AS_QUOTED_STRING,
1660     ENC_AS_EXTENDED,
1661 } EncodeAs;
1662
1663 static void write_parameters(gpointer key, gpointer value, gpointer user_data)
1664 {
1665         gchar *param = key;
1666         gchar *val = value, *valpos;
1667         FILE *fp = user_data;
1668         EncodeAs encas = ENC_AS_TOKEN;
1669
1670         for (valpos = val; *valpos != 0; valpos++) {
1671                 if (!IS_ASCII(*valpos)) {
1672                         encas = ENC_AS_EXTENDED;
1673                         break;
1674                 }
1675             
1676                 /* CTLs */
1677                 if (((*valpos >= 0) && (*valpos < 037)) || (*valpos == 0177)) {
1678                         encas = ENC_AS_QUOTED_STRING;
1679                         continue;
1680                 }
1681
1682                 /* tspecials + SPACE */
1683                 switch (*valpos) {
1684                 case ' ':
1685                 case '(': 
1686                 case ')':
1687                 case '<':
1688                 case '>':
1689                 case '@':
1690                 case ',':
1691                 case ';':
1692                 case ':':
1693                 case '\\':
1694                 case '"':
1695                 case '/':
1696                 case '[':
1697                 case ']':
1698                 case '?':
1699                 case '=':
1700                         encas = ENC_AS_QUOTED_STRING;
1701                         continue;
1702                 }
1703         }
1704
1705         switch (encas) {
1706         case ENC_AS_TOKEN:
1707                 fprintf(fp, "; %s=", param);
1708                 fprintf(fp, "%s", val);
1709                 break;
1710
1711         case ENC_AS_QUOTED_STRING:
1712                 fprintf(fp, "; %s=", param);
1713                 fprintf(fp, "\"%s\"", val);
1714                 break;
1715
1716         case ENC_AS_EXTENDED:
1717                 fprintf(fp, "; %s*=", param);
1718                 fprintf(fp, "%s''", conv_get_current_charset_str());
1719                 for (valpos = val; *valpos != '\0'; valpos++) {
1720                         if (IS_ASCII(*valpos) && isalnum(*valpos))
1721                                 fprintf(fp, "%c", *valpos);
1722                         else {
1723                                 gchar hexstr[3] = "XX";
1724                                 get_hex_str(hexstr, *valpos);
1725                                 fprintf(fp, "%%%s", hexstr);
1726                         }
1727                 }
1728                 break;
1729         }
1730 }
1731
1732 void procmime_write_mime_header(MimeInfo *mimeinfo, FILE *fp)
1733 {
1734         struct TypeTable *type_table;
1735
1736         debug_print("procmime_write_mime_header\n");
1737
1738         for (type_table = mime_type_table; type_table->str != NULL; type_table++)
1739                 if (mimeinfo->type == type_table->type) {
1740                         fprintf(fp, "Content-Type: %s/%s", type_table->str, mimeinfo->subtype);
1741                         break;
1742                 }
1743         g_hash_table_foreach(mimeinfo->typeparameters, write_parameters, fp);
1744         fprintf(fp, "\n");
1745
1746         if (mimeinfo->encoding_type != ENC_UNKNOWN)
1747                 fprintf(fp, "Content-Transfer-Encoding: %s\n", procmime_get_encoding_str(mimeinfo->encoding_type));
1748
1749         if (mimeinfo->description != NULL)
1750                 fprintf(fp, "Content-Description: %s\n", mimeinfo->description);
1751
1752         if (mimeinfo->id != NULL)
1753                 fprintf(fp, "Content-ID: %s\n", mimeinfo->id);
1754
1755         if (mimeinfo->disposition != DISPOSITIONTYPE_UNKNOWN) {
1756                 fprintf(fp, "Content-Disposition: ");
1757                 if (mimeinfo->disposition == DISPOSITIONTYPE_INLINE)
1758                         fprintf(fp, "inline");
1759                 else if (mimeinfo->disposition == DISPOSITIONTYPE_ATTACHMENT)
1760                         fprintf(fp, "attachment");
1761                 else
1762                         fprintf(fp, "unknown");
1763
1764                 /* FIXME: linebreaks after too many parameters */
1765                 g_hash_table_foreach(mimeinfo->dispositionparameters, write_parameters, fp);
1766                 fprintf(fp, "\n");
1767         }
1768
1769         fprintf(fp, "\n");
1770 }
1771
1772 gint procmime_write_message_rfc822(MimeInfo *mimeinfo, FILE *fp)
1773 {
1774         FILE *infp;
1775         GNode *childnode;
1776         MimeInfo *child;
1777         gchar buf[BUFFSIZE];
1778         gboolean skip = FALSE;;
1779
1780         debug_print("procmime_write_message_rfc822\n");
1781
1782         /* write header */
1783         switch (mimeinfo->content) {
1784         case MIMECONTENT_FILE:
1785                 if ((infp = fopen(mimeinfo->data.filename, "rb")) == NULL) {
1786                         FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1787                         return -1;
1788                 }
1789                 fseek(infp, mimeinfo->offset, SEEK_SET);
1790                 while (fgets(buf, sizeof(buf), infp) == buf) {
1791                         if (buf[0] == '\n' && buf[1] == '\0')
1792                                 break;
1793                         if (skip && (buf[0] == ' ' || buf[0] == '\t'))
1794                                 continue;
1795                         if (g_ascii_strncasecmp(buf, "Mime-Version:", 13) == 0 ||
1796                             g_ascii_strncasecmp(buf, "Content-Type:", 13) == 0 ||
1797                             g_ascii_strncasecmp(buf, "Content-Transfer-Encoding:", 26) == 0 ||
1798                             g_ascii_strncasecmp(buf, "Content-Description:", 20) == 0 ||
1799                             g_ascii_strncasecmp(buf, "Content-ID:", 11) == 0 ||
1800                             g_ascii_strncasecmp(buf, "Content-Disposition:", 20) == 0) {
1801                                 skip = TRUE;
1802                                 continue;
1803                         }
1804                         fwrite(buf, sizeof(gchar), strlen(buf), fp);
1805                         skip = FALSE;
1806                 }
1807                 fclose(infp);
1808                 break;
1809
1810         case MIMECONTENT_MEM:
1811                 fwrite(mimeinfo->data.mem, strlen(mimeinfo->data.mem), sizeof(gchar), fp);
1812                 break;
1813
1814         default:
1815                 break;
1816         }
1817
1818         childnode = mimeinfo->node->children;
1819         if (childnode == NULL)
1820                 return -1;
1821
1822         child = (MimeInfo *) childnode->data;
1823         fprintf(fp, "Mime-Version: 1.0\n");
1824         procmime_write_mime_header(child, fp);
1825         return procmime_write_mimeinfo(child, fp);
1826 }
1827
1828 gint procmime_write_multipart(MimeInfo *mimeinfo, FILE *fp)
1829 {
1830         FILE *infp;
1831         GNode *childnode;
1832         gchar *boundary, *str, *str2;
1833         gchar buf[BUFFSIZE];
1834         gboolean firstboundary;
1835
1836         debug_print("procmime_write_multipart\n");
1837
1838         boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
1839
1840         switch (mimeinfo->content) {
1841         case MIMECONTENT_FILE:
1842                 if ((infp = fopen(mimeinfo->data.filename, "rb")) == NULL) {
1843                         FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1844                         return -1;
1845                 }
1846                 fseek(infp, mimeinfo->offset, SEEK_SET);
1847                 while (fgets(buf, sizeof(buf), infp) == buf) {
1848                         if (IS_BOUNDARY(buf, boundary, strlen(boundary)))
1849                                 break;
1850                         fwrite(buf, sizeof(gchar), strlen(buf), fp);
1851                 }
1852                 fclose(infp);
1853                 break;
1854
1855         case MIMECONTENT_MEM:
1856                 str = g_strdup(mimeinfo->data.mem);
1857                 if (((str2 = strstr(str, boundary)) != NULL) && ((str2 - str) >= 2) &&
1858                     (*(str2 - 1) == '-') && (*(str2 - 2) == '-'))
1859                         *(str2 - 2) = '\0';
1860                 fwrite(str, strlen(str), sizeof(gchar), fp);
1861                 g_free(str);
1862                 break;
1863
1864         default:
1865                 break;
1866         }
1867
1868         childnode = mimeinfo->node->children;
1869         firstboundary = TRUE;
1870         while (childnode != NULL) {
1871                 MimeInfo *child = childnode->data;
1872
1873                 if (firstboundary)
1874                         firstboundary = FALSE;
1875                 else
1876                         fprintf(fp, "\n");
1877                 fprintf(fp, "--%s\n", boundary);
1878
1879                 procmime_write_mime_header(child, fp);
1880                 if (procmime_write_mimeinfo(child, fp) < 0)
1881                         return -1;
1882
1883                 childnode = g_node_next_sibling(childnode);
1884         }       
1885         fprintf(fp, "\n--%s--\n", boundary);
1886
1887         return 0;
1888 }
1889
1890 gint procmime_write_mimeinfo(MimeInfo *mimeinfo, FILE *fp)
1891 {
1892         FILE *infp;
1893
1894         debug_print("procmime_write_mimeinfo\n");
1895
1896         if (G_NODE_IS_LEAF(mimeinfo->node)) {
1897                 switch (mimeinfo->content) {
1898                 case MIMECONTENT_FILE:
1899                         if ((infp = fopen(mimeinfo->data.filename, "rb")) == NULL) {
1900                                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1901                                 return -1;
1902                         }
1903                         copy_file_part_to_fp(infp, mimeinfo->offset, mimeinfo->length, fp);
1904                         fclose(infp);
1905                         return 0;
1906
1907                 case MIMECONTENT_MEM:
1908                         fwrite(mimeinfo->data.mem, strlen(mimeinfo->data.mem), sizeof(gchar), fp);
1909                         return 0;
1910
1911                 default:
1912                         return 0;
1913                 }
1914         } else {
1915                 /* Call writer for mime type */
1916                 switch (mimeinfo->type) {
1917                 case MIMETYPE_MESSAGE:
1918                         if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0)
1919                                 return procmime_write_message_rfc822(mimeinfo, fp);
1920                         break;
1921                         
1922                 case MIMETYPE_MULTIPART:
1923                         return procmime_write_multipart(mimeinfo, fp);
1924                         
1925                 default:
1926                         break;
1927                 }
1928
1929                 return -1;
1930         }
1931
1932         return 0;
1933 }