Add a plugin method to allow updating stored passwords on master password change.
[claws.git] / src / procmime.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2012 Hiroyuki Yamamoto & The Claws Mail 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 3 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, see <http://www.gnu.org/licenses/>.
17  * 
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #include "claws-features.h"
23 #endif
24
25 #define _GNU_SOURCE
26 #include <stdio.h>
27
28 #include "defs.h"
29
30 #include <glib.h>
31 #include <glib/gi18n.h>
32 #include <string.h>
33 #if HAVE_LOCALE_H
34 #  include <locale.h>
35 #endif
36 #include <ctype.h>
37 #include <sys/types.h>
38 #include <sys/stat.h>
39 #include <unistd.h>
40 #include <errno.h>
41
42 #include "procmime.h"
43 #include "procheader.h"
44 #include "quoted-printable.h"
45 #include "uuencode.h"
46 #include "unmime.h"
47 #include "html.h"
48 #include "enriched.h"
49 #include "codeconv.h"
50 #include "utils.h"
51 #include "prefs_common.h"
52 #include "prefs_gtk.h"
53 #include "alertpanel.h"
54 #include "timing.h"
55 #include "privacy.h"
56
57 static GHashTable *procmime_get_mime_type_table (void);
58 static MimeInfo *procmime_scan_file_short(const gchar *filename);
59 static MimeInfo *procmime_scan_queue_file_short(const gchar *filename);
60 static MimeInfo *procmime_scan_queue_file_full(const gchar *filename, gboolean short_scan);
61
62 MimeInfo *procmime_mimeinfo_new(void)
63 {
64         MimeInfo *mimeinfo;
65
66         mimeinfo = g_new0(MimeInfo, 1);
67         mimeinfo->content        = MIMECONTENT_EMPTY;
68         mimeinfo->data.filename  = NULL;
69
70         mimeinfo->type           = MIMETYPE_UNKNOWN;
71         mimeinfo->encoding_type  = ENC_UNKNOWN;
72         mimeinfo->typeparameters = g_hash_table_new(g_str_hash, g_str_equal);
73
74         mimeinfo->disposition    = DISPOSITIONTYPE_UNKNOWN;
75         mimeinfo->dispositionparameters 
76                                  = g_hash_table_new(g_str_hash, g_str_equal);
77
78         mimeinfo->node           = g_node_new(mimeinfo);
79         
80         return mimeinfo;
81 }
82
83 static gboolean procmime_mimeinfo_parameters_destroy(gpointer key, gpointer value, gpointer user_data)
84 {
85         g_free(key);
86         g_free(value);
87         
88         return TRUE;
89 }
90
91 static gchar *forced_charset = NULL;
92
93 void procmime_force_charset(const gchar *str)
94 {
95         g_free(forced_charset);
96         forced_charset = NULL;
97         if (str)
98                 forced_charset = g_strdup(str);
99 }
100
101 static EncodingType forced_encoding = 0;
102
103 void procmime_force_encoding(EncodingType encoding)
104 {
105         forced_encoding = encoding;
106 }
107
108 static gboolean free_func(GNode *node, gpointer data)
109 {
110         MimeInfo *mimeinfo = (MimeInfo *) node->data;
111
112         switch (mimeinfo->content) {
113         case MIMECONTENT_FILE:
114                 if (mimeinfo->tmp)
115                         claws_unlink(mimeinfo->data.filename);
116                 g_free(mimeinfo->data.filename);
117                 break;
118
119         case MIMECONTENT_MEM:
120                 if (mimeinfo->tmp)
121                         g_free(mimeinfo->data.mem);
122         default:
123                 break;
124         }
125
126         g_free(mimeinfo->subtype);
127         g_free(mimeinfo->description);
128         g_free(mimeinfo->id);
129         g_free(mimeinfo->location);
130
131         g_hash_table_foreach_remove(mimeinfo->typeparameters,
132                 procmime_mimeinfo_parameters_destroy, NULL);
133         g_hash_table_destroy(mimeinfo->typeparameters);
134         g_hash_table_foreach_remove(mimeinfo->dispositionparameters,
135                 procmime_mimeinfo_parameters_destroy, NULL);
136         g_hash_table_destroy(mimeinfo->dispositionparameters);
137
138         if (mimeinfo->privacy)
139                 privacy_free_privacydata(mimeinfo->privacy);
140
141         return FALSE;
142 }
143
144 void procmime_mimeinfo_free_all(MimeInfo **mimeinfo_ptr)
145 {
146         MimeInfo *mimeinfo = *mimeinfo_ptr;
147         GNode *node;
148
149         if (!mimeinfo)
150                 return;
151
152         node = mimeinfo->node;
153         g_node_traverse(node, G_IN_ORDER, G_TRAVERSE_ALL, -1, free_func, NULL);
154
155         g_node_destroy(node);
156
157         g_free(mimeinfo);
158         *mimeinfo_ptr = NULL;
159 }
160
161 MimeInfo *procmime_mimeinfo_parent(MimeInfo *mimeinfo)
162 {
163         cm_return_val_if_fail(mimeinfo != NULL, NULL);
164         cm_return_val_if_fail(mimeinfo->node != NULL, NULL);
165
166         if (mimeinfo->node->parent == NULL)
167                 return NULL;
168         return (MimeInfo *) mimeinfo->node->parent->data;
169 }
170
171 MimeInfo *procmime_mimeinfo_next(MimeInfo *mimeinfo)
172 {
173         cm_return_val_if_fail(mimeinfo != NULL, NULL);
174         cm_return_val_if_fail(mimeinfo->node != NULL, NULL);
175
176         if (mimeinfo->node->children)
177                 return (MimeInfo *) mimeinfo->node->children->data;
178         if (mimeinfo->node->next)
179                 return (MimeInfo *) mimeinfo->node->next->data;
180
181         if (mimeinfo->node->parent == NULL)
182                 return NULL;
183
184         while (mimeinfo->node->parent != NULL) {
185                 mimeinfo = (MimeInfo *) mimeinfo->node->parent->data;
186                 if (mimeinfo->node->next)
187                         return (MimeInfo *) mimeinfo->node->next->data;
188         }
189
190         return NULL;
191 }
192
193 MimeInfo *procmime_scan_message(MsgInfo *msginfo)
194 {
195         gchar *filename;
196         MimeInfo *mimeinfo;
197
198         filename = procmsg_get_message_file_path(msginfo);
199         if (!filename || !is_file_exist(filename)) {
200                 g_free(filename);
201                 return NULL;
202         }
203
204         if (!folder_has_parent_of_type(msginfo->folder, F_QUEUE) &&
205             !folder_has_parent_of_type(msginfo->folder, F_DRAFT))
206                 mimeinfo = procmime_scan_file(filename);
207         else
208                 mimeinfo = procmime_scan_queue_file(filename);
209         g_free(filename);
210
211         return mimeinfo;
212 }
213
214 MimeInfo *procmime_scan_message_short(MsgInfo *msginfo)
215 {
216         gchar *filename;
217         MimeInfo *mimeinfo;
218
219         filename = procmsg_get_message_file_path(msginfo);
220         if (!filename || !is_file_exist(filename)) {
221                 g_free(filename);
222                 return NULL;
223         }
224
225         if (!folder_has_parent_of_type(msginfo->folder, F_QUEUE) &&
226             !folder_has_parent_of_type(msginfo->folder, F_DRAFT))
227                 mimeinfo = procmime_scan_file_short(filename);
228         else
229                 mimeinfo = procmime_scan_queue_file_short(filename);
230         g_free(filename);
231
232         return mimeinfo;
233 }
234
235 enum
236 {
237         H_CONTENT_TRANSFER_ENCODING = 0,
238         H_CONTENT_TYPE              = 1,
239         H_CONTENT_DISPOSITION       = 2,
240         H_CONTENT_DESCRIPTION       = 3,
241         H_SUBJECT                   = 4
242 };
243
244 const gchar *procmime_mimeinfo_get_parameter(MimeInfo *mimeinfo, const gchar *name)
245 {
246         const gchar *value;
247
248         cm_return_val_if_fail(mimeinfo != NULL, NULL);
249         cm_return_val_if_fail(name != NULL, NULL);
250
251         value = g_hash_table_lookup(mimeinfo->dispositionparameters, name);
252         if (value == NULL)
253                 value = g_hash_table_lookup(mimeinfo->typeparameters, name);
254         
255         return value;
256 }
257
258 #ifdef HAVE_FGETS_UNLOCKED
259 #define SC_FGETS fgets_unlocked
260 #define SC_FPUTS fputs_unlocked
261 #define SC_FPUTC fputc_unlocked
262 #define SC_FREAD fread_unlocked
263 #define SC_FWRITE fwrite_unlocked
264 #define SC_FEOF feof_unlocked
265 #define SC_FERROR ferror_unlocked
266
267 static FILE *procmime_fopen(const gchar *file, const gchar *mode)
268 {
269         FILE *fp = g_fopen(file, mode);
270         if (!fp)
271                 return NULL;
272         flockfile(fp);
273         return fp;
274 }
275 static int procmime_fclose(FILE *fp)
276 {
277         funlockfile(fp);
278         return fclose(fp);
279 }
280 #else
281 #define SC_FGETS fgets
282 #define SC_FPUTS fputs
283 #define SC_FPUTC fputc
284 #define SC_FREAD fread
285 #define SC_FWRITE fwrite
286 #define SC_FEOF feof
287 #define SC_FERROR ferror
288 #define procmime_fopen g_fopen
289 #define procmime_fclose fclose
290 #endif
291
292 #define FLUSH_LASTLINE() {                                                      \
293         if (*lastline != '\0') {                                                \
294                 gint llen = 0;                                                  \
295                 strretchomp(lastline);                                          \
296                 llen = strlen(lastline);                                        \
297                 if (lastline[llen-1] == ' ' && strcmp(lastline,"-- ")) {        \
298                         /* this is flowed */                                    \
299                         if (delsp)                                              \
300                                 lastline[llen-1] = '\0';                        \
301                         if (SC_FPUTS(lastline, outfp) == EOF)                   \
302                                 err = TRUE;                                     \
303                 } else {                                                        \
304                         if (SC_FPUTS(lastline, outfp) == EOF)                   \
305                                 err = TRUE;                                     \
306                         if (SC_FPUTS("\n", outfp) == EOF)                               \
307                                 err = TRUE;                                     \
308                 }                                                               \
309         }                                                                       \
310         strcpy(lastline, buf);                                                  \
311 }
312
313 gboolean procmime_decode_content(MimeInfo *mimeinfo)
314 {
315         gchar buf[BUFFSIZE];
316         gint readend;
317         gchar *tmpfilename;
318         FILE *outfp, *infp;
319         GStatBuf statbuf;
320         gboolean tmp_file = FALSE;
321         gboolean flowed = FALSE;
322         gboolean delsp = FALSE; 
323         gboolean err = FALSE;
324         gint state = 0;
325         guint save = 0;
326
327         EncodingType encoding = forced_encoding 
328                                 ? forced_encoding
329                                 : mimeinfo->encoding_type;
330         gchar lastline[BUFFSIZE];
331         memset(lastline, 0, BUFFSIZE);
332
333         cm_return_val_if_fail(mimeinfo != NULL, FALSE);
334
335         if (prefs_common.respect_flowed_format &&
336             mimeinfo->type == MIMETYPE_TEXT && 
337             !strcasecmp(mimeinfo->subtype, "plain")) {
338                 if (procmime_mimeinfo_get_parameter(mimeinfo, "format") != NULL &&
339                     !strcasecmp(procmime_mimeinfo_get_parameter(mimeinfo, "format"),"flowed"))
340                         flowed = TRUE;
341                 if (flowed &&
342                     procmime_mimeinfo_get_parameter(mimeinfo, "delsp") != NULL &&
343                     !strcasecmp(procmime_mimeinfo_get_parameter(mimeinfo, "delsp"),"yes"))
344                         delsp = TRUE;
345         }
346         
347         if (!flowed && (
348              encoding == ENC_UNKNOWN ||
349              encoding == ENC_BINARY ||
350              encoding == ENC_7BIT ||
351              encoding == ENC_8BIT
352             ))
353                 return TRUE;
354
355         if (mimeinfo->type == MIMETYPE_MULTIPART || mimeinfo->type == MIMETYPE_MESSAGE)
356                 return TRUE;
357
358         if (mimeinfo->data.filename == NULL)
359                 return FALSE;
360
361         infp = procmime_fopen(mimeinfo->data.filename, "rb");
362         if (!infp) {
363                 perror("fopen");
364                 return FALSE;
365         }
366         if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
367                 perror("fseek");
368                 procmime_fclose(infp);
369                 return FALSE;
370         }
371
372         outfp = get_tmpfile_in_dir(get_mime_tmp_dir(), &tmpfilename);
373         if (!outfp) {
374                 perror("tmpfile");
375                 procmime_fclose(infp);
376                 return FALSE;
377         }
378 #ifdef HAVE_FGETS_UNLOCKED
379         flockfile(outfp);
380 #endif
381         tmp_file = TRUE;
382         readend = mimeinfo->offset + mimeinfo->length;
383
384         if (encoding == ENC_QUOTED_PRINTABLE) {
385                 while ((ftell(infp) < readend) && (SC_FGETS(buf, sizeof(buf), infp) != NULL)) {
386                         gint len;
387                         len = qp_decode_line(buf);
388                         buf[len]='\0';
389                         if (!flowed) {
390                                 if (SC_FWRITE(buf, 1, len, outfp) < len)
391                                         err = TRUE;
392                         } else {
393                                 FLUSH_LASTLINE();
394                         }
395                 }
396                 if (flowed)
397                         FLUSH_LASTLINE();
398         } else if (encoding == ENC_BASE64) {
399                 gchar outbuf[BUFFSIZE];
400                 gint len, inlen, inread;
401                 gboolean got_error = FALSE;
402                 gboolean uncanonicalize = FALSE;
403                 FILE *tmpfp = NULL;
404                 gboolean null_bytes = FALSE;
405                 gboolean starting = TRUE;
406
407                 if (mimeinfo->type == MIMETYPE_TEXT ||
408                     mimeinfo->type == MIMETYPE_MESSAGE) {
409                         uncanonicalize = TRUE;
410                         tmpfp = my_tmpfile();
411                         if (!tmpfp) {
412                                 perror("tmpfile");
413                                 if (tmp_file) 
414                                         procmime_fclose(outfp);
415                                 procmime_fclose(infp);
416                                 return FALSE;
417                         }
418 #ifdef HAVE_FGETS_UNLOCKED
419                         flockfile(tmpfp);
420 #endif
421                 } else
422                         tmpfp = outfp;
423
424                 while ((inlen = MIN(readend - ftell(infp), sizeof(buf))) > 0 && !err) {
425                         inread = SC_FREAD(buf, 1, inlen, infp);
426                         len = g_base64_decode_step(buf, inlen, outbuf, &state, &save);
427                         if (uncanonicalize == TRUE && strlen(outbuf) < len && starting) {
428                                 uncanonicalize = FALSE;
429                                 null_bytes = TRUE;
430                         }
431                         starting = FALSE;
432                         if (((inread != inlen) || len < 0) && !got_error) {
433                                 g_warning("Bad BASE64 content.");
434                                 if (SC_FWRITE(_("[Error decoding BASE64]\n"),
435                                         sizeof(gchar),
436                                         strlen(_("[Error decoding BASE64]\n")),
437                                         tmpfp) < strlen(_("[Error decoding BASE64]\n")))
438                                         g_warning("error decoding BASE64");
439                                 got_error = TRUE;
440                                 continue;
441                         } else if (len >= 0) {
442                                 /* print out the error message only once 
443                                  * per block */
444                                 if (null_bytes) {
445                                         /* we won't uncanonicalize, output to outfp directly */
446                                         if (SC_FWRITE(outbuf, sizeof(gchar), len, outfp) < len)
447                                                 err = TRUE;
448                                 } else {
449                                         if (SC_FWRITE(outbuf, sizeof(gchar), len, tmpfp) < len)
450                                                 err = TRUE;
451                                 }
452                                 got_error = FALSE;
453                         }
454                 }
455
456                 if (uncanonicalize) {
457                         rewind(tmpfp);
458                         while (SC_FGETS(buf, sizeof(buf), tmpfp) != NULL) {
459                                 strcrchomp(buf);
460                                 if (SC_FPUTS(buf, outfp) == EOF)
461                                         err = TRUE;
462                         }
463                         procmime_fclose(tmpfp);
464                 }
465         } else if (encoding == ENC_X_UUENCODE) {
466                 gchar outbuf[BUFFSIZE];
467                 gint len;
468                 gboolean flag = FALSE;
469
470                 while ((ftell(infp) < readend) && (SC_FGETS(buf, sizeof(buf), infp) != NULL)) {
471                         if (!flag && strncmp(buf,"begin ", 6)) continue;
472
473                         if (flag) {
474                                 len = fromuutobits(outbuf, buf);
475                                 if (len <= 0) {
476                                         if (len < 0) 
477                                                 g_warning("Bad UUENCODE content (%d)", len);
478                                         break;
479                                 }
480                                 if (SC_FWRITE(outbuf, sizeof(gchar), len, outfp) < len)
481                                         err = TRUE;
482                         } else
483                                 flag = TRUE;
484                 }
485         } else {
486                 while ((ftell(infp) < readend) && (SC_FGETS(buf, sizeof(buf), infp) != NULL)) {
487                         if (!flowed) {
488                                 if (SC_FPUTS(buf, outfp) == EOF)
489                                         err = TRUE;
490                         } else {
491                                 FLUSH_LASTLINE();
492                         }
493                 }
494                 if (flowed)
495                         FLUSH_LASTLINE();
496                 if (err == TRUE)
497                         g_warning("write error");
498         }
499
500         procmime_fclose(outfp);
501         procmime_fclose(infp);
502
503         if (err == TRUE) {
504                 return FALSE;
505         }
506
507         if (g_stat(tmpfilename, &statbuf) < 0) {
508                 FILE_OP_ERROR(tmpfilename, "stat");
509                 return FALSE;
510         }
511
512         if (mimeinfo->tmp)
513                 claws_unlink(mimeinfo->data.filename);
514         g_free(mimeinfo->data.filename);
515         mimeinfo->data.filename = tmpfilename;
516         mimeinfo->tmp = TRUE;
517         mimeinfo->offset = 0;
518         mimeinfo->length = statbuf.st_size;
519         mimeinfo->encoding_type = ENC_BINARY;
520
521         return TRUE;
522 }
523
524 #define B64_LINE_SIZE           57
525 #define B64_BUFFSIZE            77
526
527 gboolean procmime_encode_content(MimeInfo *mimeinfo, EncodingType encoding)
528 {
529         FILE *infp = NULL, *outfp;
530         gint len;
531         gchar *tmpfilename;
532         GStatBuf statbuf;
533         gboolean err = FALSE;
534
535         if (mimeinfo->content == MIMECONTENT_EMPTY)
536                 return TRUE;
537
538         if (mimeinfo->encoding_type != ENC_UNKNOWN &&
539             mimeinfo->encoding_type != ENC_BINARY &&
540             mimeinfo->encoding_type != ENC_7BIT &&
541             mimeinfo->encoding_type != ENC_8BIT)
542                 if(!procmime_decode_content(mimeinfo))
543                         return FALSE;
544
545         outfp = get_tmpfile_in_dir(get_mime_tmp_dir(), &tmpfilename);
546         if (!outfp) {
547                 perror("tmpfile");
548                 return FALSE;
549         }
550 #ifdef HAVE_FGETS_UNLOCKED
551         flockfile(outfp);
552 #endif
553
554         if (mimeinfo->content == MIMECONTENT_FILE && mimeinfo->data.filename) {
555                 if ((infp = procmime_fopen(mimeinfo->data.filename, "rb")) == NULL) {
556                         g_warning("Can't open file %s", mimeinfo->data.filename);
557                         procmime_fclose(outfp);
558                         return FALSE;
559                 }
560         } else if (mimeinfo->content == MIMECONTENT_MEM) {
561                 infp = str_open_as_stream(mimeinfo->data.mem);
562                 if (infp == NULL) {
563                         procmime_fclose(outfp);
564                         return FALSE;
565                 }
566 #ifdef HAVE_FGETS_UNLOCKED
567                 flockfile(infp);
568 #endif
569         } else {
570                 procmime_fclose(outfp);
571                 g_warning("Unknown mimeinfo");
572                 return FALSE;
573         }
574
575         if (encoding == ENC_BASE64) {
576                 gchar inbuf[B64_LINE_SIZE], *out;
577                 FILE *tmp_fp = infp;
578                 gchar *tmp_file = NULL;
579
580                 if (mimeinfo->type == MIMETYPE_TEXT ||
581                      mimeinfo->type == MIMETYPE_MESSAGE) {
582                         if (mimeinfo->content == MIMECONTENT_FILE) {
583                                 tmp_file = get_tmp_file();
584                                 if (canonicalize_file(mimeinfo->data.filename, tmp_file) < 0) {
585                                         g_free(tmp_file);
586                                         procmime_fclose(infp);
587                                         procmime_fclose(outfp);
588                                         return FALSE;
589                                 }
590                                 if ((tmp_fp = procmime_fopen(tmp_file, "rb")) == NULL) {
591                                         FILE_OP_ERROR(tmp_file, "fopen");
592                                         claws_unlink(tmp_file);
593                                         g_free(tmp_file);
594                                         procmime_fclose(infp);
595                                         procmime_fclose(outfp);
596                                         return FALSE;
597                                 }
598                         } else {
599                                 gchar *out = canonicalize_str(mimeinfo->data.mem);
600                                 procmime_fclose(infp);
601                                 infp = str_open_as_stream(out);
602                                 tmp_fp = infp;
603                                 g_free(out);
604                                 if (infp == NULL) {
605                                         procmime_fclose(outfp);
606                                         return FALSE;
607                                 }
608 #ifdef HAVE_FGETS_UNLOCKED
609                                 flockfile(infp);
610 #endif
611                         }
612                 }
613
614                 while ((len = SC_FREAD(inbuf, sizeof(gchar),
615                                     B64_LINE_SIZE, tmp_fp))
616                        == B64_LINE_SIZE) {
617                         out = g_base64_encode(inbuf, B64_LINE_SIZE);
618                         if (SC_FPUTS(out, outfp) == EOF)
619                                 err = TRUE;
620                         g_free(out);
621                         if (SC_FPUTC('\n', outfp) == EOF)
622                                 err = TRUE;
623                 }
624                 if (len > 0 && SC_FEOF(tmp_fp)) {
625                         out = g_base64_encode(inbuf, len);
626                         if (SC_FPUTS(out, outfp) == EOF)
627                                 err = TRUE;
628                         g_free(out);
629                         if (SC_FPUTC('\n', outfp) == EOF)
630                                 err = TRUE;
631                 }
632
633                 if (tmp_file) {
634                         procmime_fclose(tmp_fp);
635                         claws_unlink(tmp_file);
636                         g_free(tmp_file);
637                 }
638         } else if (encoding == ENC_QUOTED_PRINTABLE) {
639                 gchar inbuf[BUFFSIZE], outbuf[BUFFSIZE * 4];
640
641                 while (SC_FGETS(inbuf, sizeof(inbuf), infp) != NULL) {
642                         qp_encode_line(outbuf, inbuf);
643
644                         if (!strncmp("From ", outbuf, sizeof("From ")-1)) {
645                                 gchar *tmpbuf = outbuf;
646                                 
647                                 tmpbuf += sizeof("From ")-1;
648                                 
649                                 if (SC_FPUTS("=46rom ", outfp) == EOF)
650                                         err = TRUE;
651                                 if (SC_FPUTS(tmpbuf, outfp) == EOF)
652                                         err = TRUE;
653                         } else {
654                                 if (SC_FPUTS(outbuf, outfp) == EOF)
655                                         err = TRUE;
656                         }
657                 }
658         } else {
659                 gchar buf[BUFFSIZE];
660
661                 while (SC_FGETS(buf, sizeof(buf), infp) != NULL) {
662                         strcrchomp(buf);
663                         if (SC_FPUTS(buf, outfp) == EOF)
664                                 err = TRUE;
665                 }
666         }
667
668         procmime_fclose(outfp);
669         procmime_fclose(infp);
670
671         if (err == TRUE)
672                 return FALSE;
673
674         if (mimeinfo->content == MIMECONTENT_FILE) {
675                 if (mimeinfo->tmp && (mimeinfo->data.filename != NULL))
676                         claws_unlink(mimeinfo->data.filename);
677                 g_free(mimeinfo->data.filename);
678         } else if (mimeinfo->content == MIMECONTENT_MEM) {
679                 if (mimeinfo->tmp && (mimeinfo->data.mem != NULL))
680                         g_free(mimeinfo->data.mem);
681         }
682
683         if (g_stat(tmpfilename, &statbuf) < 0) {
684                 FILE_OP_ERROR(tmpfilename, "stat");
685                 return FALSE;
686         }
687         mimeinfo->content = MIMECONTENT_FILE;
688         mimeinfo->data.filename = tmpfilename;
689         mimeinfo->tmp = TRUE;
690         mimeinfo->offset = 0;
691         mimeinfo->length = statbuf.st_size;
692         mimeinfo->encoding_type = encoding;
693
694         return TRUE;
695 }
696
697 gint procmime_get_part(const gchar *outfile, MimeInfo *mimeinfo)
698 {
699         FILE *infp, *outfp;
700         gchar buf[BUFFSIZE];
701         gint restlength, readlength;
702         gint saved_errno = 0;
703
704         cm_return_val_if_fail(outfile != NULL, -1);
705         cm_return_val_if_fail(mimeinfo != NULL, -1);
706
707         if (mimeinfo->encoding_type != ENC_BINARY && !procmime_decode_content(mimeinfo))
708                 return -EINVAL;
709
710         if ((infp = procmime_fopen(mimeinfo->data.filename, "rb")) == NULL) {
711                 saved_errno = errno;
712                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
713                 return -(saved_errno);
714         }
715         if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
716                 saved_errno = errno;
717                 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
718                 procmime_fclose(infp);
719                 return -(saved_errno);
720         }
721         if ((outfp = procmime_fopen(outfile, "wb")) == NULL) {
722                 saved_errno = errno;
723                 FILE_OP_ERROR(outfile, "fopen");
724                 procmime_fclose(infp);
725                 return -(saved_errno);
726         }
727
728         restlength = mimeinfo->length;
729
730         while ((restlength > 0) && ((readlength = SC_FREAD(buf, 1, restlength > BUFFSIZE ? BUFFSIZE : restlength, infp)) > 0)) {
731                 if (SC_FWRITE(buf, 1, readlength, outfp) != readlength) {
732                         saved_errno = errno;
733                         procmime_fclose(infp);
734                         procmime_fclose(outfp);
735                         return -(saved_errno);
736                 }
737                 restlength -= readlength;
738         }
739
740         procmime_fclose(infp);
741         if (procmime_fclose(outfp) == EOF) {
742                 saved_errno = errno;
743                 FILE_OP_ERROR(outfile, "fclose");
744                 claws_unlink(outfile);
745                 return -(saved_errno);
746         }
747
748         return 0;
749 }
750
751 gboolean procmime_scan_text_content(MimeInfo *mimeinfo,
752                 gboolean (*scan_callback)(const gchar *str, gpointer cb_data),
753                 gpointer cb_data) 
754 {
755         FILE *tmpfp;
756         const gchar *src_codeset;
757         gboolean conv_fail = FALSE;
758         gchar buf[BUFFSIZE];
759         gchar *str;
760         gchar *tmpfile;
761         gboolean scan_ret = FALSE;
762
763         cm_return_val_if_fail(mimeinfo != NULL, TRUE);
764         cm_return_val_if_fail(scan_callback != NULL, TRUE);
765
766         if (!procmime_decode_content(mimeinfo))
767                 return TRUE;
768
769         tmpfile = procmime_get_tmp_file_name(mimeinfo);
770         if (tmpfile == NULL)
771                 return TRUE;
772
773         if (procmime_get_part(tmpfile, mimeinfo) < 0) {
774                 g_free(tmpfile);
775                 return TRUE;
776         }
777
778         tmpfp = procmime_fopen(tmpfile, "rb");
779         if (tmpfp == NULL) {
780                 g_free(tmpfile);
781                 return TRUE;
782         }
783
784         src_codeset = forced_charset
785                       ? forced_charset : 
786                       procmime_mimeinfo_get_parameter(mimeinfo, "charset");
787
788         /* use supersets transparently when possible */
789         if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_ISO_8859_1))
790                 src_codeset = CS_WINDOWS_1252;
791         else if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_X_GBK))
792                 src_codeset = CS_GB18030;
793         else if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_GBK))
794                 src_codeset = CS_GB18030;
795         else if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_GB2312))
796                 src_codeset = CS_GB18030;
797         else if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_X_VIET_VPS))
798                 src_codeset = CS_WINDOWS_874;
799
800         if (mimeinfo->type == MIMETYPE_TEXT && !g_ascii_strcasecmp(mimeinfo->subtype, "html")) {
801                 SC_HTMLParser *parser;
802                 CodeConverter *conv;
803
804                 conv = conv_code_converter_new(src_codeset);
805                 parser = sc_html_parser_new(tmpfp, conv);
806                 while ((str = sc_html_parse(parser)) != NULL) {
807                         if ((scan_ret = scan_callback(str, cb_data)) == TRUE)
808                                 break;
809                 }
810                 sc_html_parser_destroy(parser);
811                 conv_code_converter_destroy(conv);
812         } else if (mimeinfo->type == MIMETYPE_TEXT && !g_ascii_strcasecmp(mimeinfo->subtype, "enriched")) {
813                 ERTFParser *parser;
814                 CodeConverter *conv;
815
816                 conv = conv_code_converter_new(src_codeset);
817                 parser = ertf_parser_new(tmpfp, conv);
818                 while ((str = ertf_parse(parser)) != NULL) {
819                         if ((scan_ret = scan_callback(str, cb_data)) == TRUE)
820                                 break;
821                 }
822                 ertf_parser_destroy(parser);
823                 conv_code_converter_destroy(conv);
824         } else if (mimeinfo->type == MIMETYPE_TEXT && mimeinfo->disposition != DISPOSITIONTYPE_ATTACHMENT) {
825                 while (SC_FGETS(buf, sizeof(buf), tmpfp) != NULL) {
826                         str = conv_codeset_strdup(buf, src_codeset, CS_UTF_8);
827                         if (str) {
828                                 if ((scan_ret = scan_callback(str, cb_data)) == TRUE) {
829                                         g_free(str);
830                                         break;
831                                 }
832                                 g_free(str);
833                         } else {
834                                 conv_fail = TRUE;
835                                 if ((scan_ret = scan_callback(buf, cb_data)) == TRUE)
836                                         break;
837                         }
838                 }
839         }
840
841         if (conv_fail)
842                 g_warning("procmime_get_text_content(): Code conversion failed.");
843
844         procmime_fclose(tmpfp);
845         claws_unlink(tmpfile);
846         g_free(tmpfile);
847
848         return scan_ret;
849 }
850
851 static gboolean scan_fputs_cb(const gchar *str, gpointer fp)
852 {
853         if (SC_FPUTS(str, (FILE *)fp) == EOF)
854                 return TRUE;
855         
856         return FALSE;
857 }
858
859 FILE *procmime_get_text_content(MimeInfo *mimeinfo)
860 {
861         FILE *outfp;
862         gboolean err;
863
864         if ((outfp = my_tmpfile()) == NULL) {
865                 perror("tmpfile");
866                 return NULL;
867         }
868 #ifdef HAVE_FGETS_UNLOCKED
869         flockfile(outfp);
870 #endif
871
872         err = procmime_scan_text_content(mimeinfo, scan_fputs_cb, outfp);
873
874         rewind(outfp);
875         if (err == TRUE) {
876                 procmime_fclose(outfp);
877                 return NULL;
878         }
879 #ifdef HAVE_FGETS_UNLOCKED
880         funlockfile(outfp);
881 #endif
882         return outfp;
883
884 }
885
886 FILE *procmime_get_binary_content(MimeInfo *mimeinfo)
887 {
888         FILE *outfp;
889         gchar *tmpfile;
890
891         cm_return_val_if_fail(mimeinfo != NULL, NULL);
892
893         if (!procmime_decode_content(mimeinfo))
894                 return NULL;
895
896         tmpfile = procmime_get_tmp_file_name(mimeinfo);
897         if (tmpfile == NULL)
898                 return NULL;
899
900         if (procmime_get_part(tmpfile, mimeinfo) < 0) {
901                 g_free(tmpfile);
902                 return NULL;
903         }
904
905         outfp = procmime_fopen(tmpfile, "rb");
906         if (outfp == NULL) {
907                 g_unlink(tmpfile);
908                 g_free(tmpfile);
909                 return NULL;
910         }
911
912         g_unlink(tmpfile);
913         g_free(tmpfile);
914
915 #ifdef HAVE_FGETS_UNLOCKED
916         funlockfile(outfp);
917 #endif
918         return outfp;
919 }
920
921 /* search the first text part of (multipart) MIME message,
922    decode, convert it and output to outfp. */
923 FILE *procmime_get_first_text_content(MsgInfo *msginfo)
924 {
925         FILE *outfp = NULL;
926         MimeInfo *mimeinfo, *partinfo;
927         gboolean empty_ok = FALSE, short_scan = TRUE;
928
929         cm_return_val_if_fail(msginfo != NULL, NULL);
930
931         /* first we try to short-scan (for speed), refusing empty parts */
932 scan_again:
933         if (short_scan)
934                 mimeinfo = procmime_scan_message_short(msginfo);
935         else
936                 mimeinfo = procmime_scan_message(msginfo);
937         if (!mimeinfo) return NULL;
938
939         partinfo = mimeinfo;
940         while (partinfo && (partinfo->type != MIMETYPE_TEXT ||
941                (partinfo->length == 0 && !empty_ok))) {
942                 partinfo = procmime_mimeinfo_next(partinfo);
943         }
944         if (partinfo)
945                 outfp = procmime_get_text_content(partinfo);
946         else if (!empty_ok && short_scan) {
947                 /* if short scan didn't find a non-empty part, rescan
948                  * fully for non-empty parts
949                  */
950                 short_scan = FALSE;
951                 procmime_mimeinfo_free_all(&mimeinfo);
952                 goto scan_again;
953         } else if (!empty_ok && !short_scan) {
954                 /* if full scan didn't find a non-empty part, rescan
955                  * accepting empty parts 
956                  */
957                 empty_ok = TRUE;
958                 procmime_mimeinfo_free_all(&mimeinfo);
959                 goto scan_again;
960         }
961         procmime_mimeinfo_free_all(&mimeinfo);
962
963         /* outfp already unlocked at this time */
964         return outfp;
965 }
966
967
968 static gboolean find_encrypted_func(GNode *node, gpointer data)
969 {
970         MimeInfo *mimeinfo = (MimeInfo *) node->data;
971         MimeInfo **encinfo = (MimeInfo **) data;
972         
973         if (privacy_mimeinfo_is_encrypted(mimeinfo)) {
974                 *encinfo = mimeinfo;
975                 return TRUE;
976         }
977         
978         return FALSE;
979 }
980
981 static MimeInfo *find_encrypted_part(MimeInfo *rootinfo)
982 {
983         MimeInfo *encinfo = NULL;
984
985         g_node_traverse(rootinfo->node, G_IN_ORDER, G_TRAVERSE_ALL, -1,
986                 find_encrypted_func, &encinfo);
987         
988         return encinfo;
989 }
990
991 /* search the first encrypted text part of (multipart) MIME message,
992    decode, convert it and output to outfp. */
993 FILE *procmime_get_first_encrypted_text_content(MsgInfo *msginfo)
994 {
995         FILE *outfp = NULL;
996         MimeInfo *mimeinfo, *partinfo, *encinfo;
997
998         cm_return_val_if_fail(msginfo != NULL, NULL);
999
1000         mimeinfo = procmime_scan_message(msginfo);
1001         if (!mimeinfo) {
1002                 return NULL;
1003         }
1004
1005         partinfo = mimeinfo;
1006         if ((encinfo = find_encrypted_part(partinfo)) != NULL) {
1007                 debug_print("decrypting message part\n");
1008                 if (privacy_mimeinfo_decrypt(encinfo) < 0) {
1009                         alertpanel_error(_("Couldn't decrypt: %s"),
1010                                 privacy_get_error());
1011                         return NULL;
1012                 }
1013         }
1014         partinfo = mimeinfo;
1015         while (partinfo && partinfo->type != MIMETYPE_TEXT) {
1016                 partinfo = procmime_mimeinfo_next(partinfo);
1017                 if (privacy_mimeinfo_is_signed(partinfo))
1018                         procmsg_msginfo_set_flags(msginfo, 0, MSG_SIGNED);
1019         }
1020
1021         if (partinfo)
1022                 outfp = procmime_get_text_content(partinfo);
1023
1024         procmime_mimeinfo_free_all(&mimeinfo);
1025
1026         /* outfp already unlocked at this time */
1027         return outfp;
1028 }
1029
1030 gboolean procmime_msginfo_is_encrypted(MsgInfo *msginfo)
1031 {
1032         MimeInfo *mimeinfo, *partinfo;
1033         gboolean result = FALSE;
1034
1035         cm_return_val_if_fail(msginfo != NULL, FALSE);
1036
1037         mimeinfo = procmime_scan_message(msginfo);
1038         if (!mimeinfo) {
1039                 return FALSE;
1040         }
1041
1042         partinfo = mimeinfo;
1043         result = (find_encrypted_part(partinfo) != NULL);
1044         procmime_mimeinfo_free_all(&mimeinfo);
1045
1046         return result;
1047 }
1048
1049 gchar *procmime_get_tmp_file_name(MimeInfo *mimeinfo)
1050 {
1051         static guint32 id = 0;
1052         gchar *base;
1053         gchar *filename;
1054         gchar f_prefix[10];
1055
1056         cm_return_val_if_fail(mimeinfo != NULL, NULL);
1057
1058         g_snprintf(f_prefix, sizeof(f_prefix), "%08x.", id++);
1059
1060         if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
1061                 base = g_strdup("mimetmp.html");
1062         else {
1063                 const gchar *basetmp;
1064
1065                 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
1066                 if (basetmp == NULL)
1067                         basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
1068                 if (basetmp == NULL)
1069                         basetmp = "mimetmp";
1070                 basetmp = g_path_get_basename(basetmp);
1071                 if (*basetmp == '\0') 
1072                         basetmp = g_strdup("mimetmp");
1073                 base = conv_filename_from_utf8(basetmp);
1074                 g_free((gchar*)basetmp);
1075                 subst_for_shellsafe_filename(base);
1076         }
1077
1078         filename = g_strconcat(get_mime_tmp_dir(), G_DIR_SEPARATOR_S,
1079                                f_prefix, base, NULL);
1080
1081         g_free(base);
1082         
1083         return filename;
1084 }
1085
1086 static GList *mime_type_list = NULL;
1087
1088 gchar *procmime_get_mime_type(const gchar *filename)
1089 {
1090         const gchar *p;
1091         gchar *ext = NULL;
1092         gchar *base;
1093 #ifndef G_OS_WIN32
1094         static GHashTable *mime_type_table = NULL;
1095         MimeType *mime_type;
1096
1097         if (!mime_type_table) {
1098                 mime_type_table = procmime_get_mime_type_table();
1099                 if (!mime_type_table) return NULL;
1100         }
1101 #endif
1102
1103         if (filename == NULL)
1104                 return NULL;
1105
1106         base = g_path_get_basename(filename);
1107         if ((p = strrchr(base, '.')) != NULL)
1108                 ext = g_utf8_strdown(p + 1, -1);
1109         else
1110                 ext = g_utf8_strdown(base, -1);
1111         g_free(base);
1112
1113 #ifndef G_OS_WIN32
1114         mime_type = g_hash_table_lookup(mime_type_table, ext);
1115         
1116         if (mime_type) {
1117                 gchar *str;
1118                 str = g_strconcat(mime_type->type, "/", mime_type->sub_type,
1119                                   NULL);
1120                 debug_print("got type %s for %s\n", str, ext);
1121                 g_free(ext);
1122                 return str;
1123         } 
1124         return NULL;
1125 #else
1126         gchar *str = get_content_type_from_registry_with_ext(ext);
1127
1128         g_free(ext);
1129         return str;
1130 #endif
1131 }
1132
1133 static guint procmime_str_hash(gconstpointer gptr)
1134 {
1135         guint hash_result = 0;
1136         const char *str;
1137
1138         for (str = gptr; str && *str; str++) {
1139                 if (isupper(*str)) hash_result += (*str + ' ');
1140                 else hash_result += *str;
1141         }
1142
1143         return hash_result;
1144 }
1145
1146 static gint procmime_str_equal(gconstpointer gptr1, gconstpointer gptr2)
1147 {
1148         const char *str1 = gptr1;
1149         const char *str2 = gptr2;
1150
1151         return !g_utf8_collate(str1, str2);
1152 }
1153
1154 static GHashTable *procmime_get_mime_type_table(void)
1155 {
1156         GHashTable *table = NULL;
1157         GList *cur;
1158         MimeType *mime_type;
1159         gchar **exts;
1160
1161         if (!mime_type_list) {
1162                 mime_type_list = procmime_get_mime_type_list();
1163                 if (!mime_type_list) return NULL;
1164         }
1165
1166         table = g_hash_table_new(procmime_str_hash, procmime_str_equal);
1167
1168         for (cur = mime_type_list; cur != NULL; cur = cur->next) {
1169                 gint i;
1170                 gchar *key;
1171
1172                 mime_type = (MimeType *)cur->data;
1173
1174                 if (!mime_type->extension) continue;
1175
1176                 exts = g_strsplit(mime_type->extension, " ", 16);
1177                 for (i = 0; exts[i] != NULL; i++) {
1178                         /* Don't overwrite previously inserted extension */
1179                         if (!g_hash_table_lookup(table, exts[i])) {
1180                                 key = g_strdup(exts[i]);
1181                                 g_hash_table_insert(table, key, mime_type);
1182                         }
1183                 }
1184                 g_strfreev(exts);
1185         }
1186
1187         return table;
1188 }
1189
1190 GList *procmime_get_mime_type_list(void)
1191 {
1192         GList *list = NULL;
1193         FILE *fp;
1194         gchar buf[BUFFSIZE];
1195         gchar *p;
1196         gchar *delim;
1197         MimeType *mime_type;
1198         gboolean fp_is_glob_file = TRUE;
1199
1200         if (mime_type_list) 
1201                 return mime_type_list;
1202         
1203 #if defined(__NetBSD__) || defined(__OpenBSD__) || defined(__FreeBSD__)
1204         if ((fp = procmime_fopen(DATAROOTDIR "/mime/globs", "rb")) == NULL) 
1205 #else
1206         if ((fp = procmime_fopen("/usr/share/mime/globs", "rb")) == NULL) 
1207 #endif
1208         {
1209                 fp_is_glob_file = FALSE;
1210                 if ((fp = procmime_fopen("/etc/mime.types", "rb")) == NULL) {
1211                         if ((fp = procmime_fopen(SYSCONFDIR "/mime.types", "rb")) 
1212                                 == NULL) {
1213                                 FILE_OP_ERROR(SYSCONFDIR "/mime.types", 
1214                                         "fopen");
1215                                 return NULL;
1216                         }
1217                 }
1218         }
1219
1220         while (SC_FGETS(buf, sizeof(buf), fp) != NULL) {
1221                 p = strchr(buf, '#');
1222                 if (p) *p = '\0';
1223                 g_strstrip(buf);
1224
1225                 p = buf;
1226                 
1227                 if (fp_is_glob_file) {
1228                         while (*p && !g_ascii_isspace(*p) && (*p!=':')) p++;
1229                 } else {
1230                         while (*p && !g_ascii_isspace(*p)) p++;
1231                 }
1232
1233                 if (*p) {
1234                         *p = '\0';
1235                         p++;
1236                 }
1237                 delim = strchr(buf, '/');
1238                 if (delim == NULL) continue;
1239                 *delim = '\0';
1240
1241                 mime_type = g_new(MimeType, 1);
1242                 mime_type->type = g_strdup(buf);
1243                 mime_type->sub_type = g_strdup(delim + 1);
1244
1245                 if (fp_is_glob_file) {
1246                         while (*p && (g_ascii_isspace(*p)||(*p=='*')||(*p=='.'))) p++;
1247                 } else {
1248                         while (*p && g_ascii_isspace(*p)) p++;
1249                 }
1250
1251                 if (*p)
1252                         mime_type->extension = g_utf8_strdown(p, -1);
1253                 else
1254                         mime_type->extension = NULL;
1255
1256                 list = g_list_append(list, mime_type);
1257         }
1258
1259         procmime_fclose(fp);
1260
1261         if (!list)
1262                 g_warning("Can't read mime.types");
1263
1264         return list;
1265 }
1266
1267 EncodingType procmime_get_encoding_for_charset(const gchar *charset)
1268 {
1269         if (!charset)
1270                 return ENC_8BIT;
1271         else if (!g_ascii_strncasecmp(charset, "ISO-2022-", 9) ||
1272                  !g_ascii_strcasecmp(charset, "US-ASCII"))
1273                 return ENC_7BIT;
1274         else if (!g_ascii_strcasecmp(charset, "ISO-8859-5") ||
1275                  !g_ascii_strncasecmp(charset, "KOI8-", 5) ||
1276                  !g_ascii_strcasecmp(charset, "X-MAC-CYRILLIC") ||
1277                  !g_ascii_strcasecmp(charset, "MAC-CYRILLIC") ||
1278                  !g_ascii_strcasecmp(charset, "Windows-1251"))
1279                 return ENC_8BIT;
1280         else if (!g_ascii_strncasecmp(charset, "ISO-8859-", 9))
1281                 return ENC_QUOTED_PRINTABLE;
1282         else if (!g_ascii_strncasecmp(charset, "UTF-8", 5))
1283                 return ENC_QUOTED_PRINTABLE;
1284         else 
1285                 return ENC_8BIT;
1286 }
1287
1288 EncodingType procmime_get_encoding_for_text_file(const gchar *file, gboolean *has_binary)
1289 {
1290         FILE *fp;
1291         guchar buf[BUFFSIZE];
1292         size_t len;
1293         size_t octet_chars = 0;
1294         size_t total_len = 0;
1295         gfloat octet_percentage;
1296         gboolean force_b64 = FALSE;
1297
1298         if ((fp = procmime_fopen(file, "rb")) == NULL) {
1299                 FILE_OP_ERROR(file, "fopen");
1300                 return ENC_UNKNOWN;
1301         }
1302
1303         while ((len = SC_FREAD(buf, sizeof(guchar), sizeof(buf), fp)) > 0) {
1304                 guchar *p;
1305                 gint i;
1306
1307                 for (p = buf, i = 0; i < len; ++p, ++i) {
1308                         if (*p & 0x80)
1309                                 ++octet_chars;
1310                         if (*p == '\0') {
1311                                 force_b64 = TRUE;
1312                                 *has_binary = TRUE;
1313                         }
1314                 }
1315                 total_len += len;
1316         }
1317
1318         procmime_fclose(fp);
1319         
1320         if (total_len > 0)
1321                 octet_percentage = (gfloat)octet_chars / (gfloat)total_len;
1322         else
1323                 octet_percentage = 0.0;
1324
1325         debug_print("procmime_get_encoding_for_text_file(): "
1326                     "8bit chars: %zd / %zd (%f%%)\n", octet_chars, total_len,
1327                     100.0 * octet_percentage);
1328
1329         if (octet_percentage > 0.20 || force_b64) {
1330                 debug_print("using BASE64\n");
1331                 return ENC_BASE64;
1332         } else if (octet_chars > 0) {
1333                 debug_print("using quoted-printable\n");
1334                 return ENC_QUOTED_PRINTABLE;
1335         } else {
1336                 debug_print("using 7bit\n");
1337                 return ENC_7BIT;
1338         }
1339 }
1340
1341 struct EncodingTable 
1342 {
1343         gchar *str;
1344         EncodingType enc_type;
1345 };
1346
1347 struct EncodingTable encoding_table[] = {
1348         {"7bit", ENC_7BIT},
1349         {"8bit", ENC_8BIT},
1350         {"binary", ENC_BINARY},
1351         {"quoted-printable", ENC_QUOTED_PRINTABLE},
1352         {"base64", ENC_BASE64},
1353         {"x-uuencode", ENC_UNKNOWN},
1354         {NULL, ENC_UNKNOWN},
1355 };
1356
1357 const gchar *procmime_get_encoding_str(EncodingType encoding)
1358 {
1359         struct EncodingTable *enc_table;
1360         
1361         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1362                 if (enc_table->enc_type == encoding)
1363                         return enc_table->str;
1364         }
1365         return NULL;
1366 }
1367
1368 /* --- NEW MIME STUFF --- */
1369 struct TypeTable
1370 {
1371         gchar *str;
1372         MimeMediaType type;
1373 };
1374
1375 static struct TypeTable mime_type_table[] = {
1376         {"text", MIMETYPE_TEXT},
1377         {"image", MIMETYPE_IMAGE},
1378         {"audio", MIMETYPE_AUDIO},
1379         {"video", MIMETYPE_VIDEO},
1380         {"application", MIMETYPE_APPLICATION},
1381         {"message", MIMETYPE_MESSAGE},
1382         {"multipart", MIMETYPE_MULTIPART},
1383         {NULL, 0},
1384 };
1385
1386 const gchar *procmime_get_media_type_str(MimeMediaType type)
1387 {
1388         struct TypeTable *type_table;
1389         
1390         for (type_table = mime_type_table; type_table->str != NULL; type_table++) {
1391                 if (type_table->type == type)
1392                         return type_table->str;
1393         }
1394         return NULL;
1395 }
1396
1397 MimeMediaType procmime_get_media_type(const gchar *str)
1398 {
1399         struct TypeTable *typetablearray;
1400
1401         for (typetablearray = mime_type_table; typetablearray->str != NULL; typetablearray++)
1402                 if (g_ascii_strncasecmp(str, typetablearray->str, strlen(typetablearray->str)) == 0)
1403                         return typetablearray->type;
1404
1405         return MIMETYPE_UNKNOWN;
1406 }
1407
1408 /*!
1409  *\brief        Safe wrapper for content type string.
1410  *
1411  *\return       const gchar * Pointer to content type string. 
1412  */
1413 gchar *procmime_get_content_type_str(MimeMediaType type,
1414                                            const char *subtype)
1415 {
1416         const gchar *type_str = NULL;
1417
1418         if (subtype == NULL || !(type_str = procmime_get_media_type_str(type)))
1419                 return g_strdup("unknown");
1420         return g_strdup_printf("%s/%s", type_str, subtype);
1421 }
1422
1423 static int procmime_parse_mimepart(MimeInfo *parent,
1424                              gchar *content_type,
1425                              gchar *content_encoding,
1426                              gchar *content_description,
1427                              gchar *content_id,
1428                              gchar *content_disposition,
1429                              gchar *content_location,
1430                              const gchar *original_msgid,
1431                              const gchar *disposition_notification_hdr,
1432                              const gchar *filename,
1433                              guint offset,
1434                              guint length,
1435                              gboolean short_scan);
1436
1437 static void procmime_parse_message_rfc822(MimeInfo *mimeinfo, gboolean short_scan)
1438 {
1439         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1440                                 {"Content-Transfer-Encoding:",
1441                                                    NULL, FALSE},
1442                                 {"Content-Description:",
1443                                                    NULL, TRUE},
1444                                 {"Content-ID:",
1445                                                    NULL, TRUE},
1446                                 {"Content-Disposition:",
1447                                                    NULL, TRUE},
1448                                 {"Content-Location:",
1449                                                    NULL, TRUE},
1450                                 {"MIME-Version:",
1451                                                    NULL, TRUE},
1452                                 {"Original-Message-ID:",
1453                                                    NULL, TRUE},
1454                                 {"Disposition:",
1455                                                    NULL, TRUE},
1456                                 {NULL,             NULL, FALSE}};
1457         guint content_start, i;
1458         FILE *fp;
1459         gchar *tmp;
1460         gint len = 0;
1461
1462         procmime_decode_content(mimeinfo);
1463
1464         fp = procmime_fopen(mimeinfo->data.filename, "rb");
1465         if (fp == NULL) {
1466                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1467                 return;
1468         }
1469         if (fseek(fp, mimeinfo->offset, SEEK_SET) < 0) {
1470                 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
1471                 procmime_fclose(fp);
1472                 return;
1473         }
1474         procheader_get_header_fields(fp, hentry);
1475         if (hentry[0].body != NULL) {
1476                 tmp = conv_unmime_header(hentry[0].body, NULL, FALSE);
1477                 g_free(hentry[0].body);
1478                 hentry[0].body = tmp;
1479         }                
1480         if (hentry[2].body != NULL) {
1481                 tmp = conv_unmime_header(hentry[2].body, NULL, FALSE);
1482                 g_free(hentry[2].body);
1483                 hentry[2].body = tmp;
1484         }                
1485         if (hentry[4].body != NULL) {
1486                 tmp = conv_unmime_header(hentry[4].body, NULL, FALSE);
1487                 g_free(hentry[4].body);
1488                 hentry[4].body = tmp;
1489         }                
1490         if (hentry[5].body != NULL) {
1491                 tmp = conv_unmime_header(hentry[5].body, NULL, FALSE);
1492                 g_free(hentry[5].body);
1493                 hentry[5].body = tmp;
1494         }                
1495         if (hentry[7].body != NULL) {
1496                 tmp = conv_unmime_header(hentry[7].body, NULL, FALSE);
1497                 g_free(hentry[7].body);
1498                 hentry[7].body = tmp;
1499         }
1500         if (hentry[8].body != NULL) {
1501                 tmp = conv_unmime_header(hentry[8].body, NULL, FALSE);
1502                 g_free(hentry[8].body);
1503                 hentry[8].body = tmp;
1504         }
1505   
1506         content_start = ftell(fp);
1507         procmime_fclose(fp);
1508         
1509         len = mimeinfo->length - (content_start - mimeinfo->offset);
1510         if (len < 0)
1511                 len = 0;
1512         procmime_parse_mimepart(mimeinfo,
1513                                 hentry[0].body, hentry[1].body,
1514                                 hentry[2].body, hentry[3].body,
1515                                 hentry[4].body, hentry[5].body,
1516                                 hentry[7].body, hentry[8].body, 
1517                                 mimeinfo->data.filename, content_start,
1518                                 len, short_scan);
1519         
1520         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1521                 g_free(hentry[i].body);
1522                 hentry[i].body = NULL;
1523         }
1524 }
1525
1526 static void procmime_parse_disposition_notification(MimeInfo *mimeinfo, 
1527                 const gchar *original_msgid, const gchar *disposition_notification_hdr,
1528                 gboolean short_scan)
1529 {
1530         HeaderEntry hentry[] = {{"Original-Message-ID:",  NULL, TRUE},
1531                                 {"Disposition:",          NULL, TRUE},
1532                                 {NULL,                    NULL, FALSE}};
1533         guint i;
1534         FILE *fp;
1535         gchar *orig_msg_id = NULL;
1536         gchar *disp = NULL;
1537
1538         procmime_decode_content(mimeinfo);
1539
1540         debug_print("parse disposition notification\n");
1541         fp = procmime_fopen(mimeinfo->data.filename, "rb");
1542         if (fp == NULL) {
1543                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1544                 return;
1545         }
1546         if (fseek(fp, mimeinfo->offset, SEEK_SET) < 0) {
1547                 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
1548                 procmime_fclose(fp);
1549                 return;
1550         }
1551
1552         if (original_msgid && disposition_notification_hdr) {
1553                 hentry[0].body = g_strdup(original_msgid);
1554                 hentry[1].body = g_strdup(disposition_notification_hdr);
1555         } else {
1556                 procheader_get_header_fields(fp, hentry);
1557         }
1558     
1559         procmime_fclose(fp);
1560
1561         if (!hentry[0].body || !hentry[1].body) {
1562                 debug_print("MsgId %s, Disp %s\n",
1563                         hentry[0].body ? hentry[0].body:"(nil)",
1564                         hentry[1].body ? hentry[1].body:"(nil)");
1565                 goto bail;
1566         }
1567
1568         orig_msg_id = g_strdup(hentry[0].body);
1569         disp = g_strdup(hentry[1].body);
1570
1571         extract_parenthesis(orig_msg_id, '<', '>');
1572         remove_space(orig_msg_id);
1573         
1574         if (strstr(disp, "displayed")) {
1575                 /* find sent message, if possible */
1576                 MsgInfo *info = NULL;
1577                 GList *flist;
1578                 debug_print("%s has been displayed.\n", orig_msg_id);
1579                 for (flist = folder_get_list(); flist != NULL; flist = g_list_next(flist)) {
1580                         FolderItem *outbox = ((Folder *)(flist->data))->outbox;
1581                         if (!outbox) {
1582                                 debug_print("skipping folder with no outbox...\n");
1583                                 continue;
1584                         }
1585                         info = folder_item_get_msginfo_by_msgid(outbox, orig_msg_id);
1586                         debug_print("%s %s in %s\n", info?"found":"didn't find", orig_msg_id, outbox->path);
1587                         if (info) {
1588                                 procmsg_msginfo_set_flags(info, MSG_RETRCPT_GOT, 0);
1589                                 procmsg_msginfo_free(&info);
1590                         }
1591                 }
1592         }
1593         g_free(orig_msg_id);
1594         g_free(disp);
1595 bail:
1596         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1597                 g_free(hentry[i].body);
1598                 hentry[i].body = NULL;
1599         }
1600 }
1601
1602 #define GET_HEADERS() {                                         \
1603         procheader_get_header_fields(fp, hentry);               \
1604         if (hentry[0].body != NULL) {                           \
1605                 tmp = conv_unmime_header(hentry[0].body, NULL, FALSE);  \
1606                 g_free(hentry[0].body);                         \
1607                 hentry[0].body = tmp;                           \
1608         }                                                       \
1609         if (hentry[2].body != NULL) {                           \
1610                 tmp = conv_unmime_header(hentry[2].body, NULL, FALSE);  \
1611                 g_free(hentry[2].body);                         \
1612                 hentry[2].body = tmp;                           \
1613         }                                                       \
1614         if (hentry[4].body != NULL) {                           \
1615                 tmp = conv_unmime_header(hentry[4].body, NULL, FALSE);  \
1616                 g_free(hentry[4].body);                         \
1617                 hentry[4].body = tmp;                           \
1618         }                                                       \
1619         if (hentry[5].body != NULL) {                           \
1620                 tmp = conv_unmime_header(hentry[5].body, NULL, FALSE);  \
1621                 g_free(hentry[5].body);                         \
1622                 hentry[5].body = tmp;                           \
1623         }                                                       \
1624         if (hentry[6].body != NULL) {                           \
1625                 tmp = conv_unmime_header(hentry[6].body, NULL, FALSE);  \
1626                 g_free(hentry[6].body);                         \
1627                 hentry[6].body = tmp;                           \
1628         }                                                       \
1629         if (hentry[7].body != NULL) {                           \
1630                 tmp = conv_unmime_header(hentry[7].body, NULL, FALSE);  \
1631                 g_free(hentry[7].body);                         \
1632                 hentry[7].body = tmp;                           \
1633         }                                                       \
1634 }
1635
1636 static void procmime_parse_multipart(MimeInfo *mimeinfo, gboolean short_scan)
1637 {
1638         HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1639                                 {"Content-Transfer-Encoding:",
1640                                                    NULL, FALSE},
1641                                 {"Content-Description:",
1642                                                    NULL, TRUE},
1643                                 {"Content-ID:",
1644                                                    NULL, TRUE},
1645                                 {"Content-Disposition:",
1646                                                    NULL, TRUE},
1647                                 {"Content-Location:",
1648                                                    NULL, TRUE},
1649                                 {"Original-Message-ID:",
1650                                                    NULL, TRUE},
1651                                 {"Disposition:",
1652                                                    NULL, TRUE},
1653                                 {NULL,             NULL, FALSE}};
1654         gchar *tmp;
1655         gchar *boundary;
1656         gint boundary_len = 0, lastoffset = -1, i;
1657         gchar buf[BUFFSIZE];
1658         FILE *fp;
1659         int result = 0;
1660         gboolean start_found = FALSE;
1661         gboolean end_found = FALSE;
1662
1663         boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
1664         if (!boundary)
1665                 return;
1666         boundary_len = strlen(boundary);
1667
1668         procmime_decode_content(mimeinfo);
1669
1670         fp = procmime_fopen(mimeinfo->data.filename, "rb");
1671         if (fp == NULL) {
1672                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1673                 return;
1674         }
1675
1676         if (fseek(fp, mimeinfo->offset, SEEK_SET) < 0) {
1677                 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
1678                 procmime_fclose(fp);
1679                 return;
1680         }
1681
1682         while (SC_FGETS(buf, sizeof(buf), fp) != NULL && result == 0) {
1683                 if (ftell(fp) - 1 > (mimeinfo->offset + mimeinfo->length))
1684                         break;
1685
1686                 if (IS_BOUNDARY(buf, boundary, boundary_len)) {
1687                         start_found = TRUE;
1688
1689                         if (lastoffset != -1) {
1690                                 gint len = (ftell(fp) - strlen(buf)) - lastoffset - 1;
1691                                 if (len < 0)
1692                                         len = 0;
1693                                 result = procmime_parse_mimepart(mimeinfo,
1694                                                         hentry[0].body, hentry[1].body,
1695                                                         hentry[2].body, hentry[3].body, 
1696                                                         hentry[4].body, hentry[5].body,
1697                                                         hentry[6].body, hentry[7].body,
1698                                                         mimeinfo->data.filename, lastoffset,
1699                                                         len, short_scan);
1700                                 if (result == 1 && short_scan)
1701                                         break;
1702                                 
1703                         } 
1704                         
1705                         if (buf[2 + boundary_len]     == '-' &&
1706                             buf[2 + boundary_len + 1] == '-') {
1707                                 end_found = TRUE;
1708                                 break;
1709                         }
1710                         for (i = 0; i < (sizeof hentry / sizeof hentry[0]) ; i++) {
1711                                 g_free(hentry[i].body);
1712                                 hentry[i].body = NULL;
1713                         }
1714                         GET_HEADERS();
1715                         lastoffset = ftell(fp);
1716                 }
1717         }
1718         
1719         if (start_found && !end_found && lastoffset != -1) {
1720                 gint len = (ftell(fp) - strlen(buf)) - lastoffset - 1;
1721
1722                 if (len >= 0) {
1723                         result = procmime_parse_mimepart(mimeinfo,
1724                                         hentry[0].body, hentry[1].body,
1725                                         hentry[2].body, hentry[3].body, 
1726                                         hentry[4].body, hentry[5].body,
1727                                         hentry[6].body, hentry[7].body,
1728                                         mimeinfo->data.filename, lastoffset,
1729                                         len, short_scan);
1730                 }
1731                 mimeinfo->broken = TRUE;
1732         }
1733         
1734         for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1735                 g_free(hentry[i].body);
1736                 hentry[i].body = NULL;
1737         }
1738         procmime_fclose(fp);
1739 }
1740
1741 static void parse_parameters(const gchar *parameters, GHashTable *table)
1742 {
1743         gchar *params, *param, *next;
1744         GSList *convlist = NULL, *concatlist = NULL, *cur;
1745
1746         params = g_strdup(parameters);
1747         param = params;
1748         next = params;
1749         for (; next != NULL; param = next) {
1750                 gchar *attribute, *value, *tmp, *down_attr, *orig_down_attr;
1751                 gint len;
1752                 gboolean convert = FALSE;
1753
1754                 next = strchr_with_skip_quote(param, '"', ';');
1755                 if (next != NULL) {
1756                         next[0] = '\0';
1757                         next++;
1758                 }
1759
1760                 g_strstrip(param);
1761
1762                 attribute = param;
1763                 value = strchr(attribute, '=');
1764                 if (value == NULL)
1765                         continue;
1766
1767                 value[0] = '\0';
1768                 value++;
1769                 while (value[0] != '\0' && value[0] == ' ')
1770                         value++;
1771
1772                 down_attr = g_utf8_strdown(attribute, -1);
1773                 orig_down_attr = down_attr;
1774         
1775                 len = down_attr ? strlen(down_attr):0;
1776                 if (len > 0 && down_attr[len - 1] == '*') {
1777                         gchar *srcpos, *dstpos, *endpos;
1778
1779                         convert = TRUE;
1780                         down_attr[len - 1] = '\0';
1781
1782                         srcpos = value;
1783                         dstpos = value;
1784                         endpos = value + strlen(value);
1785                         while (srcpos < endpos) {
1786                                 if (*srcpos != '%')
1787                                         *dstpos = *srcpos;
1788                                 else {
1789                                         guchar dstvalue;
1790
1791                                         if (!get_hex_value(&dstvalue, srcpos[1], srcpos[2]))
1792                                                 *dstpos = '?';
1793                                         else
1794                                                 *dstpos = dstvalue;
1795                                         srcpos += 2;
1796                                 }
1797                                 srcpos++;
1798                                 dstpos++;
1799                         }
1800                         *dstpos = '\0';
1801                         if (value[0] == '"')
1802                                 extract_quote(value, '"');
1803                 } else {
1804                         if (value[0] == '"')
1805                                 extract_quote(value, '"');
1806                         else if ((tmp = strchr(value, ' ')) != NULL)
1807                                 *tmp = '\0';
1808                 }
1809
1810                 if (down_attr) {
1811                         while (down_attr[0] == ' ')
1812                                 down_attr++;
1813                         while (down_attr[strlen(down_attr)-1] == ' ') 
1814                                 down_attr[strlen(down_attr)-1] = '\0';
1815                 } 
1816
1817                 while (value[0] != '\0' && value[0] == ' ')
1818                         value++;
1819                 while (value[strlen(value)-1] == ' ') 
1820                         value[strlen(value)-1] = '\0';
1821
1822                 if (down_attr && strrchr(down_attr, '*') != NULL) {
1823                         gchar *tmpattr;
1824
1825                         tmpattr = g_strdup(down_attr);
1826                         tmp = strrchr(tmpattr, '*');
1827                         tmp[0] = '\0';
1828
1829                         if ((tmp[1] == '0') && (tmp[2] == '\0') && 
1830                             (g_slist_find_custom(concatlist, down_attr, (GCompareFunc)g_strcmp0) == NULL))
1831                                 concatlist = g_slist_prepend(concatlist, g_strdup(tmpattr));
1832
1833                         if (convert && (g_slist_find_custom(convlist, tmpattr, (GCompareFunc)g_strcmp0) == NULL))
1834                                 convlist = g_slist_prepend(convlist, g_strdup(tmpattr));
1835
1836                         g_free(tmpattr);
1837                 } else if (convert) {
1838                         if (g_slist_find_custom(convlist, down_attr, (GCompareFunc)g_strcmp0) == NULL)
1839                                 convlist = g_slist_prepend(convlist, g_strdup(down_attr));
1840                 }
1841
1842                 if (g_hash_table_lookup(table, down_attr) == NULL)
1843                         g_hash_table_insert(table, g_strdup(down_attr), g_strdup(value));
1844                 g_free(orig_down_attr);
1845         }
1846
1847         for (cur = concatlist; cur != NULL; cur = g_slist_next(cur)) {
1848                 gchar *attribute, *attrwnum, *partvalue;
1849                 gint n = 0;
1850                 GString *value;
1851
1852                 attribute = (gchar *) cur->data;
1853                 value = g_string_sized_new(64);
1854
1855                 attrwnum = g_strdup_printf("%s*%d", attribute, n);
1856                 while ((partvalue = g_hash_table_lookup(table, attrwnum)) != NULL) {
1857                         g_string_append(value, partvalue);
1858
1859                         g_hash_table_remove(table, attrwnum);
1860                         g_free(attrwnum);
1861                         n++;
1862                         attrwnum = g_strdup_printf("%s*%d", attribute, n);
1863                 }
1864                 g_free(attrwnum);
1865
1866                 g_hash_table_insert(table, g_strdup(attribute), g_strdup(value->str));
1867                 g_string_free(value, TRUE);
1868         }
1869         slist_free_strings_full(concatlist);
1870
1871         for (cur = convlist; cur != NULL; cur = g_slist_next(cur)) {
1872                 gchar *attribute, *key, *value;
1873                 gchar *charset, *lang, *oldvalue, *newvalue;
1874
1875                 attribute = (gchar *) cur->data;
1876                 if (!g_hash_table_lookup_extended(
1877                         table, attribute, (gpointer *)(gchar *) &key, (gpointer *)(gchar *) &value))
1878                         continue;
1879
1880                 charset = value;
1881                 if (charset == NULL)
1882                         continue;
1883                 lang = strchr(charset, '\'');
1884                 if (lang == NULL)
1885                         continue;
1886                 lang[0] = '\0';
1887                 lang++;
1888                 oldvalue = strchr(lang, '\'');
1889                 if (oldvalue == NULL)
1890                         continue;
1891                 oldvalue[0] = '\0';
1892                 oldvalue++;
1893
1894                 newvalue = conv_codeset_strdup(oldvalue, charset, CS_UTF_8);
1895
1896                 g_hash_table_remove(table, attribute);
1897                 g_free(key);
1898                 g_free(value);
1899
1900                 g_hash_table_insert(table, g_strdup(attribute), newvalue);
1901         }
1902         slist_free_strings_full(convlist);
1903
1904         g_free(params);
1905 }       
1906
1907 static void procmime_parse_content_type(const gchar *content_type, MimeInfo *mimeinfo)
1908 {
1909         cm_return_if_fail(content_type != NULL);
1910         cm_return_if_fail(mimeinfo != NULL);
1911
1912         /* RFC 2045, page 13 says that the mime subtype is MANDATORY;
1913          * if it's not available we use the default Content-Type */
1914         if ((content_type[0] == '\0') || (strchr(content_type, '/') == NULL)) {
1915                 mimeinfo->type = MIMETYPE_TEXT;
1916                 mimeinfo->subtype = g_strdup("plain");
1917                 if (g_hash_table_lookup(mimeinfo->typeparameters,
1918                                        "charset") == NULL) {
1919                         g_hash_table_insert(mimeinfo->typeparameters,
1920                                     g_strdup("charset"),
1921                                     g_strdup(
1922                                         conv_get_locale_charset_str_no_utf8()));
1923                 }
1924         } else {
1925                 gchar *type, *subtype, *params;
1926
1927                 type = g_strdup(content_type);
1928                 subtype = strchr(type, '/') + 1;
1929                 *(subtype - 1) = '\0';
1930                 if ((params = strchr(subtype, ';')) != NULL) {
1931                         params[0] = '\0';
1932                         params++;
1933                 }
1934
1935                 mimeinfo->type = procmime_get_media_type(type);
1936                 mimeinfo->subtype = g_strstrip(g_strdup(subtype));
1937
1938                 /* Get mimeinfo->typeparameters */
1939                 if (params != NULL)
1940                         parse_parameters(params, mimeinfo->typeparameters);
1941
1942                 g_free(type);
1943         }
1944 }
1945
1946 static void procmime_parse_content_disposition(const gchar *content_disposition, MimeInfo *mimeinfo)
1947 {
1948         gchar *tmp, *params;
1949
1950         cm_return_if_fail(content_disposition != NULL);
1951         cm_return_if_fail(mimeinfo != NULL);
1952
1953         tmp = g_strdup(content_disposition);
1954         if ((params = strchr(tmp, ';')) != NULL) {
1955                 params[0] = '\0';
1956                 params++;
1957         }       
1958         g_strstrip(tmp);
1959
1960         if (!g_ascii_strcasecmp(tmp, "inline")) 
1961                 mimeinfo->disposition = DISPOSITIONTYPE_INLINE;
1962         else if (!g_ascii_strcasecmp(tmp, "attachment"))
1963                 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1964         else
1965                 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1966         
1967         if (params != NULL)
1968                 parse_parameters(params, mimeinfo->dispositionparameters);
1969
1970         g_free(tmp);
1971 }
1972
1973
1974 static void procmime_parse_content_encoding(const gchar *content_encoding, MimeInfo *mimeinfo)
1975 {
1976         struct EncodingTable *enc_table;
1977         
1978         for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1979                 if (g_ascii_strcasecmp(enc_table->str, content_encoding) == 0) {
1980                         mimeinfo->encoding_type = enc_table->enc_type;
1981                         return;
1982                 }
1983         }
1984         mimeinfo->encoding_type = ENC_UNKNOWN;
1985         return;
1986 }
1987
1988 static GSList *registered_parsers = NULL;
1989
1990 static MimeParser *procmime_get_mimeparser_for_type(MimeMediaType type, const gchar *sub_type)
1991 {
1992         GSList *cur;
1993         for (cur = registered_parsers; cur; cur = cur->next) {
1994                 MimeParser *parser = (MimeParser *)cur->data;
1995                 if (parser->type == type && !strcmp2(parser->sub_type, sub_type))
1996                         return parser;
1997         }
1998         return NULL;
1999 }
2000
2001 void procmime_mimeparser_register(MimeParser *parser)
2002 {
2003         if (!procmime_get_mimeparser_for_type(parser->type, parser->sub_type))
2004                 registered_parsers = g_slist_append(registered_parsers, parser);
2005 }
2006
2007
2008 void procmime_mimeparser_unregister(MimeParser *parser) 
2009 {
2010         registered_parsers = g_slist_remove(registered_parsers, parser);
2011 }
2012
2013 static gboolean procmime_mimeparser_parse(MimeParser *parser, MimeInfo *mimeinfo)
2014 {
2015         cm_return_val_if_fail(parser->parse != NULL, FALSE);
2016         return parser->parse(parser, mimeinfo); 
2017 }
2018
2019 static int procmime_parse_mimepart(MimeInfo *parent,
2020                              gchar *content_type,
2021                              gchar *content_encoding,
2022                              gchar *content_description,
2023                              gchar *content_id,
2024                              gchar *content_disposition,
2025                              gchar *content_location,
2026                              const gchar *original_msgid,
2027                              const gchar *disposition_notification_hdr,
2028                              const gchar *filename,
2029                              guint offset,
2030                              guint length,
2031                              gboolean short_scan)
2032 {
2033         MimeInfo *mimeinfo;
2034         MimeParser *parser = NULL;
2035         gboolean parsed = FALSE;
2036         int result = 0;
2037
2038         /* Create MimeInfo */
2039         mimeinfo = procmime_mimeinfo_new();
2040         mimeinfo->content = MIMECONTENT_FILE;
2041
2042         if (parent != NULL) {
2043                 if (g_node_depth(parent->node) > 32) {
2044                         /* 32 is an arbitrary value
2045                          * this avoids DOSsing ourselves 
2046                          * with enormous messages
2047                          */
2048                         procmime_mimeinfo_free_all(&mimeinfo);
2049                         return -1;                      
2050                 }
2051                 g_node_append(parent->node, mimeinfo->node);
2052         }
2053         mimeinfo->data.filename = g_strdup(filename);
2054         mimeinfo->offset = offset;
2055         mimeinfo->length = length;
2056
2057         if (content_type != NULL) {
2058                 g_strchomp(content_type);
2059                 procmime_parse_content_type(content_type, mimeinfo);
2060         } else {
2061                 mimeinfo->type = MIMETYPE_TEXT;
2062                 mimeinfo->subtype = g_strdup("plain");
2063                 if (g_hash_table_lookup(mimeinfo->typeparameters,
2064                                        "charset") == NULL) {
2065                         g_hash_table_insert(mimeinfo->typeparameters,
2066                                     g_strdup("charset"),
2067                                     g_strdup(
2068                                         conv_get_locale_charset_str_no_utf8()));
2069                 }
2070         }
2071
2072         if (content_encoding != NULL) {
2073                 g_strchomp(content_encoding);
2074                 procmime_parse_content_encoding(content_encoding, mimeinfo);
2075         } else {
2076                 mimeinfo->encoding_type = ENC_UNKNOWN;
2077         }
2078
2079         if (content_description != NULL)
2080                 mimeinfo->description = g_strdup(content_description);
2081         else
2082                 mimeinfo->description = NULL;
2083
2084         if (content_id != NULL)
2085                 mimeinfo->id = g_strdup(content_id);
2086         else
2087                 mimeinfo->id = NULL;
2088
2089         if (content_location != NULL)
2090                 mimeinfo->location = g_strdup(content_location);
2091         else
2092                 mimeinfo->location = NULL;
2093
2094         if (content_disposition != NULL) {
2095                 g_strchomp(content_disposition);
2096                 procmime_parse_content_disposition(content_disposition, mimeinfo);
2097         } else
2098                 mimeinfo->disposition = DISPOSITIONTYPE_UNKNOWN;
2099
2100         /* Call parser for mime type */
2101         if ((parser = procmime_get_mimeparser_for_type(mimeinfo->type, mimeinfo->subtype)) != NULL) {
2102                 parsed = procmime_mimeparser_parse(parser, mimeinfo);
2103         } 
2104         if (!parsed) {
2105                 switch (mimeinfo->type) {
2106                 case MIMETYPE_TEXT:
2107                         if (g_ascii_strcasecmp(mimeinfo->subtype, "plain") == 0 && short_scan) {
2108                                 return 1;
2109                         }
2110                         break;
2111
2112                 case MIMETYPE_MESSAGE:
2113                         if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
2114                                 procmime_parse_message_rfc822(mimeinfo, short_scan);
2115                         }
2116                         if (g_ascii_strcasecmp(mimeinfo->subtype, "disposition-notification") == 0) {
2117                                 procmime_parse_disposition_notification(mimeinfo, 
2118                                         original_msgid, disposition_notification_hdr, short_scan);
2119                         }
2120                         break;
2121                         
2122                 case MIMETYPE_MULTIPART:
2123                         procmime_parse_multipart(mimeinfo, short_scan);
2124                         break;
2125                 
2126                 case MIMETYPE_APPLICATION:
2127                         if (g_ascii_strcasecmp(mimeinfo->subtype, "octet-stream") == 0
2128                         && original_msgid && *original_msgid 
2129                         && disposition_notification_hdr && *disposition_notification_hdr) {
2130                                 procmime_parse_disposition_notification(mimeinfo, 
2131                                         original_msgid, disposition_notification_hdr, short_scan);
2132                         }
2133                         break;
2134                 default:
2135                         break;
2136                 }
2137         }
2138
2139         return result;
2140 }
2141
2142 static gchar *typenames[] = {
2143     "text",
2144     "image",
2145     "audio",
2146     "video",
2147     "application",
2148     "message",
2149     "multipart",
2150     "unknown",
2151 };
2152
2153 static gboolean output_func(GNode *node, gpointer data)
2154 {
2155         guint i, depth;
2156         MimeInfo *mimeinfo = (MimeInfo *) node->data;
2157
2158         depth = g_node_depth(node);
2159         for (i = 0; i < depth; i++)
2160                 g_print("    ");
2161         g_print("%s/%s (offset:%d length:%d encoding: %d)\n", typenames[mimeinfo->type], mimeinfo->subtype, mimeinfo->offset, mimeinfo->length, mimeinfo->encoding_type);
2162
2163         return FALSE;
2164 }
2165
2166 static void output_mime_structure(MimeInfo *mimeinfo, int indent)
2167 {
2168         g_node_traverse(mimeinfo->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1, output_func, NULL);
2169 }
2170
2171 static MimeInfo *procmime_scan_file_with_offset(const gchar *filename, int offset, gboolean short_scan)
2172 {
2173         MimeInfo *mimeinfo;
2174         GStatBuf buf;
2175
2176         if (g_stat(filename, &buf) < 0) {
2177                 FILE_OP_ERROR(filename, "stat");
2178                 return NULL;
2179         }
2180
2181         mimeinfo = procmime_mimeinfo_new();
2182         mimeinfo->content = MIMECONTENT_FILE;
2183         mimeinfo->encoding_type = ENC_UNKNOWN;
2184         mimeinfo->type = MIMETYPE_MESSAGE;
2185         mimeinfo->subtype = g_strdup("rfc822");
2186         mimeinfo->data.filename = g_strdup(filename);
2187         mimeinfo->offset = offset;
2188         mimeinfo->length = buf.st_size - offset;
2189
2190         procmime_parse_message_rfc822(mimeinfo, short_scan);
2191         if (debug_get_mode())
2192                 output_mime_structure(mimeinfo, 0);
2193
2194         return mimeinfo;
2195 }
2196
2197 static MimeInfo *procmime_scan_file_full(const gchar *filename, gboolean short_scan)
2198 {
2199         MimeInfo *mimeinfo;
2200
2201         cm_return_val_if_fail(filename != NULL, NULL);
2202
2203         mimeinfo = procmime_scan_file_with_offset(filename, 0, short_scan);
2204
2205         return mimeinfo;
2206 }
2207
2208 MimeInfo *procmime_scan_file(const gchar *filename)
2209 {
2210         return procmime_scan_file_full(filename, FALSE);
2211 }
2212
2213 static MimeInfo *procmime_scan_file_short(const gchar *filename)
2214 {
2215         return procmime_scan_file_full(filename, TRUE);
2216 }
2217
2218 static MimeInfo *procmime_scan_queue_file_full(const gchar *filename, gboolean short_scan)
2219 {
2220         FILE *fp;
2221         MimeInfo *mimeinfo;
2222         gchar buf[BUFFSIZE];
2223         gint offset = 0;
2224
2225         cm_return_val_if_fail(filename != NULL, NULL);
2226
2227         /* Open file */
2228         if ((fp = procmime_fopen(filename, "rb")) == NULL)
2229                 return NULL;
2230         /* Skip queue header */
2231         while (SC_FGETS(buf, sizeof(buf), fp) != NULL) {
2232                 /* new way */
2233                 if ((!strncmp(buf, "X-Claws-End-Special-Headers: 1",
2234                         strlen("X-Claws-End-Special-Headers:"))) ||
2235                    (!strncmp(buf, "X-Sylpheed-End-Special-Headers: 1",
2236                         strlen("X-Sylpheed-End-Special-Headers:"))))
2237                         break;
2238                 /* old way */
2239                 if (buf[0] == '\r' || buf[0] == '\n') break;
2240                 /* from other mailers */
2241                 if (!strncmp(buf, "Date: ", 6)
2242                 ||  !strncmp(buf, "To: ", 4)
2243                 ||  !strncmp(buf, "From: ", 6)
2244                 ||  !strncmp(buf, "Subject: ", 9)) {
2245                         rewind(fp);
2246                         break;
2247                 }
2248         }
2249         offset = ftell(fp);
2250         procmime_fclose(fp);
2251
2252         mimeinfo = procmime_scan_file_with_offset(filename, offset, short_scan);
2253
2254         return mimeinfo;
2255 }
2256
2257 MimeInfo *procmime_scan_queue_file(const gchar *filename)
2258 {
2259         return procmime_scan_queue_file_full(filename, FALSE);
2260 }
2261
2262 static MimeInfo *procmime_scan_queue_file_short(const gchar *filename)
2263 {
2264         return procmime_scan_queue_file_full(filename, TRUE);
2265 }
2266
2267 typedef enum {
2268     ENC_AS_TOKEN,
2269     ENC_AS_QUOTED_STRING,
2270     ENC_AS_EXTENDED,
2271     ENC_AS_ENCWORD
2272 } EncodeAs;
2273
2274 typedef struct _ParametersData {
2275         FILE *fp;
2276         guint len;
2277         gint error;
2278 } ParametersData;
2279
2280 static void write_parameters(gpointer key, gpointer value, gpointer user_data)
2281 {
2282         gchar *param = key;
2283         gchar *val = value, *valpos, *tmp;
2284         ParametersData *pdata = (ParametersData *)user_data;
2285         GString *buf = g_string_new("");
2286         gint len;
2287
2288         EncodeAs encas = ENC_AS_TOKEN;
2289
2290         for (valpos = val; *valpos != 0; valpos++) {
2291                 if (!IS_ASCII(*valpos)) {
2292                         encas = ENC_AS_ENCWORD;
2293                         break;
2294                 }
2295             
2296                 /* CTLs */
2297                 if (((*valpos >= 0) && (*valpos < 037)) || (*valpos == 0177)) {
2298                         encas = ENC_AS_QUOTED_STRING;
2299                         continue;
2300                 }
2301
2302                 /* tspecials + SPACE */
2303                 switch (*valpos) {
2304                 case ' ':
2305                 case '(': 
2306                 case ')':
2307                 case '<':
2308                 case '>':
2309                 case '@':
2310                 case ',':
2311                 case ';':
2312                 case ':':
2313                 case '\\':
2314                 case '"':
2315                 case '/':
2316                 case '[':
2317                 case ']':
2318                 case '?':
2319                 case '=':
2320                         encas = ENC_AS_QUOTED_STRING;
2321                         continue;
2322                 }
2323         }
2324         
2325         switch (encas) {
2326         case ENC_AS_TOKEN:
2327                 g_string_append_printf(buf, "%s=%s", param, val);
2328                 break;
2329
2330         case ENC_AS_QUOTED_STRING:
2331                 g_string_append_printf(buf, "%s=\"%s\"", param, val);
2332                 break;
2333
2334 #if 0 /* we don't use that for now */
2335         case ENC_AS_EXTENDED:
2336                 if (!g_utf8_validate(val, -1, NULL))
2337                         g_string_append_printf(buf, "%s*=%s''", param,
2338                                 conv_get_locale_charset_str());
2339                 else
2340                         g_string_append_printf(buf, "%s*=%s''", param,
2341                                 CS_INTERNAL);
2342                 for (valpos = val; *valpos != '\0'; valpos++) {
2343                         if (IS_ASCII(*valpos) && isalnum(*valpos)) {
2344                                 g_string_append_printf(buf, "%c", *valpos);
2345                         } else {
2346                                 gchar hexstr[3] = "XX";
2347                                 get_hex_str(hexstr, *valpos);
2348                                 g_string_append_printf(buf, "%%%s", hexstr);
2349                         }
2350                 }
2351                 break;
2352 #else
2353         case ENC_AS_EXTENDED:
2354                 debug_print("Unhandled ENC_AS_EXTENDED.");
2355                 break;
2356 #endif
2357         case ENC_AS_ENCWORD:
2358                 len = MAX(strlen(val)*6, 512);
2359                 tmp = g_malloc(len+1);
2360                 codeconv_set_strict(TRUE);
2361                 conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2362                         prefs_common.outgoing_charset);
2363                 codeconv_set_strict(FALSE);
2364                 if (!tmp || !*tmp) {
2365                         codeconv_set_strict(TRUE);
2366                         conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2367                                 conv_get_outgoing_charset_str());
2368                         codeconv_set_strict(FALSE);
2369                 }
2370                 if (!tmp || !*tmp) {
2371                         codeconv_set_strict(TRUE);
2372                         conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2373                                 CS_UTF_8);
2374                         codeconv_set_strict(FALSE);
2375                 }
2376                 if (!tmp || !*tmp) {
2377                         conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2378                                 CS_UTF_8);
2379                 }
2380                 g_string_append_printf(buf, "%s=\"%s\"", param, tmp);
2381                 g_free(tmp);
2382                 break;
2383
2384         }
2385         
2386         if (buf->str && strlen(buf->str)) {
2387                 tmp = strstr(buf->str, "\n");
2388                 if (tmp)
2389                         len = (tmp - buf->str);
2390                 else
2391                         len = strlen(buf->str);
2392                 if (pdata->len + len > 76) {
2393                         if (fprintf(pdata->fp, ";\n %s", buf->str) < 0)
2394                                 pdata->error = TRUE;
2395                         pdata->len = strlen(buf->str) + 1;
2396                 } else {
2397                         if (fprintf(pdata->fp, "; %s", buf->str) < 0)
2398                                 pdata->error = TRUE;
2399                         pdata->len += strlen(buf->str) + 2;
2400                 }
2401         }
2402         g_string_free(buf, TRUE);
2403 }
2404
2405 #define TRY(func) { \
2406         if (!(func)) { \
2407                 return -1; \
2408         } \
2409 }
2410
2411 int procmime_write_mime_header(MimeInfo *mimeinfo, FILE *fp)
2412 {
2413         struct TypeTable *type_table;
2414         ParametersData *pdata = g_new0(ParametersData, 1);
2415         debug_print("procmime_write_mime_header\n");
2416         
2417         pdata->fp = fp;
2418         pdata->error = FALSE;
2419         for (type_table = mime_type_table; type_table->str != NULL; type_table++)
2420                 if (mimeinfo->type == type_table->type) {
2421                         gchar *buf = g_strdup_printf(
2422                                 "Content-Type: %s/%s", type_table->str, mimeinfo->subtype);
2423                         if (fprintf(fp, "%s", buf) < 0) {
2424                                 g_free(buf);
2425                                 g_free(pdata);
2426                                 return -1;
2427                         }
2428                         pdata->len = strlen(buf);
2429                         g_free(buf);
2430                         break;
2431                 }
2432         g_hash_table_foreach(mimeinfo->typeparameters, write_parameters, pdata);
2433         if (pdata->error == TRUE) {
2434                 g_free(pdata);
2435                 return -1;
2436         }
2437         g_free(pdata);
2438
2439         TRY(fprintf(fp, "\n") >= 0);
2440
2441         if (mimeinfo->encoding_type != ENC_UNKNOWN)
2442                 TRY(fprintf(fp, "Content-Transfer-Encoding: %s\n", procmime_get_encoding_str(mimeinfo->encoding_type)) >= 0);
2443
2444         if (mimeinfo->description != NULL)
2445                 TRY(fprintf(fp, "Content-Description: %s\n", mimeinfo->description) >= 0);
2446
2447         if (mimeinfo->id != NULL)
2448                 TRY(fprintf(fp, "Content-ID: %s\n", mimeinfo->id) >= 0);
2449
2450         if (mimeinfo->location != NULL)
2451                 TRY(fprintf(fp, "Content-Location: %s\n", mimeinfo->location) >= 0);
2452
2453         if (mimeinfo->disposition != DISPOSITIONTYPE_UNKNOWN) {
2454                 ParametersData *pdata = g_new0(ParametersData, 1);
2455                 gchar *buf = NULL;
2456                 if (mimeinfo->disposition == DISPOSITIONTYPE_INLINE)
2457                         buf = g_strdup("Content-Disposition: inline");
2458                 else if (mimeinfo->disposition == DISPOSITIONTYPE_ATTACHMENT)
2459                         buf = g_strdup("Content-Disposition: attachment");
2460                 else
2461                         buf = g_strdup("Content-Disposition: unknown");
2462
2463                 if (fprintf(fp, "%s", buf) < 0) {
2464                         g_free(buf);
2465                         g_free(pdata);
2466                         return -1;
2467                 }
2468                 pdata->len = strlen(buf);
2469                 g_free(buf);
2470
2471                 pdata->fp = fp;
2472                 pdata->error = FALSE;
2473                 g_hash_table_foreach(mimeinfo->dispositionparameters, write_parameters, pdata);
2474                 if (pdata->error == TRUE) {
2475                         g_free(pdata);
2476                         return -1;
2477                 }
2478                 g_free(pdata);
2479                 TRY(fprintf(fp, "\n") >= 0);
2480         }
2481
2482         TRY(fprintf(fp, "\n") >= 0);
2483         
2484         return 0;
2485 }
2486
2487 static gint procmime_write_message_rfc822(MimeInfo *mimeinfo, FILE *fp)
2488 {
2489         FILE *infp;
2490         GNode *childnode;
2491         MimeInfo *child;
2492         gchar buf[BUFFSIZE];
2493         gboolean skip = FALSE;;
2494         size_t len;
2495
2496         debug_print("procmime_write_message_rfc822\n");
2497
2498         /* write header */
2499         switch (mimeinfo->content) {
2500         case MIMECONTENT_FILE:
2501                 if ((infp = procmime_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2502                         FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2503                         return -1;
2504                 }
2505                 if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
2506                         FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
2507                         procmime_fclose(infp);
2508                         return -1;
2509                 }
2510                 while (SC_FGETS(buf, sizeof(buf), infp) == buf) {
2511                         strcrchomp(buf);
2512                         if (buf[0] == '\n' && buf[1] == '\0')
2513                                 break;
2514                         if (skip && (buf[0] == ' ' || buf[0] == '\t'))
2515                                 continue;
2516                         if (g_ascii_strncasecmp(buf, "MIME-Version:", 13) == 0 ||
2517                             g_ascii_strncasecmp(buf, "Content-Type:", 13) == 0 ||
2518                             g_ascii_strncasecmp(buf, "Content-Transfer-Encoding:", 26) == 0 ||
2519                             g_ascii_strncasecmp(buf, "Content-Description:", 20) == 0 ||
2520                             g_ascii_strncasecmp(buf, "Content-ID:", 11) == 0 ||
2521                             g_ascii_strncasecmp(buf, "Content-Location:", 17) == 0 ||
2522                             g_ascii_strncasecmp(buf, "Content-Disposition:", 20) == 0) {
2523                                 skip = TRUE;
2524                                 continue;
2525                         }
2526                         len = strlen(buf);
2527                         if (SC_FWRITE(buf, sizeof(gchar), len, fp) < len) {
2528                                 g_warning("failed to dump %zd bytes from file", len);
2529                                 procmime_fclose(infp);
2530                                 return -1;
2531                         }
2532                         skip = FALSE;
2533                 }
2534                 procmime_fclose(infp);
2535                 break;
2536
2537         case MIMECONTENT_MEM:
2538                 len = strlen(mimeinfo->data.mem);
2539                 if (SC_FWRITE(mimeinfo->data.mem, sizeof(gchar), len, fp) < len) {
2540                         g_warning("failed to dump %zd bytes from mem", len);
2541                         return -1;
2542                 }
2543                 break;
2544
2545         default:
2546                 break;
2547         }
2548
2549         childnode = mimeinfo->node->children;
2550         if (childnode == NULL)
2551                 return -1;
2552
2553         child = (MimeInfo *) childnode->data;
2554         if (fprintf(fp, "MIME-Version: 1.0\n") < 0) {
2555                 g_warning("failed to write mime version");
2556                 return -1;
2557         }
2558         if (procmime_write_mime_header(child, fp) < 0)
2559                 return -1;
2560         return procmime_write_mimeinfo(child, fp);
2561 }
2562
2563 static gint procmime_write_multipart(MimeInfo *mimeinfo, FILE *fp)
2564 {
2565         FILE *infp;
2566         GNode *childnode;
2567         gchar *boundary, *str, *str2;
2568         gchar buf[BUFFSIZE];
2569         gboolean firstboundary;
2570         size_t len;
2571
2572         debug_print("procmime_write_multipart\n");
2573
2574         boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
2575
2576         switch (mimeinfo->content) {
2577         case MIMECONTENT_FILE:
2578                 if ((infp = procmime_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2579                         FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2580                         return -1;
2581                 }
2582                 if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
2583                         FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
2584                         procmime_fclose(infp);
2585                         return -1;
2586                 }
2587                 while (SC_FGETS(buf, sizeof(buf), infp) == buf) {
2588                         if (IS_BOUNDARY(buf, boundary, strlen(boundary)))
2589                                 break;
2590                         len = strlen(buf);
2591                         if (SC_FWRITE(buf, sizeof(gchar), len, fp) < len) {
2592                                 g_warning("failed to write %zd", len);
2593                                 procmime_fclose(infp);
2594                                 return -1;
2595                         }
2596                 }
2597                 procmime_fclose(infp);
2598                 break;
2599
2600         case MIMECONTENT_MEM:
2601                 str = g_strdup(mimeinfo->data.mem);
2602                 if (((str2 = strstr(str, boundary)) != NULL) && ((str2 - str) >= 2) &&
2603                     (*(str2 - 1) == '-') && (*(str2 - 2) == '-'))
2604                         *(str2 - 2) = '\0';
2605                 len = strlen(str);
2606                 if (SC_FWRITE(str, sizeof(gchar), len, fp) < len) {
2607                         g_warning("failed to write %zd from mem", len);
2608                         g_free(str);
2609                         return -1;
2610                 }
2611                 g_free(str);
2612                 break;
2613
2614         default:
2615                 break;
2616         }
2617
2618         childnode = mimeinfo->node->children;
2619         firstboundary = TRUE;
2620         while (childnode != NULL) {
2621                 MimeInfo *child = childnode->data;
2622
2623                 if (firstboundary)
2624                         firstboundary = FALSE;
2625                 else
2626                         TRY(fprintf(fp, "\n") >= 0);
2627                         
2628                 TRY(fprintf(fp, "--%s\n", boundary) >= 0);
2629
2630                 if (procmime_write_mime_header(child, fp) < 0)
2631                         return -1;
2632                 if (procmime_write_mimeinfo(child, fp) < 0)
2633                         return -1;
2634
2635                 childnode = g_node_next_sibling(childnode);
2636         }       
2637         TRY(fprintf(fp, "\n--%s--\n", boundary) >= 0);
2638
2639         return 0;
2640 }
2641
2642 gint procmime_write_mimeinfo(MimeInfo *mimeinfo, FILE *fp)
2643 {
2644         FILE *infp;
2645         size_t len;
2646         debug_print("procmime_write_mimeinfo\n");
2647
2648         if (G_NODE_IS_LEAF(mimeinfo->node)) {
2649                 switch (mimeinfo->content) {
2650                 case MIMECONTENT_FILE:
2651                         if ((infp = procmime_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2652                                 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2653                                 return -1;
2654                         }
2655                         copy_file_part_to_fp(infp, mimeinfo->offset, mimeinfo->length, fp);
2656                         procmime_fclose(infp);
2657                         return 0;
2658
2659                 case MIMECONTENT_MEM:
2660                         len = strlen(mimeinfo->data.mem);
2661                         if (SC_FWRITE(mimeinfo->data.mem, sizeof(gchar), len, fp) < len)
2662                                 return -1;
2663                         return 0;
2664
2665                 default:
2666                         return 0;
2667                 }
2668         } else {
2669                 /* Call writer for mime type */
2670                 switch (mimeinfo->type) {
2671                 case MIMETYPE_MESSAGE:
2672                         if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
2673                                 return procmime_write_message_rfc822(mimeinfo, fp);
2674                         }
2675                         break;
2676                         
2677                 case MIMETYPE_MULTIPART:
2678                         return procmime_write_multipart(mimeinfo, fp);
2679                         
2680                 default:
2681                         break;
2682                 }
2683
2684                 return -1;
2685         }
2686
2687         return 0;
2688 }
2689
2690 gchar *procmime_get_part_file_name(MimeInfo *mimeinfo)
2691 {
2692         gchar *base;
2693
2694         if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
2695                 base = g_strdup("mimetmp.html");
2696         else {
2697                 const gchar *basetmp;
2698                 gchar *basename;
2699
2700                 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
2701                 if (basetmp == NULL)
2702                         basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
2703                 if (basetmp == NULL)
2704                         basetmp = "mimetmp";
2705                 basename = g_path_get_basename(basetmp);
2706                 if (*basename == '\0') {
2707                         g_free(basename);
2708                         basename = g_strdup("mimetmp");
2709                 }
2710                 base = conv_filename_from_utf8(basename);
2711                 g_free(basename);
2712                 subst_for_shellsafe_filename(base);
2713         }
2714         
2715         return base;
2716 }
2717