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