update team data
[claws.git] / src / procmime.c
blobba6c94d3c1e1d432dfd683617d524840fd210de4
1 /*
2 * Claws Mail -- a GTK based, lightweight, and fast e-mail client
3 * Copyright (C) 1999-2021 the Claws Mail team and Hiroyuki Yamamoto
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.
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.
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/>.
19 #ifdef HAVE_CONFIG_H
20 # include "config.h"
21 #include "claws-features.h"
22 #endif
24 #include <stdio.h>
26 #include "defs.h"
28 #include <glib.h>
29 #include <glib/gi18n.h>
30 #include <string.h>
31 #if HAVE_LOCALE_H
32 # include <locale.h>
33 #endif
34 #include <ctype.h>
35 #include <sys/types.h>
36 #include <sys/stat.h>
37 #include <unistd.h>
38 #include <errno.h>
40 #include "procmime.h"
41 #include "procheader.h"
42 #include "quoted-printable.h"
43 #include "uuencode.h"
44 #include "unmime.h"
45 #include "html.h"
46 #include "enriched.h"
47 #include "codeconv.h"
48 #include "utils.h"
49 #include "prefs_common.h"
50 #include "prefs_gtk.h"
51 #include "alertpanel.h"
52 #include "timing.h"
53 #include "privacy.h"
54 #include "account.h"
55 #include "file-utils.h"
57 #ifdef G_OS_WIN32
58 #include "w32_reg.h"
59 #define REG_MIME_TYPE_VALUE "Content Type"
60 #endif
62 #ifndef G_OS_WIN32
63 static GHashTable *procmime_get_mime_type_table (void);
64 #endif
65 static MimeInfo *procmime_scan_file_short(const gchar *filename);
66 static MimeInfo *procmime_scan_queue_file_short(const gchar *filename);
67 static MimeInfo *procmime_scan_queue_file_full(const gchar *filename, gboolean short_scan);
69 MimeInfo *procmime_mimeinfo_new(void)
71 MimeInfo *mimeinfo;
73 mimeinfo = g_new0(MimeInfo, 1);
75 mimeinfo->content = MIMECONTENT_EMPTY;
76 mimeinfo->data.filename = NULL;
78 mimeinfo->type = MIMETYPE_UNKNOWN;
79 mimeinfo->encoding_type = ENC_UNKNOWN;
80 mimeinfo->typeparameters = g_hash_table_new(g_str_hash, g_str_equal);
82 mimeinfo->disposition = DISPOSITIONTYPE_UNKNOWN;
83 mimeinfo->dispositionparameters
84 = g_hash_table_new(g_str_hash, g_str_equal);
86 mimeinfo->node = g_node_new(mimeinfo);
88 return mimeinfo;
91 static gboolean procmime_mimeinfo_parameters_destroy(gpointer key, gpointer value, gpointer user_data)
93 g_free(key);
94 g_free(value);
96 return TRUE;
99 static gchar *forced_charset = NULL;
101 void procmime_force_charset(const gchar *str)
103 g_free(forced_charset);
104 forced_charset = NULL;
105 if (str)
106 forced_charset = g_strdup(str);
109 static EncodingType forced_encoding = 0;
111 void procmime_force_encoding(EncodingType encoding)
113 forced_encoding = encoding;
116 static gboolean free_func(GNode *node, gpointer data)
118 MimeInfo *mimeinfo = (MimeInfo *) node->data;
120 switch (mimeinfo->content) {
121 case MIMECONTENT_FILE:
122 if (mimeinfo->tmp)
123 claws_unlink(mimeinfo->data.filename);
124 g_free(mimeinfo->data.filename);
125 break;
127 case MIMECONTENT_MEM:
128 if (mimeinfo->tmp)
129 g_free(mimeinfo->data.mem);
130 default:
131 break;
134 g_free(mimeinfo->subtype);
135 g_free(mimeinfo->description);
136 g_free(mimeinfo->id);
137 g_free(mimeinfo->location);
139 g_hash_table_foreach_remove(mimeinfo->typeparameters,
140 procmime_mimeinfo_parameters_destroy, NULL);
141 g_hash_table_destroy(mimeinfo->typeparameters);
142 g_hash_table_foreach_remove(mimeinfo->dispositionparameters,
143 procmime_mimeinfo_parameters_destroy, NULL);
144 g_hash_table_destroy(mimeinfo->dispositionparameters);
146 if (mimeinfo->privacy)
147 privacy_free_privacydata(mimeinfo->privacy);
149 if (mimeinfo->sig_data)
150 privacy_free_signature_data(mimeinfo->sig_data);
152 g_free(mimeinfo);
154 return FALSE;
157 void procmime_mimeinfo_free_all(MimeInfo **mimeinfo_ptr)
159 MimeInfo *mimeinfo = *mimeinfo_ptr;
160 GNode *node;
162 if (!mimeinfo)
163 return;
165 node = mimeinfo->node;
166 g_node_traverse(node, G_IN_ORDER, G_TRAVERSE_ALL, -1, free_func, NULL);
168 g_node_destroy(node);
170 *mimeinfo_ptr = NULL;
173 MimeInfo *procmime_mimeinfo_parent(MimeInfo *mimeinfo)
175 cm_return_val_if_fail(mimeinfo != NULL, NULL);
176 cm_return_val_if_fail(mimeinfo->node != NULL, NULL);
178 if (mimeinfo->node->parent == NULL)
179 return NULL;
180 return (MimeInfo *) mimeinfo->node->parent->data;
183 MimeInfo *procmime_mimeinfo_next(MimeInfo *mimeinfo)
185 cm_return_val_if_fail(mimeinfo != NULL, NULL);
186 cm_return_val_if_fail(mimeinfo->node != NULL, NULL);
188 if (mimeinfo->node->children)
189 return (MimeInfo *) mimeinfo->node->children->data;
190 if (mimeinfo->node->next)
191 return (MimeInfo *) mimeinfo->node->next->data;
193 if (mimeinfo->node->parent == NULL)
194 return NULL;
196 while (mimeinfo->node->parent != NULL) {
197 mimeinfo = (MimeInfo *) mimeinfo->node->parent->data;
198 if (mimeinfo->node->next)
199 return (MimeInfo *) mimeinfo->node->next->data;
202 return NULL;
205 MimeInfo *procmime_scan_message(MsgInfo *msginfo)
207 gchar *filename;
208 MimeInfo *mimeinfo;
210 filename = procmsg_get_message_file_path(msginfo);
211 if (!filename || !is_file_exist(filename)) {
212 g_free(filename);
213 return NULL;
216 if (!folder_has_parent_of_type(msginfo->folder, F_QUEUE) &&
217 !folder_has_parent_of_type(msginfo->folder, F_DRAFT))
218 mimeinfo = procmime_scan_file(filename);
219 else
220 mimeinfo = procmime_scan_queue_file(filename);
221 g_free(filename);
223 return mimeinfo;
226 MimeInfo *procmime_scan_message_short(MsgInfo *msginfo)
228 gchar *filename;
229 MimeInfo *mimeinfo;
231 filename = procmsg_get_message_file_path(msginfo);
232 if (!filename || !is_file_exist(filename)) {
233 g_free(filename);
234 return NULL;
237 if (!folder_has_parent_of_type(msginfo->folder, F_QUEUE) &&
238 !folder_has_parent_of_type(msginfo->folder, F_DRAFT))
239 mimeinfo = procmime_scan_file_short(filename);
240 else
241 mimeinfo = procmime_scan_queue_file_short(filename);
242 g_free(filename);
244 return mimeinfo;
247 enum
249 H_CONTENT_TRANSFER_ENCODING = 0,
250 H_CONTENT_TYPE = 1,
251 H_CONTENT_DISPOSITION = 2,
252 H_CONTENT_DESCRIPTION = 3,
253 H_SUBJECT = 4
256 const gchar *procmime_mimeinfo_get_parameter(MimeInfo *mimeinfo, const gchar *name)
258 const gchar *value;
260 cm_return_val_if_fail(mimeinfo != NULL, NULL);
261 cm_return_val_if_fail(name != NULL, NULL);
263 value = g_hash_table_lookup(mimeinfo->dispositionparameters, name);
264 if (value == NULL)
265 value = g_hash_table_lookup(mimeinfo->typeparameters, name);
267 return value;
270 #define FLUSH_LASTLINE() { \
271 if (*lastline != '\0') { \
272 gint llen = 0; \
273 strretchomp(lastline); \
274 llen = strlen(lastline); \
275 if (lastline[llen-1] == ' ' && !account_sigsep_matchlist_str_found(lastline, "%s") && \
276 !(llen == 2 && lastline[1] == ' ' && strchr(prefs_common.quote_chars, lastline[0]))) { \
277 /* this is flowed */ \
278 if (delsp) \
279 lastline[llen-1] = '\0'; \
280 if (claws_fputs(lastline, outfp) == EOF) \
281 err = TRUE; \
282 } else { \
283 if (claws_fputs(lastline, outfp) == EOF) \
284 err = TRUE; \
285 if (claws_fputs("\n", outfp) == EOF) \
286 err = TRUE; \
289 strcpy(lastline, buf); \
292 gboolean procmime_decode_content(MimeInfo *mimeinfo)
294 gchar buf[BUFFSIZE];
295 gint readend;
296 gchar *tmpfilename;
297 FILE *outfp, *infp;
298 GStatBuf statbuf;
299 gboolean tmp_file = FALSE;
300 gboolean flowed = FALSE;
301 gboolean delsp = FALSE;
302 gboolean err = FALSE;
303 gint state = 0;
304 guint save = 0;
306 cm_return_val_if_fail(mimeinfo != NULL, FALSE);
308 EncodingType encoding = forced_encoding
309 ? forced_encoding
310 : mimeinfo->encoding_type;
311 gchar lastline[BUFFSIZE];
312 memset(lastline, 0, BUFFSIZE);
314 if (prefs_common.respect_flowed_format &&
315 mimeinfo->type == MIMETYPE_TEXT &&
316 !strcasecmp(mimeinfo->subtype, "plain")) {
317 if (procmime_mimeinfo_get_parameter(mimeinfo, "format") != NULL &&
318 !strcasecmp(procmime_mimeinfo_get_parameter(mimeinfo, "format"),"flowed"))
319 flowed = TRUE;
320 if (flowed &&
321 procmime_mimeinfo_get_parameter(mimeinfo, "delsp") != NULL &&
322 !strcasecmp(procmime_mimeinfo_get_parameter(mimeinfo, "delsp"),"yes"))
323 delsp = TRUE;
326 if (!flowed && (
327 encoding == ENC_UNKNOWN ||
328 encoding == ENC_BINARY ||
329 encoding == ENC_7BIT ||
330 encoding == ENC_8BIT
332 return TRUE;
334 if (mimeinfo->type == MIMETYPE_MULTIPART || mimeinfo->type == MIMETYPE_MESSAGE)
335 return TRUE;
337 if (mimeinfo->data.filename == NULL)
338 return FALSE;
340 infp = claws_fopen(mimeinfo->data.filename, "rb");
341 if (!infp) {
342 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
343 return FALSE;
345 if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
346 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
347 claws_fclose(infp);
348 return FALSE;
351 outfp = get_tmpfile_in_dir(get_mime_tmp_dir(), &tmpfilename);
352 if (!outfp) {
353 perror("tmpfile");
354 claws_fclose(infp);
355 g_free(tmpfilename);
356 return FALSE;
359 tmp_file = TRUE;
360 readend = mimeinfo->offset + mimeinfo->length;
362 account_sigsep_matchlist_create(); /* FLUSH_LASTLINE will use it */
364 *buf = '\0';
365 if (encoding == ENC_QUOTED_PRINTABLE) {
366 while ((ftell(infp) < readend) && (claws_fgets(buf, sizeof(buf), infp) != NULL)) {
367 gint len;
368 len = qp_decode_line(buf);
369 buf[len] = '\0';
370 if (!flowed) {
371 if (claws_fwrite(buf, 1, len, outfp) < len)
372 err = TRUE;
373 } else {
374 FLUSH_LASTLINE();
377 if (flowed)
378 FLUSH_LASTLINE();
379 } else if (encoding == ENC_BASE64) {
380 gchar outbuf[BUFFSIZE + 1];
381 gint len, inlen, inread;
382 gboolean got_error = FALSE;
383 gboolean uncanonicalize = FALSE;
384 FILE *tmpfp = NULL;
385 gboolean null_bytes = FALSE;
386 gboolean starting = TRUE;
388 if (mimeinfo->type == MIMETYPE_TEXT ||
389 mimeinfo->type == MIMETYPE_MESSAGE) {
390 uncanonicalize = TRUE;
391 tmpfp = my_tmpfile();
392 if (!tmpfp) {
393 perror("my_tmpfile");
394 if (tmp_file)
395 claws_fclose(outfp);
396 claws_fclose(infp);
397 g_free(tmpfilename);
398 return FALSE;
400 } else
401 tmpfp = outfp;
403 while ((inlen = MIN(readend - ftell(infp), sizeof(buf))) > 0 && !err) {
404 inread = claws_fread(buf, 1, inlen, infp);
405 memset(outbuf, 0, sizeof(buf));
406 len = g_base64_decode_step(buf, inlen, outbuf, &state, &save);
407 if (uncanonicalize == TRUE && strlen(outbuf) < len && starting) {
408 uncanonicalize = FALSE;
409 null_bytes = TRUE;
411 starting = FALSE;
412 if (((inread != inlen) || len < 0) && !got_error) {
413 g_warning("bad BASE64 content");
414 if (claws_fwrite(_("[Error decoding BASE64]\n"),
415 sizeof(gchar),
416 strlen(_("[Error decoding BASE64]\n")),
417 tmpfp) < strlen(_("[Error decoding BASE64]\n")))
418 g_warning("error decoding BASE64");
419 got_error = TRUE;
420 continue;
421 } else if (len >= 0) {
422 /* print out the error message only once
423 * per block */
424 if (null_bytes) {
425 /* we won't uncanonicalize, output to outfp directly */
426 if (claws_fwrite(outbuf, sizeof(gchar), len, outfp) < len)
427 err = TRUE;
428 } else {
429 if (claws_fwrite(outbuf, sizeof(gchar), len, tmpfp) < len)
430 err = TRUE;
432 got_error = FALSE;
436 if (uncanonicalize) {
437 rewind(tmpfp);
438 while (claws_fgets(buf, sizeof(buf), tmpfp) != NULL) {
439 strcrchomp(buf);
440 if (claws_fputs(buf, outfp) == EOF)
441 err = TRUE;
444 if (tmpfp != outfp) {
445 ftruncate(fileno(tmpfp), ftell(tmpfp));
446 claws_fclose(tmpfp);
448 } else if (encoding == ENC_X_UUENCODE) {
449 gchar outbuf[BUFFSIZE];
450 gint len;
451 gboolean flag = FALSE;
453 while ((ftell(infp) < readend) && (claws_fgets(buf, sizeof(buf), infp) != NULL)) {
454 if (!flag && strncmp(buf,"begin ", 6)) continue;
456 if (flag) {
457 len = fromuutobits(outbuf, buf);
458 if (len <= 0) {
459 if (len < 0)
460 g_warning("bad UUENCODE content (%d)", len);
461 break;
463 if (claws_fwrite(outbuf, sizeof(gchar), len, outfp) < len)
464 err = TRUE;
465 } else
466 flag = TRUE;
468 } else {
469 while ((ftell(infp) < readend) && (claws_fgets(buf, sizeof(buf), infp) != NULL)) {
470 if (!flowed) {
471 if (claws_fputs(buf, outfp) == EOF)
472 err = TRUE;
473 } else {
474 FLUSH_LASTLINE();
477 if (flowed)
478 FLUSH_LASTLINE();
479 if (err == TRUE)
480 g_warning("write error");
483 ftruncate(fileno(outfp), ftell(outfp));
484 claws_fclose(outfp);
485 claws_fclose(infp);
487 account_sigsep_matchlist_delete();
489 if (err == TRUE) {
490 g_free(tmpfilename);
491 return FALSE;
494 if (g_stat(tmpfilename, &statbuf) < 0) {
495 FILE_OP_ERROR(tmpfilename, "stat");
496 g_free(tmpfilename);
497 return FALSE;
500 if (mimeinfo->tmp)
501 claws_unlink(mimeinfo->data.filename);
502 g_free(mimeinfo->data.filename);
503 mimeinfo->data.filename = tmpfilename;
504 mimeinfo->tmp = TRUE;
505 mimeinfo->offset = 0;
506 mimeinfo->length = statbuf.st_size;
507 mimeinfo->encoding_type = ENC_BINARY;
509 return TRUE;
512 #define B64_LINE_SIZE 57
513 #define B64_BUFFSIZE 77
515 gboolean procmime_encode_content(MimeInfo *mimeinfo, EncodingType encoding)
517 FILE *infp = NULL, *outfp;
518 gint len;
519 gchar *tmpfilename;
520 GStatBuf statbuf;
521 gboolean err = FALSE;
523 if (mimeinfo->content == MIMECONTENT_EMPTY)
524 return TRUE;
526 if (mimeinfo->encoding_type != ENC_UNKNOWN &&
527 mimeinfo->encoding_type != ENC_BINARY &&
528 mimeinfo->encoding_type != ENC_7BIT &&
529 mimeinfo->encoding_type != ENC_8BIT)
530 if(!procmime_decode_content(mimeinfo))
531 return FALSE;
533 outfp = get_tmpfile_in_dir(get_mime_tmp_dir(), &tmpfilename);
534 if (!outfp) {
535 perror("tmpfile");
536 g_free(tmpfilename);
537 return FALSE;
540 if (mimeinfo->content == MIMECONTENT_FILE && mimeinfo->data.filename) {
541 if ((infp = claws_fopen(mimeinfo->data.filename, "rb")) == NULL) {
542 g_warning("can't open file %s", mimeinfo->data.filename);
543 g_free(tmpfilename);
544 claws_fclose(outfp);
545 return FALSE;
547 } else if (mimeinfo->content == MIMECONTENT_MEM) {
548 infp = str_open_as_stream(mimeinfo->data.mem);
549 if (infp == NULL) {
550 g_free(tmpfilename);
551 claws_fclose(outfp);
552 return FALSE;
554 } else {
555 g_free(tmpfilename);
556 claws_fclose(outfp);
557 g_warning("unknown mimeinfo");
558 return FALSE;
561 if (encoding == ENC_BASE64) {
562 gchar inbuf[B64_LINE_SIZE], *out;
563 FILE *tmp_fp = infp;
564 gchar *tmp_file = NULL;
566 if (mimeinfo->type == MIMETYPE_TEXT ||
567 mimeinfo->type == MIMETYPE_MESSAGE) {
568 if (mimeinfo->content == MIMECONTENT_FILE) {
569 tmp_file = get_tmp_file();
570 if (canonicalize_file(mimeinfo->data.filename, tmp_file) < 0) {
571 g_free(tmp_file);
572 g_free(tmpfilename);
573 claws_fclose(infp);
574 claws_fclose(outfp);
575 return FALSE;
577 if ((tmp_fp = claws_fopen(tmp_file, "rb")) == NULL) {
578 FILE_OP_ERROR(tmp_file, "claws_fopen");
579 claws_unlink(tmp_file);
580 g_free(tmp_file);
581 g_free(tmpfilename);
582 claws_fclose(infp);
583 claws_fclose(outfp);
584 return FALSE;
586 } else {
587 gchar *out = canonicalize_str(mimeinfo->data.mem);
588 claws_fclose(infp);
589 infp = str_open_as_stream(out);
590 tmp_fp = infp;
591 g_free(out);
592 if (infp == NULL) {
593 g_free(tmpfilename);
594 claws_fclose(outfp);
595 return FALSE;
600 while ((len = claws_fread(inbuf, sizeof(gchar),
601 B64_LINE_SIZE, tmp_fp))
602 == B64_LINE_SIZE) {
603 out = g_base64_encode(inbuf, B64_LINE_SIZE);
604 if (claws_fputs(out, outfp) == EOF)
605 err = TRUE;
606 g_free(out);
607 if (claws_fputc('\n', outfp) == EOF)
608 err = TRUE;
610 if (len > 0 && claws_feof(tmp_fp)) {
611 out = g_base64_encode(inbuf, len);
612 if (claws_fputs(out, outfp) == EOF)
613 err = TRUE;
614 g_free(out);
615 if (claws_fputc('\n', outfp) == EOF)
616 err = TRUE;
619 if (tmp_file) {
620 claws_fclose(tmp_fp);
621 claws_unlink(tmp_file);
622 g_free(tmp_file);
624 } else if (encoding == ENC_QUOTED_PRINTABLE) {
625 gchar inbuf[BUFFSIZE], outbuf[BUFFSIZE * 4];
627 while (claws_fgets(inbuf, sizeof(inbuf), infp) != NULL) {
628 qp_encode_line(outbuf, inbuf);
630 if (!strncmp("From ", outbuf, sizeof("From ")-1)) {
631 gchar *tmpbuf = outbuf;
633 tmpbuf += sizeof("From ")-1;
635 if (claws_fputs("=46rom ", outfp) == EOF)
636 err = TRUE;
637 if (claws_fputs(tmpbuf, outfp) == EOF)
638 err = TRUE;
639 } else {
640 if (claws_fputs(outbuf, outfp) == EOF)
641 err = TRUE;
644 } else {
645 gchar buf[BUFFSIZE];
647 while (claws_fgets(buf, sizeof(buf), infp) != NULL) {
648 strcrchomp(buf);
649 if (claws_fputs(buf, outfp) == EOF)
650 err = TRUE;
654 claws_fclose(outfp);
655 claws_fclose(infp);
657 if (err == TRUE) {
658 g_free(tmpfilename);
659 return FALSE;
662 if (mimeinfo->content == MIMECONTENT_FILE) {
663 if (mimeinfo->tmp && (mimeinfo->data.filename != NULL))
664 claws_unlink(mimeinfo->data.filename);
665 g_free(mimeinfo->data.filename);
666 } else if (mimeinfo->content == MIMECONTENT_MEM) {
667 if (mimeinfo->tmp && (mimeinfo->data.mem != NULL))
668 g_free(mimeinfo->data.mem);
671 if (g_stat(tmpfilename, &statbuf) < 0) {
672 FILE_OP_ERROR(tmpfilename, "stat");
673 g_free(tmpfilename);
674 return FALSE;
676 mimeinfo->content = MIMECONTENT_FILE;
677 mimeinfo->data.filename = tmpfilename;
678 mimeinfo->tmp = TRUE;
679 mimeinfo->offset = 0;
680 mimeinfo->length = statbuf.st_size;
681 mimeinfo->encoding_type = encoding;
683 return TRUE;
686 static gint procmime_get_part_to_stream(FILE *outfp, MimeInfo *mimeinfo)
688 FILE *infp;
689 gchar buf[BUFFSIZE];
690 gint restlength, readlength;
691 gint saved_errno = 0;
693 cm_return_val_if_fail(outfp != NULL, -1);
694 cm_return_val_if_fail(mimeinfo != NULL, -1);
696 if (mimeinfo->encoding_type != ENC_BINARY && !procmime_decode_content(mimeinfo))
697 return -EINVAL;
699 if ((infp = claws_fopen(mimeinfo->data.filename, "rb")) == NULL) {
700 saved_errno = errno;
701 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
702 return -(saved_errno);
704 if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
705 saved_errno = errno;
706 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
707 claws_fclose(infp);
708 return -(saved_errno);
711 restlength = mimeinfo->length;
713 while ((restlength > 0) && ((readlength = claws_fread(buf, 1, restlength > BUFFSIZE ? BUFFSIZE : restlength, infp)) > 0)) {
714 if (claws_fwrite(buf, 1, readlength, outfp) != readlength) {
715 saved_errno = errno;
716 claws_fclose(infp);
717 return -(saved_errno);
719 restlength -= readlength;
722 claws_fclose(infp);
723 rewind(outfp);
725 return 0;
728 gint procmime_get_part(const gchar *outfile, MimeInfo *mimeinfo)
730 FILE *outfp;
731 gint result;
732 gint saved_errno = 0;
734 cm_return_val_if_fail(outfile != NULL, -1);
736 if ((outfp = claws_fopen(outfile, "wb")) == NULL) {
737 saved_errno = errno;
738 FILE_OP_ERROR(outfile, "claws_fopen");
739 return -(saved_errno);
742 if (change_file_mode_rw(outfp, outfile) < 0) {
743 FILE_OP_ERROR(outfile, "chmod");
744 g_warning("can't change file mode: %s", outfile);
747 result = procmime_get_part_to_stream(outfp, mimeinfo);
749 if (claws_fclose(outfp) == EOF) {
750 saved_errno = errno;
751 FILE_OP_ERROR(outfile, "claws_fclose");
752 if (claws_unlink(outfile) < 0)
753 FILE_OP_ERROR(outfile, "claws_unlink");
754 return -(saved_errno);
757 return result;
760 gboolean procmime_scan_text_content(MimeInfo *mimeinfo,
761 gboolean (*scan_callback)(const gchar *str, gpointer cb_data),
762 gpointer cb_data)
764 FILE *tmpfp;
765 const gchar *src_codeset;
766 gboolean conv_fail = FALSE;
767 gchar buf[BUFFSIZE];
768 gchar *str;
769 gboolean scan_ret = FALSE;
770 gchar *tmpfile = NULL;
771 int r;
773 cm_return_val_if_fail(mimeinfo != NULL, TRUE);
774 cm_return_val_if_fail(scan_callback != NULL, TRUE);
776 if (!procmime_decode_content(mimeinfo))
777 return TRUE;
779 #if HAVE_FMEMOPEN
780 tmpfp = fmemopen(NULL, mimeinfo->length * 2, "w+");
781 #else
782 tmpfile = procmime_get_tmp_file_name(mimeinfo);
783 if (tmpfile == NULL) {
784 g_warning("no filename");
785 return TRUE;
788 tmpfp = claws_fopen(tmpfile, "w+");
789 #endif
791 if (tmpfp == NULL) {
792 g_free(tmpfile);
793 FILE_OP_ERROR(tmpfile, "open");
794 return TRUE;
797 if ((r = procmime_get_part_to_stream(tmpfp, mimeinfo)) < 0) {
798 g_warning("procmime_get_part_to_stream error %d", r);
799 g_free(tmpfile);
800 return TRUE;
803 src_codeset = forced_charset
804 ? forced_charset :
805 procmime_mimeinfo_get_parameter(mimeinfo, "charset");
807 /* use supersets transparently when possible */
808 if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_ISO_8859_1))
809 src_codeset = CS_WINDOWS_1252;
810 else if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_X_GBK))
811 src_codeset = CS_GB18030;
812 else if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_GBK))
813 src_codeset = CS_GB18030;
814 else if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_GB2312))
815 src_codeset = CS_GB18030;
816 else if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_X_VIET_VPS))
817 src_codeset = CS_WINDOWS_874;
819 if (mimeinfo->type == MIMETYPE_TEXT && !g_ascii_strcasecmp(mimeinfo->subtype, "html")) {
820 SC_HTMLParser *parser;
821 CodeConverter *conv;
823 conv = conv_code_converter_new(src_codeset);
824 parser = sc_html_parser_new(tmpfp, conv);
825 while ((str = sc_html_parse(parser)) != NULL) {
826 if ((scan_ret = scan_callback(str, cb_data)) == TRUE)
827 break;
829 sc_html_parser_destroy(parser);
830 conv_code_converter_destroy(conv);
831 } else if (mimeinfo->type == MIMETYPE_TEXT && !g_ascii_strcasecmp(mimeinfo->subtype, "enriched")) {
832 ERTFParser *parser;
833 CodeConverter *conv;
835 conv = conv_code_converter_new(src_codeset);
836 parser = ertf_parser_new(tmpfp, conv);
837 while ((str = ertf_parse(parser)) != NULL) {
838 if ((scan_ret = scan_callback(str, cb_data)) == TRUE)
839 break;
841 ertf_parser_destroy(parser);
842 conv_code_converter_destroy(conv);
843 } else if (mimeinfo->type == MIMETYPE_TEXT && mimeinfo->disposition != DISPOSITIONTYPE_ATTACHMENT) {
844 while (claws_fgets(buf, sizeof(buf), tmpfp) != NULL) {
845 str = conv_codeset_strdup(buf, src_codeset, CS_UTF_8);
846 if (str) {
847 if ((scan_ret = scan_callback(str, cb_data)) == TRUE) {
848 g_free(str);
849 break;
851 g_free(str);
852 } else {
853 conv_fail = TRUE;
854 if ((scan_ret = scan_callback(buf, cb_data)) == TRUE)
855 break;
860 if (conv_fail)
861 g_warning("procmime_get_text_content(): code conversion failed");
863 claws_fclose(tmpfp);
865 #if !HAVE_FMEMOPEN
866 claws_unlink(tmpfile);
867 g_free(tmpfile);
868 #endif
870 return scan_ret;
873 static gboolean scan_fputs_cb(const gchar *str, gpointer fp)
875 if (claws_fputs(str, (FILE *)fp) == EOF)
876 return TRUE;
878 return FALSE;
881 FILE *procmime_get_text_content(MimeInfo *mimeinfo)
883 FILE *outfp;
884 gboolean err;
886 if ((outfp = my_tmpfile()) == NULL) {
887 perror("my_tmpfile");
888 return NULL;
891 err = procmime_scan_text_content(mimeinfo, scan_fputs_cb, outfp);
893 ftruncate(fileno(outfp), ftell(outfp));
894 rewind(outfp);
895 if (err == TRUE) {
896 claws_fclose(outfp);
897 return NULL;
899 return outfp;
903 FILE *procmime_get_binary_content(MimeInfo *mimeinfo)
905 FILE *outfp;
906 #if !HAVE_FMEMOPEN
907 gchar *tmpfile = NULL;
908 #endif
910 cm_return_val_if_fail(mimeinfo != NULL, NULL);
912 if (!procmime_decode_content(mimeinfo))
913 return NULL;
915 #if HAVE_FMEMOPEN
916 outfp = fmemopen(NULL, mimeinfo->length * 2, "w+");
917 #else
918 tmpfile = procmime_get_tmp_file_name(mimeinfo);
919 if (tmpfile == NULL) {
920 g_warning("no filename");
921 return NULL;
924 outfp = claws_fopen(tmpfile, "w+");
926 if (tmpfile != NULL) {
927 g_unlink(tmpfile);
928 g_free(tmpfile);
930 #endif
932 if (procmime_get_part_to_stream(outfp, mimeinfo) < 0) {
933 return NULL;
935 ftruncate(fileno(outfp), ftell(outfp));
936 return outfp;
939 /* search the first text part of (multipart) MIME message,
940 decode, convert it and output to outfp. */
941 FILE *procmime_get_first_text_content(MsgInfo *msginfo)
943 FILE *outfp = NULL;
944 MimeInfo *mimeinfo, *partinfo;
945 gboolean empty_ok = FALSE, short_scan = TRUE;
947 cm_return_val_if_fail(msginfo != NULL, NULL);
949 /* first we try to short-scan (for speed), refusing empty parts */
950 scan_again:
951 if (short_scan)
952 mimeinfo = procmime_scan_message_short(msginfo);
953 else
954 mimeinfo = procmime_scan_message(msginfo);
955 if (!mimeinfo) return NULL;
957 partinfo = mimeinfo;
958 while (partinfo && (partinfo->type != MIMETYPE_TEXT ||
959 (partinfo->length == 0 && !empty_ok))) {
960 partinfo = procmime_mimeinfo_next(partinfo);
962 if (partinfo)
963 outfp = procmime_get_text_content(partinfo);
964 else if (!empty_ok && short_scan) {
965 /* if short scan didn't find a non-empty part, rescan
966 * fully for non-empty parts
968 short_scan = FALSE;
969 procmime_mimeinfo_free_all(&mimeinfo);
970 goto scan_again;
971 } else if (!empty_ok && !short_scan) {
972 /* if full scan didn't find a non-empty part, rescan
973 * accepting empty parts
975 empty_ok = TRUE;
976 procmime_mimeinfo_free_all(&mimeinfo);
977 goto scan_again;
979 procmime_mimeinfo_free_all(&mimeinfo);
981 return outfp;
985 static gboolean find_encrypted_func(GNode *node, gpointer data)
987 MimeInfo *mimeinfo = (MimeInfo *) node->data;
988 MimeInfo **encinfo = (MimeInfo **) data;
990 if (privacy_mimeinfo_is_encrypted(mimeinfo)) {
991 *encinfo = mimeinfo;
992 return TRUE;
995 return FALSE;
998 static MimeInfo *find_encrypted_part(MimeInfo *rootinfo)
1000 MimeInfo *encinfo = NULL;
1002 g_node_traverse(rootinfo->node, G_IN_ORDER, G_TRAVERSE_ALL, -1,
1003 find_encrypted_func, &encinfo);
1005 return encinfo;
1008 /* search the first encrypted text part of (multipart) MIME message,
1009 decode, convert it and output to outfp. */
1010 FILE *procmime_get_first_encrypted_text_content(MsgInfo *msginfo)
1012 FILE *outfp = NULL;
1013 MimeInfo *mimeinfo, *partinfo, *encinfo;
1015 cm_return_val_if_fail(msginfo != NULL, NULL);
1017 mimeinfo = procmime_scan_message(msginfo);
1018 if (!mimeinfo) {
1019 return NULL;
1022 partinfo = mimeinfo;
1023 if ((encinfo = find_encrypted_part(partinfo)) != NULL) {
1024 debug_print("decrypting message part\n");
1025 if (privacy_mimeinfo_decrypt(encinfo) < 0) {
1026 alertpanel_error(_("Couldn't decrypt: %s"),
1027 privacy_get_error());
1028 return NULL;
1031 partinfo = mimeinfo;
1032 while (partinfo && partinfo->type != MIMETYPE_TEXT) {
1033 partinfo = procmime_mimeinfo_next(partinfo);
1034 if (privacy_mimeinfo_is_signed(partinfo))
1035 procmsg_msginfo_set_flags(msginfo, 0, MSG_SIGNED);
1038 if (partinfo)
1039 outfp = procmime_get_text_content(partinfo);
1041 procmime_mimeinfo_free_all(&mimeinfo);
1043 return outfp;
1046 gboolean procmime_msginfo_is_encrypted(MsgInfo *msginfo)
1048 MimeInfo *mimeinfo, *partinfo;
1049 gboolean result = FALSE;
1051 cm_return_val_if_fail(msginfo != NULL, FALSE);
1053 mimeinfo = procmime_scan_message(msginfo);
1054 if (!mimeinfo) {
1055 return FALSE;
1058 partinfo = mimeinfo;
1059 result = (find_encrypted_part(partinfo) != NULL);
1060 procmime_mimeinfo_free_all(&mimeinfo);
1062 return result;
1065 gchar *procmime_get_tmp_file_name(MimeInfo *mimeinfo)
1067 static guint32 id = 0;
1068 gchar *base;
1069 gchar *filename;
1070 gchar f_prefix[10];
1072 cm_return_val_if_fail(mimeinfo != NULL, NULL);
1074 g_snprintf(f_prefix, sizeof(f_prefix), "%08x.", id++);
1076 if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
1077 base = g_strdup("mimetmp.html");
1078 else {
1079 const gchar *basetmp1;
1080 gchar *basetmp2;
1082 basetmp1 = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
1083 if (basetmp1 == NULL)
1084 basetmp1 = procmime_mimeinfo_get_parameter(mimeinfo, "name");
1085 if (basetmp1 == NULL)
1086 basetmp1 = "mimetmp";
1087 basetmp2 = g_path_get_basename(basetmp1);
1088 if (*basetmp2 == '\0') {
1089 g_free(basetmp2);
1090 basetmp2 = g_strdup("mimetmp");
1092 base = conv_filename_from_utf8(basetmp2);
1093 g_free(basetmp2);
1094 subst_for_shellsafe_filename(base);
1097 filename = g_strconcat(get_mime_tmp_dir(), G_DIR_SEPARATOR_S,
1098 f_prefix, base, NULL);
1100 g_free(base);
1102 return filename;
1105 static GList *mime_type_list = NULL;
1107 gchar *procmime_get_mime_type(const gchar *filename)
1109 const gchar *p;
1110 gchar *ext = NULL;
1111 gchar *base;
1112 gchar *str;
1113 #ifndef G_OS_WIN32
1114 static GHashTable *mime_type_table = NULL;
1115 MimeType *mime_type;
1117 if (!mime_type_table) {
1118 mime_type_table = procmime_get_mime_type_table();
1119 if (!mime_type_table) return NULL;
1121 #endif
1123 if (filename == NULL)
1124 return NULL;
1126 base = g_path_get_basename(filename);
1127 if ((p = strrchr(base, '.')) != NULL)
1128 #ifndef G_OS_WIN32
1129 ext = g_utf8_strdown(p + 1, -1);
1130 #else
1131 ext = g_utf8_strdown(p, -1);
1132 #endif
1133 else
1134 ext = g_utf8_strdown(base, -1);
1135 g_free(base);
1137 #ifndef G_OS_WIN32
1138 mime_type = g_hash_table_lookup(mime_type_table, ext);
1140 if (mime_type) {
1141 str = g_strconcat(mime_type->type, "/", mime_type->sub_type,
1142 NULL);
1143 debug_print("got type %s for %s\n", str, ext);
1144 g_free(ext);
1145 return str;
1147 g_free(ext);
1148 return NULL;
1149 #else
1150 str = read_w32_registry_string(HKEY_CLASSES_ROOT, ext, REG_MIME_TYPE_VALUE);
1151 debug_print("got type %s for %s\n", str, ext);
1152 g_free(ext);
1153 return str;
1154 #endif
1157 #ifndef G_OS_WIN32
1158 static guint procmime_str_hash(gconstpointer gptr)
1160 guint hash_result = 0;
1161 const char *str;
1163 for (str = gptr; str && *str; str++) {
1164 if (isupper(*str)) hash_result += (*str + ' ');
1165 else hash_result += *str;
1168 return hash_result;
1171 static gint procmime_str_equal(gconstpointer gptr1, gconstpointer gptr2)
1173 const char *str1 = gptr1;
1174 const char *str2 = gptr2;
1176 return !g_utf8_collate(str1, str2);
1179 static GHashTable *procmime_get_mime_type_table(void)
1181 GHashTable *table = NULL;
1182 GList *cur;
1183 MimeType *mime_type;
1184 gchar **exts;
1186 if (!mime_type_list) {
1187 mime_type_list = procmime_get_mime_type_list();
1188 if (!mime_type_list) return NULL;
1191 table = g_hash_table_new(procmime_str_hash, procmime_str_equal);
1193 for (cur = mime_type_list; cur != NULL; cur = cur->next) {
1194 gint i;
1195 gchar *key;
1197 mime_type = (MimeType *)cur->data;
1199 if (!mime_type->extension) continue;
1201 exts = g_strsplit(mime_type->extension, " ", 16);
1202 for (i = 0; exts[i] != NULL; i++) {
1203 /* Don't overwrite previously inserted extension */
1204 if (!g_hash_table_lookup(table, exts[i])) {
1205 key = g_strdup(exts[i]);
1206 g_hash_table_insert(table, key, mime_type);
1209 g_strfreev(exts);
1212 return table;
1214 #endif
1216 GList *procmime_get_mime_type_list(void)
1218 GList *list = NULL;
1219 FILE *fp;
1220 gchar buf[BUFFSIZE];
1221 gchar *p;
1222 gchar *delim;
1223 MimeType *mime_type;
1224 gboolean fp_is_glob_file = TRUE;
1226 if (mime_type_list)
1227 return mime_type_list;
1229 #if defined(__NetBSD__) || defined(__OpenBSD__) || defined(__FreeBSD__)
1230 if ((fp = claws_fopen(DATAROOTDIR "/mime/globs", "rb")) == NULL)
1231 #else
1232 if ((fp = claws_fopen("/usr/share/mime/globs", "rb")) == NULL)
1233 #endif
1235 fp_is_glob_file = FALSE;
1236 if ((fp = claws_fopen("/etc/mime.types", "rb")) == NULL) {
1237 if ((fp = claws_fopen(SYSCONFDIR "/mime.types", "rb"))
1238 == NULL) {
1239 FILE_OP_ERROR(SYSCONFDIR "/mime.types",
1240 "claws_fopen");
1241 return NULL;
1246 while (claws_fgets(buf, sizeof(buf), fp) != NULL) {
1247 p = strchr(buf, '#');
1248 if (p) *p = '\0';
1249 g_strstrip(buf);
1251 p = buf;
1253 if (fp_is_glob_file) {
1254 while (*p && !g_ascii_isspace(*p) && (*p!=':')) p++;
1255 } else {
1256 while (*p && !g_ascii_isspace(*p)) p++;
1259 if (*p) {
1260 *p = '\0';
1261 p++;
1263 delim = strchr(buf, '/');
1264 if (delim == NULL) continue;
1265 *delim = '\0';
1267 mime_type = g_new(MimeType, 1);
1268 mime_type->type = g_strdup(buf);
1269 mime_type->sub_type = g_strdup(delim + 1);
1271 if (fp_is_glob_file) {
1272 while (*p && (g_ascii_isspace(*p)||(*p=='*')||(*p=='.'))) p++;
1273 } else {
1274 while (*p && g_ascii_isspace(*p)) p++;
1277 if (*p)
1278 mime_type->extension = g_utf8_strdown(p, -1);
1279 else
1280 mime_type->extension = NULL;
1282 list = g_list_append(list, mime_type);
1285 claws_fclose(fp);
1287 if (!list)
1288 g_warning("can't read mime.types");
1290 return list;
1293 EncodingType procmime_get_encoding_for_charset(const gchar *charset)
1295 if (!charset)
1296 return ENC_8BIT;
1297 else if (!g_ascii_strncasecmp(charset, "ISO-2022-", 9) ||
1298 !g_ascii_strcasecmp(charset, "US-ASCII"))
1299 return ENC_7BIT;
1300 else if (!g_ascii_strcasecmp(charset, "ISO-8859-5") ||
1301 !g_ascii_strncasecmp(charset, "KOI8-", 5) ||
1302 !g_ascii_strcasecmp(charset, "X-MAC-CYRILLIC") ||
1303 !g_ascii_strcasecmp(charset, "MAC-CYRILLIC") ||
1304 !g_ascii_strcasecmp(charset, "Windows-1251"))
1305 return ENC_8BIT;
1306 else if (!g_ascii_strncasecmp(charset, "ISO-8859-", 9))
1307 return ENC_QUOTED_PRINTABLE;
1308 else if (!g_ascii_strncasecmp(charset, "UTF-8", 5))
1309 return ENC_QUOTED_PRINTABLE;
1310 else
1311 return ENC_8BIT;
1314 EncodingType procmime_get_encoding_for_text_file(const gchar *file, gboolean *has_binary)
1316 FILE *fp;
1317 guchar buf[BUFFSIZE];
1318 size_t len;
1319 size_t octet_chars = 0;
1320 size_t total_len = 0;
1321 gfloat octet_percentage;
1322 gboolean force_b64 = FALSE;
1324 if ((fp = claws_fopen(file, "rb")) == NULL) {
1325 FILE_OP_ERROR(file, "claws_fopen");
1326 return ENC_UNKNOWN;
1329 while ((len = claws_fread(buf, sizeof(guchar), sizeof(buf), fp)) > 0) {
1330 guchar *p;
1331 gint i;
1333 for (p = buf, i = 0; i < len; ++p, ++i) {
1334 if (*p & 0x80)
1335 ++octet_chars;
1336 if (*p == '\0') {
1337 force_b64 = TRUE;
1338 *has_binary = TRUE;
1341 total_len += len;
1344 claws_fclose(fp);
1346 if (total_len > 0)
1347 octet_percentage = (gfloat)octet_chars / (gfloat)total_len;
1348 else
1349 octet_percentage = 0.0;
1351 debug_print("procmime_get_encoding_for_text_file(): "
1352 "8bit chars: %"G_GSIZE_FORMAT" / %"G_GSIZE_FORMAT" (%f%%)\n", octet_chars, total_len,
1353 100.0 * octet_percentage);
1355 if (octet_percentage > 0.20 || force_b64) {
1356 debug_print("using BASE64\n");
1357 return ENC_BASE64;
1358 } else if (octet_chars > 0) {
1359 debug_print("using quoted-printable\n");
1360 return ENC_QUOTED_PRINTABLE;
1361 } else {
1362 debug_print("using 7bit\n");
1363 return ENC_7BIT;
1367 struct EncodingTable
1369 gchar *str;
1370 EncodingType enc_type;
1373 struct EncodingTable encoding_table[] = {
1374 {"7bit", ENC_7BIT},
1375 {"8bit", ENC_8BIT},
1376 {"binary", ENC_BINARY},
1377 {"quoted-printable", ENC_QUOTED_PRINTABLE},
1378 {"base64", ENC_BASE64},
1379 {"x-uuencode", ENC_UNKNOWN},
1380 {NULL, ENC_UNKNOWN},
1383 const gchar *procmime_get_encoding_str(EncodingType encoding)
1385 struct EncodingTable *enc_table;
1387 for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1388 if (enc_table->enc_type == encoding)
1389 return enc_table->str;
1391 return NULL;
1394 /* --- NEW MIME STUFF --- */
1395 struct TypeTable
1397 gchar *str;
1398 MimeMediaType type;
1401 static struct TypeTable mime_type_table[] = {
1402 {"text", MIMETYPE_TEXT},
1403 {"image", MIMETYPE_IMAGE},
1404 {"audio", MIMETYPE_AUDIO},
1405 {"video", MIMETYPE_VIDEO},
1406 {"model", MIMETYPE_MODEL},
1407 {"application", MIMETYPE_APPLICATION},
1408 {"message", MIMETYPE_MESSAGE},
1409 {"multipart", MIMETYPE_MULTIPART},
1410 {NULL, 0},
1413 const gchar *procmime_get_media_type_str(MimeMediaType type)
1415 struct TypeTable *type_table;
1417 for (type_table = mime_type_table; type_table->str != NULL; type_table++) {
1418 if (type_table->type == type)
1419 return type_table->str;
1421 return NULL;
1424 MimeMediaType procmime_get_media_type(const gchar *str)
1426 struct TypeTable *typetablearray;
1428 for (typetablearray = mime_type_table; typetablearray->str != NULL; typetablearray++)
1429 if (g_ascii_strncasecmp(str, typetablearray->str, strlen(typetablearray->str)) == 0)
1430 return typetablearray->type;
1432 return MIMETYPE_UNKNOWN;
1436 *\brief Safe wrapper for content type string.
1438 *\return const gchar * Pointer to content type string.
1440 gchar *procmime_get_content_type_str(MimeMediaType type,
1441 const char *subtype)
1443 const gchar *type_str = NULL;
1445 if (subtype == NULL || !(type_str = procmime_get_media_type_str(type)))
1446 return g_strdup("unknown");
1447 return g_strdup_printf("%s/%s", type_str, subtype);
1450 static int procmime_parse_mimepart(MimeInfo *parent,
1451 gchar *content_type,
1452 gchar *content_encoding,
1453 gchar *content_description,
1454 gchar *content_id,
1455 gchar *content_disposition,
1456 gchar *content_location,
1457 const gchar *original_msgid,
1458 const gchar *disposition_notification_hdr,
1459 const gchar *filename,
1460 guint offset,
1461 guint length,
1462 gboolean short_scan);
1464 static void procmime_parse_message_rfc822(MimeInfo *mimeinfo, gboolean short_scan)
1466 HeaderEntry hentry[] = {{"Content-Type:", NULL, TRUE},
1467 {"Content-Transfer-Encoding:",
1468 NULL, FALSE},
1469 {"Content-Description:",
1470 NULL, TRUE},
1471 {"Content-ID:",
1472 NULL, TRUE},
1473 {"Content-Disposition:",
1474 NULL, TRUE},
1475 {"Content-Location:",
1476 NULL, TRUE},
1477 {"MIME-Version:",
1478 NULL, TRUE},
1479 {"Original-Message-ID:",
1480 NULL, TRUE},
1481 {"Disposition:",
1482 NULL, TRUE},
1483 {NULL, NULL, FALSE}};
1484 guint content_start, i;
1485 FILE *fp;
1486 gchar *tmp;
1487 gint len = 0;
1489 procmime_decode_content(mimeinfo);
1491 fp = claws_fopen(mimeinfo->data.filename, "rb");
1492 if (fp == NULL) {
1493 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
1494 return;
1496 if (fseek(fp, mimeinfo->offset, SEEK_SET) < 0) {
1497 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
1498 claws_fclose(fp);
1499 return;
1501 procheader_get_header_fields(fp, hentry);
1502 if (hentry[0].body != NULL) {
1503 tmp = conv_unmime_header(hentry[0].body, NULL, FALSE);
1504 g_free(hentry[0].body);
1505 hentry[0].body = tmp;
1507 if (hentry[2].body != NULL) {
1508 tmp = conv_unmime_header(hentry[2].body, NULL, FALSE);
1509 g_free(hentry[2].body);
1510 hentry[2].body = tmp;
1512 if (hentry[4].body != NULL) {
1513 tmp = conv_unmime_header(hentry[4].body, NULL, FALSE);
1514 g_free(hentry[4].body);
1515 hentry[4].body = tmp;
1517 if (hentry[5].body != NULL) {
1518 tmp = conv_unmime_header(hentry[5].body, NULL, FALSE);
1519 g_free(hentry[5].body);
1520 hentry[5].body = tmp;
1522 if (hentry[7].body != NULL) {
1523 tmp = conv_unmime_header(hentry[7].body, NULL, FALSE);
1524 g_free(hentry[7].body);
1525 hentry[7].body = tmp;
1527 if (hentry[8].body != NULL) {
1528 tmp = conv_unmime_header(hentry[8].body, NULL, FALSE);
1529 g_free(hentry[8].body);
1530 hentry[8].body = tmp;
1533 content_start = ftell(fp);
1534 claws_fclose(fp);
1536 len = mimeinfo->length - (content_start - mimeinfo->offset);
1537 if (len < 0)
1538 len = 0;
1539 procmime_parse_mimepart(mimeinfo,
1540 hentry[0].body, hentry[1].body,
1541 hentry[2].body, hentry[3].body,
1542 hentry[4].body, hentry[5].body,
1543 hentry[7].body, hentry[8].body,
1544 mimeinfo->data.filename, content_start,
1545 len, short_scan);
1547 for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1548 g_free(hentry[i].body);
1549 hentry[i].body = NULL;
1553 static void procmime_parse_disposition_notification(MimeInfo *mimeinfo,
1554 const gchar *original_msgid, const gchar *disposition_notification_hdr,
1555 gboolean short_scan)
1557 HeaderEntry hentry[] = {{"Original-Message-ID:", NULL, TRUE},
1558 {"Disposition:", NULL, TRUE},
1559 {NULL, NULL, FALSE}};
1560 guint i;
1561 FILE *fp;
1562 gchar *orig_msg_id = NULL;
1563 gchar *disp = NULL;
1565 procmime_decode_content(mimeinfo);
1567 debug_print("parse disposition notification\n");
1568 fp = claws_fopen(mimeinfo->data.filename, "rb");
1569 if (fp == NULL) {
1570 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
1571 return;
1573 if (fseek(fp, mimeinfo->offset, SEEK_SET) < 0) {
1574 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
1575 claws_fclose(fp);
1576 return;
1579 if (original_msgid && disposition_notification_hdr) {
1580 hentry[0].body = g_strdup(original_msgid);
1581 hentry[1].body = g_strdup(disposition_notification_hdr);
1582 } else {
1583 procheader_get_header_fields(fp, hentry);
1586 claws_fclose(fp);
1588 if (!hentry[0].body || !hentry[1].body) {
1589 debug_print("MsgId %s, Disp %s\n",
1590 hentry[0].body ? hentry[0].body:"(nil)",
1591 hentry[1].body ? hentry[1].body:"(nil)");
1592 goto bail;
1595 orig_msg_id = g_strdup(hentry[0].body);
1596 disp = g_strdup(hentry[1].body);
1598 extract_parenthesis(orig_msg_id, '<', '>');
1599 remove_space(orig_msg_id);
1601 if (strstr(disp, "displayed")) {
1602 /* find sent message, if possible */
1603 MsgInfo *info = NULL;
1604 GList *flist;
1605 debug_print("%s has been displayed.\n", orig_msg_id);
1606 for (flist = folder_get_list(); flist != NULL; flist = g_list_next(flist)) {
1607 FolderItem *outbox = ((Folder *)(flist->data))->outbox;
1608 if (!outbox) {
1609 debug_print("skipping folder with no outbox...\n");
1610 continue;
1612 info = folder_item_get_msginfo_by_msgid(outbox, orig_msg_id);
1613 debug_print("%s %s in %s\n", info?"found":"didn't find", orig_msg_id, outbox->path);
1614 if (info) {
1615 procmsg_msginfo_set_flags(info, MSG_RETRCPT_GOT, 0);
1616 procmsg_msginfo_free(&info);
1620 g_free(orig_msg_id);
1621 g_free(disp);
1622 bail:
1623 for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1624 g_free(hentry[i].body);
1625 hentry[i].body = NULL;
1629 #define GET_HEADERS() { \
1630 procheader_get_header_fields(fp, hentry); \
1631 if (hentry[0].body != NULL) { \
1632 tmp = conv_unmime_header(hentry[0].body, NULL, FALSE); \
1633 g_free(hentry[0].body); \
1634 hentry[0].body = tmp; \
1636 if (hentry[2].body != NULL) { \
1637 tmp = conv_unmime_header(hentry[2].body, NULL, FALSE); \
1638 g_free(hentry[2].body); \
1639 hentry[2].body = tmp; \
1641 if (hentry[4].body != NULL) { \
1642 tmp = conv_unmime_header(hentry[4].body, NULL, FALSE); \
1643 g_free(hentry[4].body); \
1644 hentry[4].body = tmp; \
1646 if (hentry[5].body != NULL) { \
1647 tmp = conv_unmime_header(hentry[5].body, NULL, FALSE); \
1648 g_free(hentry[5].body); \
1649 hentry[5].body = tmp; \
1651 if (hentry[6].body != NULL) { \
1652 tmp = conv_unmime_header(hentry[6].body, NULL, FALSE); \
1653 g_free(hentry[6].body); \
1654 hentry[6].body = tmp; \
1656 if (hentry[7].body != NULL) { \
1657 tmp = conv_unmime_header(hentry[7].body, NULL, FALSE); \
1658 g_free(hentry[7].body); \
1659 hentry[7].body = tmp; \
1663 static void procmime_parse_multipart(MimeInfo *mimeinfo, gboolean short_scan)
1665 HeaderEntry hentry[] = {{"Content-Type:", NULL, TRUE},
1666 {"Content-Transfer-Encoding:",
1667 NULL, FALSE},
1668 {"Content-Description:",
1669 NULL, TRUE},
1670 {"Content-ID:",
1671 NULL, TRUE},
1672 {"Content-Disposition:",
1673 NULL, TRUE},
1674 {"Content-Location:",
1675 NULL, TRUE},
1676 {"Original-Message-ID:",
1677 NULL, TRUE},
1678 {"Disposition:",
1679 NULL, TRUE},
1680 {NULL, NULL, FALSE}};
1681 gchar *tmp;
1682 gchar *boundary;
1683 gint boundary_len = 0, lastoffset = -1, i;
1684 gchar buf[BUFFSIZE];
1685 FILE *fp;
1686 int result = 0;
1687 gboolean start_found = FALSE;
1688 gboolean end_found = FALSE;
1690 boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
1691 if (!boundary)
1692 return;
1693 boundary_len = strlen(boundary);
1695 procmime_decode_content(mimeinfo);
1697 fp = claws_fopen(mimeinfo->data.filename, "rb");
1698 if (fp == NULL) {
1699 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
1700 return;
1703 if (fseek(fp, mimeinfo->offset, SEEK_SET) < 0) {
1704 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
1705 claws_fclose(fp);
1706 return;
1709 while (claws_fgets(buf, sizeof(buf), fp) != NULL && result == 0) {
1710 if (ftell(fp) - 1 > (mimeinfo->offset + mimeinfo->length))
1711 break;
1713 if (IS_BOUNDARY(buf, boundary, boundary_len)) {
1714 start_found = TRUE;
1716 if (lastoffset != -1) {
1717 gint len = (ftell(fp) - strlen(buf)) - lastoffset - 1;
1718 if (len < 0)
1719 len = 0;
1720 result = procmime_parse_mimepart(mimeinfo,
1721 hentry[0].body, hentry[1].body,
1722 hentry[2].body, hentry[3].body,
1723 hentry[4].body, hentry[5].body,
1724 hentry[6].body, hentry[7].body,
1725 mimeinfo->data.filename, lastoffset,
1726 len, short_scan);
1727 if (result == 1 && short_scan)
1728 break;
1732 if (buf[2 + boundary_len] == '-' &&
1733 buf[2 + boundary_len + 1] == '-') {
1734 end_found = TRUE;
1735 break;
1737 for (i = 0; i < (sizeof hentry / sizeof hentry[0]) ; i++) {
1738 g_free(hentry[i].body);
1739 hentry[i].body = NULL;
1741 GET_HEADERS();
1742 lastoffset = ftell(fp);
1746 if (start_found && !end_found && lastoffset != -1) {
1747 gint len = (ftell(fp) - strlen(buf)) - lastoffset - 1;
1749 if (len >= 0) {
1750 result = procmime_parse_mimepart(mimeinfo,
1751 hentry[0].body, hentry[1].body,
1752 hentry[2].body, hentry[3].body,
1753 hentry[4].body, hentry[5].body,
1754 hentry[6].body, hentry[7].body,
1755 mimeinfo->data.filename, lastoffset,
1756 len, short_scan);
1758 mimeinfo->broken = TRUE;
1761 for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1762 g_free(hentry[i].body);
1763 hentry[i].body = NULL;
1765 claws_fclose(fp);
1768 static void parse_parameters(const gchar *parameters, GHashTable *table)
1770 gchar *params, *param, *next;
1771 GSList *convlist = NULL, *concatlist = NULL, *cur;
1773 params = g_strdup(parameters);
1774 param = params;
1775 next = params;
1776 for (; next != NULL; param = next) {
1777 gchar *attribute, *value, *tmp, *down_attr, *orig_down_attr;
1778 gint len;
1779 gboolean convert = FALSE;
1781 next = strchr_with_skip_quote(param, '"', ';');
1782 if (next != NULL) {
1783 next[0] = '\0';
1784 next++;
1787 g_strstrip(param);
1789 attribute = param;
1790 value = strchr(attribute, '=');
1791 if (value == NULL)
1792 continue;
1794 value[0] = '\0';
1795 value++;
1796 while (value[0] != '\0' && value[0] == ' ')
1797 value++;
1799 down_attr = g_utf8_strdown(attribute, -1);
1800 orig_down_attr = down_attr;
1802 len = down_attr ? strlen(down_attr):0;
1803 if (len > 0 && down_attr[len - 1] == '*') {
1804 gchar *srcpos, *dstpos, *endpos;
1806 convert = TRUE;
1807 down_attr[len - 1] = '\0';
1809 srcpos = value;
1810 dstpos = value;
1811 endpos = value + strlen(value);
1812 while (srcpos < endpos) {
1813 if (*srcpos != '%')
1814 *dstpos = *srcpos;
1815 else {
1816 guchar dstvalue;
1818 if (!get_hex_value(&dstvalue, srcpos[1], srcpos[2]))
1819 *dstpos = '?';
1820 else
1821 *dstpos = dstvalue;
1822 srcpos += 2;
1824 srcpos++;
1825 dstpos++;
1827 *dstpos = '\0';
1828 if (value[0] == '"')
1829 extract_quote(value, '"');
1830 } else {
1831 if (value[0] == '"')
1832 extract_quote(value, '"');
1833 else if ((tmp = strchr(value, ' ')) != NULL)
1834 *tmp = '\0';
1837 if (down_attr) {
1838 while (down_attr[0] == ' ')
1839 down_attr++;
1840 while (down_attr[strlen(down_attr)-1] == ' ')
1841 down_attr[strlen(down_attr)-1] = '\0';
1844 while (value[0] != '\0' && value[0] == ' ')
1845 value++;
1846 while (value[strlen(value)-1] == ' ')
1847 value[strlen(value)-1] = '\0';
1849 if (down_attr && strrchr(down_attr, '*') != NULL) {
1850 gchar *tmpattr;
1852 tmpattr = g_strdup(down_attr);
1853 tmp = strrchr(tmpattr, '*');
1854 tmp[0] = '\0';
1856 if ((tmp[1] == '0') && (tmp[2] == '\0') &&
1857 (g_slist_find_custom(concatlist, down_attr, (GCompareFunc)g_strcmp0) == NULL))
1858 concatlist = g_slist_prepend(concatlist, g_strdup(tmpattr));
1860 if (convert && (g_slist_find_custom(convlist, tmpattr, (GCompareFunc)g_strcmp0) == NULL))
1861 convlist = g_slist_prepend(convlist, g_strdup(tmpattr));
1863 g_free(tmpattr);
1864 } else if (convert) {
1865 if (g_slist_find_custom(convlist, down_attr, (GCompareFunc)g_strcmp0) == NULL)
1866 convlist = g_slist_prepend(convlist, g_strdup(down_attr));
1869 if (g_hash_table_lookup(table, down_attr) == NULL)
1870 g_hash_table_insert(table, g_strdup(down_attr), g_strdup(value));
1871 g_free(orig_down_attr);
1874 for (cur = concatlist; cur != NULL; cur = g_slist_next(cur)) {
1875 gchar *attribute, *attrwnum, *partvalue;
1876 gint n = 0;
1877 GString *value;
1879 attribute = (gchar *) cur->data;
1880 value = g_string_sized_new(64);
1882 attrwnum = g_strdup_printf("%s*%d", attribute, n);
1883 while ((partvalue = g_hash_table_lookup(table, attrwnum)) != NULL) {
1884 g_string_append(value, partvalue);
1886 g_hash_table_remove(table, attrwnum);
1887 g_free(attrwnum);
1888 n++;
1889 attrwnum = g_strdup_printf("%s*%d", attribute, n);
1891 g_free(attrwnum);
1893 g_hash_table_insert(table, g_strdup(attribute), g_strdup(value->str));
1894 g_string_free(value, TRUE);
1896 slist_free_strings_full(concatlist);
1898 for (cur = convlist; cur != NULL; cur = g_slist_next(cur)) {
1899 gchar *attribute, *key, *value;
1900 gchar *charset, *lang, *oldvalue, *newvalue;
1902 attribute = (gchar *) cur->data;
1903 if (!g_hash_table_lookup_extended(
1904 table, attribute, (gpointer *)(gchar *) &key, (gpointer *)(gchar *) &value))
1905 continue;
1907 charset = value;
1908 if (charset == NULL)
1909 continue;
1910 lang = strchr(charset, '\'');
1911 if (lang == NULL)
1912 continue;
1913 lang[0] = '\0';
1914 lang++;
1915 oldvalue = strchr(lang, '\'');
1916 if (oldvalue == NULL)
1917 continue;
1918 oldvalue[0] = '\0';
1919 oldvalue++;
1921 newvalue = conv_codeset_strdup(oldvalue, charset, CS_UTF_8);
1923 g_hash_table_remove(table, attribute);
1924 g_free(key);
1925 g_free(value);
1927 g_hash_table_insert(table, g_strdup(attribute), newvalue);
1929 slist_free_strings_full(convlist);
1931 g_free(params);
1934 static void procmime_parse_content_type(const gchar *content_type, MimeInfo *mimeinfo)
1936 cm_return_if_fail(content_type != NULL);
1937 cm_return_if_fail(mimeinfo != NULL);
1939 /* RFC 2045, page 13 says that the mime subtype is MANDATORY;
1940 * if it's not available we use the default Content-Type */
1941 if ((content_type[0] == '\0') || (strchr(content_type, '/') == NULL)) {
1942 mimeinfo->type = MIMETYPE_TEXT;
1943 mimeinfo->subtype = g_strdup("plain");
1944 if (g_hash_table_lookup(mimeinfo->typeparameters,
1945 "charset") == NULL) {
1946 g_hash_table_insert(mimeinfo->typeparameters,
1947 g_strdup("charset"),
1948 g_strdup(
1949 conv_get_locale_charset_str_no_utf8()));
1951 } else {
1952 gchar *type, *subtype, *params;
1954 type = g_strdup(content_type);
1955 subtype = strchr(type, '/') + 1;
1956 *(subtype - 1) = '\0';
1957 if ((params = strchr(subtype, ';')) != NULL) {
1958 params[0] = '\0';
1959 params++;
1962 mimeinfo->type = procmime_get_media_type(type);
1963 mimeinfo->subtype = g_strstrip(g_strdup(subtype));
1965 /* Get mimeinfo->typeparameters */
1966 if (params != NULL)
1967 parse_parameters(params, mimeinfo->typeparameters);
1969 g_free(type);
1973 static void procmime_parse_content_disposition(const gchar *content_disposition, MimeInfo *mimeinfo)
1975 gchar *tmp, *params;
1977 cm_return_if_fail(content_disposition != NULL);
1978 cm_return_if_fail(mimeinfo != NULL);
1980 tmp = g_strdup(content_disposition);
1981 if ((params = strchr(tmp, ';')) != NULL) {
1982 params[0] = '\0';
1983 params++;
1985 g_strstrip(tmp);
1987 if (!g_ascii_strcasecmp(tmp, "inline"))
1988 mimeinfo->disposition = DISPOSITIONTYPE_INLINE;
1989 else if (!g_ascii_strcasecmp(tmp, "attachment"))
1990 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1991 else
1992 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1994 if (params != NULL)
1995 parse_parameters(params, mimeinfo->dispositionparameters);
1997 g_free(tmp);
2001 static void procmime_parse_content_encoding(const gchar *content_encoding, MimeInfo *mimeinfo)
2003 struct EncodingTable *enc_table;
2005 for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
2006 if (g_ascii_strcasecmp(enc_table->str, content_encoding) == 0) {
2007 mimeinfo->encoding_type = enc_table->enc_type;
2008 return;
2011 mimeinfo->encoding_type = ENC_UNKNOWN;
2012 return;
2015 static GSList *registered_parsers = NULL;
2017 static MimeParser *procmime_get_mimeparser_for_type(MimeMediaType type, const gchar *sub_type)
2019 GSList *cur;
2020 for (cur = registered_parsers; cur; cur = cur->next) {
2021 MimeParser *parser = (MimeParser *)cur->data;
2022 if (parser->type == type && !g_strcmp0(parser->sub_type, sub_type))
2023 return parser;
2025 return NULL;
2028 void procmime_mimeparser_register(MimeParser *parser)
2030 if (!procmime_get_mimeparser_for_type(parser->type, parser->sub_type))
2031 registered_parsers = g_slist_append(registered_parsers, parser);
2035 void procmime_mimeparser_unregister(MimeParser *parser)
2037 registered_parsers = g_slist_remove(registered_parsers, parser);
2040 static gboolean procmime_mimeparser_parse(MimeParser *parser, MimeInfo *mimeinfo)
2042 cm_return_val_if_fail(parser->parse != NULL, FALSE);
2043 return parser->parse(parser, mimeinfo);
2046 static int procmime_parse_mimepart(MimeInfo *parent,
2047 gchar *content_type,
2048 gchar *content_encoding,
2049 gchar *content_description,
2050 gchar *content_id,
2051 gchar *content_disposition,
2052 gchar *content_location,
2053 const gchar *original_msgid,
2054 const gchar *disposition_notification_hdr,
2055 const gchar *filename,
2056 guint offset,
2057 guint length,
2058 gboolean short_scan)
2060 MimeInfo *mimeinfo;
2061 MimeParser *parser = NULL;
2062 gboolean parsed = FALSE;
2063 int result = 0;
2065 /* Create MimeInfo */
2066 mimeinfo = procmime_mimeinfo_new();
2067 mimeinfo->content = MIMECONTENT_FILE;
2069 if (parent != NULL) {
2070 if (g_node_depth(parent->node) > 32) {
2071 /* 32 is an arbitrary value
2072 * this avoids DOSsing ourselves
2073 * with enormous messages
2075 procmime_mimeinfo_free_all(&mimeinfo);
2076 return -1;
2078 g_node_append(parent->node, mimeinfo->node);
2080 mimeinfo->data.filename = g_strdup(filename);
2081 mimeinfo->offset = offset;
2082 mimeinfo->length = length;
2084 if (content_type != NULL) {
2085 g_strchomp(content_type);
2086 procmime_parse_content_type(content_type, mimeinfo);
2087 } else {
2088 mimeinfo->type = MIMETYPE_TEXT;
2089 mimeinfo->subtype = g_strdup("plain");
2090 if (g_hash_table_lookup(mimeinfo->typeparameters,
2091 "charset") == NULL) {
2092 g_hash_table_insert(mimeinfo->typeparameters,
2093 g_strdup("charset"),
2094 g_strdup(
2095 conv_get_locale_charset_str_no_utf8()));
2099 if (content_encoding != NULL) {
2100 g_strchomp(content_encoding);
2101 procmime_parse_content_encoding(content_encoding, mimeinfo);
2102 } else {
2103 mimeinfo->encoding_type = ENC_UNKNOWN;
2106 if (content_description != NULL)
2107 mimeinfo->description = g_strdup(content_description);
2108 else
2109 mimeinfo->description = NULL;
2111 if (content_id != NULL)
2112 mimeinfo->id = g_strdup(content_id);
2113 else
2114 mimeinfo->id = NULL;
2116 if (content_location != NULL)
2117 mimeinfo->location = g_strdup(content_location);
2118 else
2119 mimeinfo->location = NULL;
2121 if (content_disposition != NULL) {
2122 g_strchomp(content_disposition);
2123 procmime_parse_content_disposition(content_disposition, mimeinfo);
2124 } else
2125 mimeinfo->disposition = DISPOSITIONTYPE_UNKNOWN;
2127 /* Call parser for mime type */
2128 if ((parser = procmime_get_mimeparser_for_type(mimeinfo->type, mimeinfo->subtype)) != NULL) {
2129 parsed = procmime_mimeparser_parse(parser, mimeinfo);
2131 if (!parsed) {
2132 switch (mimeinfo->type) {
2133 case MIMETYPE_TEXT:
2134 if (g_ascii_strcasecmp(mimeinfo->subtype, "plain") == 0 && short_scan) {
2135 return 1;
2137 break;
2139 case MIMETYPE_MESSAGE:
2140 if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
2141 procmime_parse_message_rfc822(mimeinfo, short_scan);
2143 if (g_ascii_strcasecmp(mimeinfo->subtype, "disposition-notification") == 0) {
2144 procmime_parse_disposition_notification(mimeinfo,
2145 original_msgid, disposition_notification_hdr, short_scan);
2147 break;
2149 case MIMETYPE_MULTIPART:
2150 procmime_parse_multipart(mimeinfo, short_scan);
2151 break;
2153 case MIMETYPE_APPLICATION:
2154 if (g_ascii_strcasecmp(mimeinfo->subtype, "octet-stream") == 0
2155 && original_msgid && *original_msgid
2156 && disposition_notification_hdr && *disposition_notification_hdr) {
2157 procmime_parse_disposition_notification(mimeinfo,
2158 original_msgid, disposition_notification_hdr, short_scan);
2160 break;
2161 default:
2162 break;
2166 return result;
2169 static gchar *typenames[] = {
2170 "text",
2171 "image",
2172 "audio",
2173 "video",
2174 "application",
2175 "message",
2176 "multipart",
2177 "model",
2178 "unknown",
2181 static gboolean output_func(GNode *node, gpointer data)
2183 guint i, depth;
2184 MimeInfo *mimeinfo = (MimeInfo *) node->data;
2186 depth = g_node_depth(node);
2187 for (i = 0; i < depth; i++)
2188 g_print(" ");
2189 g_print("%s/%s (offset:%d length:%d encoding: %d)\n",
2190 (mimeinfo->type <= MIMETYPE_UNKNOWN)? typenames[mimeinfo->type] : "unknown",
2191 mimeinfo->subtype, mimeinfo->offset, mimeinfo->length, mimeinfo->encoding_type);
2193 return FALSE;
2196 static void output_mime_structure(MimeInfo *mimeinfo, int indent)
2198 g_node_traverse(mimeinfo->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1, output_func, NULL);
2201 static MimeInfo *procmime_scan_file_with_offset(const gchar *filename, int offset, gboolean short_scan)
2203 MimeInfo *mimeinfo;
2204 GStatBuf buf;
2206 if (g_stat(filename, &buf) < 0) {
2207 FILE_OP_ERROR(filename, "stat");
2208 return NULL;
2211 mimeinfo = procmime_mimeinfo_new();
2212 mimeinfo->content = MIMECONTENT_FILE;
2213 mimeinfo->encoding_type = ENC_UNKNOWN;
2214 mimeinfo->type = MIMETYPE_MESSAGE;
2215 mimeinfo->subtype = g_strdup("rfc822");
2216 mimeinfo->data.filename = g_strdup(filename);
2217 mimeinfo->offset = offset;
2218 mimeinfo->length = buf.st_size - offset;
2220 procmime_parse_message_rfc822(mimeinfo, short_scan);
2221 if (debug_get_mode())
2222 output_mime_structure(mimeinfo, 0);
2224 return mimeinfo;
2227 static MimeInfo *procmime_scan_file_full(const gchar *filename, gboolean short_scan)
2229 MimeInfo *mimeinfo;
2231 cm_return_val_if_fail(filename != NULL, NULL);
2233 mimeinfo = procmime_scan_file_with_offset(filename, 0, short_scan);
2235 return mimeinfo;
2238 MimeInfo *procmime_scan_file(const gchar *filename)
2240 return procmime_scan_file_full(filename, FALSE);
2243 static MimeInfo *procmime_scan_file_short(const gchar *filename)
2245 return procmime_scan_file_full(filename, TRUE);
2248 static MimeInfo *procmime_scan_queue_file_full(const gchar *filename, gboolean short_scan)
2250 FILE *fp;
2251 MimeInfo *mimeinfo;
2252 gchar buf[BUFFSIZE];
2253 gint offset = 0;
2255 cm_return_val_if_fail(filename != NULL, NULL);
2257 /* Open file */
2258 if ((fp = claws_fopen(filename, "rb")) == NULL)
2259 return NULL;
2260 /* Skip queue header */
2261 while (claws_fgets(buf, sizeof(buf), fp) != NULL) {
2262 /* new way */
2263 if ((!strncmp(buf, "X-Claws-End-Special-Headers: 1",
2264 strlen("X-Claws-End-Special-Headers:"))) ||
2265 (!strncmp(buf, "X-Sylpheed-End-Special-Headers: 1",
2266 strlen("X-Sylpheed-End-Special-Headers:"))))
2267 break;
2268 /* old way */
2269 if (buf[0] == '\r' || buf[0] == '\n') break;
2270 /* from other mailers */
2271 if (!strncmp(buf, "Date: ", 6)
2272 || !strncmp(buf, "To: ", 4)
2273 || !strncmp(buf, "From: ", 6)
2274 || !strncmp(buf, "Subject: ", 9)) {
2275 rewind(fp);
2276 break;
2279 offset = ftell(fp);
2280 claws_fclose(fp);
2282 mimeinfo = procmime_scan_file_with_offset(filename, offset, short_scan);
2284 return mimeinfo;
2287 MimeInfo *procmime_scan_queue_file(const gchar *filename)
2289 return procmime_scan_queue_file_full(filename, FALSE);
2292 static MimeInfo *procmime_scan_queue_file_short(const gchar *filename)
2294 return procmime_scan_queue_file_full(filename, TRUE);
2297 typedef enum {
2298 ENC_AS_TOKEN,
2299 ENC_AS_QUOTED_STRING,
2300 ENC_AS_EXTENDED,
2301 ENC_AS_ENCWORD
2302 } EncodeAs;
2304 typedef struct _ParametersData {
2305 FILE *fp;
2306 guint len;
2307 gint error;
2308 } ParametersData;
2310 static void write_parameters(gpointer key, gpointer value, gpointer user_data)
2312 gchar *param = key;
2313 gchar *val = value, *valpos, *tmp;
2314 ParametersData *pdata = (ParametersData *)user_data;
2315 GString *buf = g_string_new("");
2316 gint len;
2318 EncodeAs encas = ENC_AS_TOKEN;
2320 for (valpos = val; *valpos != 0; valpos++) {
2321 if (!IS_ASCII(*valpos)) {
2322 encas = ENC_AS_ENCWORD;
2323 break;
2326 /* CTLs */
2327 if (((*valpos >= 0) && (*valpos < 037)) || (*valpos == 0177)) {
2328 encas = ENC_AS_QUOTED_STRING;
2329 continue;
2332 /* tspecials + SPACE */
2333 switch (*valpos) {
2334 case ' ':
2335 case '(':
2336 case ')':
2337 case '<':
2338 case '>':
2339 case '@':
2340 case ',':
2341 case ';':
2342 case ':':
2343 case '\\':
2344 case '"':
2345 case '/':
2346 case '[':
2347 case ']':
2348 case '?':
2349 case '=':
2350 encas = ENC_AS_QUOTED_STRING;
2351 continue;
2355 switch (encas) {
2356 case ENC_AS_TOKEN:
2357 g_string_append_printf(buf, "%s=%s", param, val);
2358 break;
2360 case ENC_AS_QUOTED_STRING:
2361 g_string_append_printf(buf, "%s=\"%s\"", param, val);
2362 break;
2364 #if 0 /* we don't use that for now */
2365 case ENC_AS_EXTENDED:
2366 if (!g_utf8_validate(val, -1, NULL))
2367 g_string_append_printf(buf, "%s*=%s''", param,
2368 conv_get_locale_charset_str());
2369 else
2370 g_string_append_printf(buf, "%s*=%s''", param,
2371 CS_INTERNAL);
2372 for (valpos = val; *valpos != '\0'; valpos++) {
2373 if (IS_ASCII(*valpos) && isalnum(*valpos)) {
2374 g_string_append_printf(buf, "%c", *valpos);
2375 } else {
2376 gchar hexstr[3] = "XX";
2377 get_hex_str(hexstr, *valpos);
2378 g_string_append_printf(buf, "%%%s", hexstr);
2381 break;
2382 #else
2383 case ENC_AS_EXTENDED:
2384 debug_print("Unhandled ENC_AS_EXTENDED.\n");
2385 break;
2386 #endif
2387 case ENC_AS_ENCWORD:
2388 len = MAX(strlen(val)*6, 512);
2389 tmp = g_malloc(len+1);
2390 codeconv_set_strict(TRUE);
2391 conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2392 prefs_common.outgoing_charset);
2393 codeconv_set_strict(FALSE);
2394 if (!tmp || !*tmp) {
2395 codeconv_set_strict(TRUE);
2396 conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2397 conv_get_outgoing_charset_str());
2398 codeconv_set_strict(FALSE);
2400 if (!tmp || !*tmp) {
2401 codeconv_set_strict(TRUE);
2402 conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2403 CS_UTF_8);
2404 codeconv_set_strict(FALSE);
2406 if (!tmp || !*tmp) {
2407 conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2408 CS_UTF_8);
2410 g_string_append_printf(buf, "%s=\"%s\"", param, tmp);
2411 g_free(tmp);
2412 break;
2416 if (buf->str && strlen(buf->str)) {
2417 tmp = strstr(buf->str, "\n");
2418 if (tmp)
2419 len = (tmp - buf->str);
2420 else
2421 len = strlen(buf->str);
2422 if (pdata->len + len > 76) {
2423 if (fprintf(pdata->fp, ";\n %s", buf->str) < 0)
2424 pdata->error = TRUE;
2425 pdata->len = strlen(buf->str) + 1;
2426 } else {
2427 if (fprintf(pdata->fp, "; %s", buf->str) < 0)
2428 pdata->error = TRUE;
2429 pdata->len += strlen(buf->str) + 2;
2432 g_string_free(buf, TRUE);
2435 #define TRY(func) { \
2436 if (!(func)) { \
2437 return -1; \
2441 int procmime_write_mime_header(MimeInfo *mimeinfo, FILE *fp)
2443 struct TypeTable *type_table;
2444 ParametersData *pdata = g_new0(ParametersData, 1);
2445 debug_print("procmime_write_mime_header\n");
2447 pdata->fp = fp;
2448 pdata->error = FALSE;
2449 for (type_table = mime_type_table; type_table->str != NULL; type_table++)
2450 if (mimeinfo->type == type_table->type) {
2451 gchar *buf = g_strdup_printf(
2452 "Content-Type: %s/%s", type_table->str, mimeinfo->subtype);
2453 if (fprintf(fp, "%s", buf) < 0) {
2454 g_free(buf);
2455 g_free(pdata);
2456 return -1;
2458 pdata->len = strlen(buf);
2459 g_free(buf);
2460 break;
2462 g_hash_table_foreach(mimeinfo->typeparameters, write_parameters, pdata);
2463 if (pdata->error == TRUE) {
2464 g_free(pdata);
2465 return -1;
2467 g_free(pdata);
2469 TRY(fprintf(fp, "\n") >= 0);
2471 if (mimeinfo->encoding_type != ENC_UNKNOWN)
2472 TRY(fprintf(fp, "Content-Transfer-Encoding: %s\n", procmime_get_encoding_str(mimeinfo->encoding_type)) >= 0);
2474 if (mimeinfo->description != NULL)
2475 TRY(fprintf(fp, "Content-Description: %s\n", mimeinfo->description) >= 0);
2477 if (mimeinfo->id != NULL)
2478 TRY(fprintf(fp, "Content-ID: %s\n", mimeinfo->id) >= 0);
2480 if (mimeinfo->location != NULL)
2481 TRY(fprintf(fp, "Content-Location: %s\n", mimeinfo->location) >= 0);
2483 if (mimeinfo->disposition != DISPOSITIONTYPE_UNKNOWN) {
2484 ParametersData *pdata = g_new0(ParametersData, 1);
2485 gchar *buf = NULL;
2486 if (mimeinfo->disposition == DISPOSITIONTYPE_INLINE)
2487 buf = g_strdup("Content-Disposition: inline");
2488 else if (mimeinfo->disposition == DISPOSITIONTYPE_ATTACHMENT)
2489 buf = g_strdup("Content-Disposition: attachment");
2490 else
2491 buf = g_strdup("Content-Disposition: unknown");
2493 if (fprintf(fp, "%s", buf) < 0) {
2494 g_free(buf);
2495 g_free(pdata);
2496 return -1;
2498 pdata->len = strlen(buf);
2499 g_free(buf);
2501 pdata->fp = fp;
2502 pdata->error = FALSE;
2503 g_hash_table_foreach(mimeinfo->dispositionparameters, write_parameters, pdata);
2504 if (pdata->error == TRUE) {
2505 g_free(pdata);
2506 return -1;
2508 g_free(pdata);
2509 TRY(fprintf(fp, "\n") >= 0);
2512 TRY(fprintf(fp, "\n") >= 0);
2514 return 0;
2517 static gint procmime_write_message_rfc822(MimeInfo *mimeinfo, FILE *fp)
2519 FILE *infp;
2520 GNode *childnode;
2521 MimeInfo *child;
2522 gchar buf[BUFFSIZE];
2523 gboolean skip = FALSE;
2524 size_t len;
2526 debug_print("procmime_write_message_rfc822\n");
2528 /* write header */
2529 switch (mimeinfo->content) {
2530 case MIMECONTENT_FILE:
2531 if ((infp = claws_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2532 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
2533 return -1;
2535 if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
2536 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
2537 claws_fclose(infp);
2538 return -1;
2540 while (claws_fgets(buf, sizeof(buf), infp) == buf) {
2541 strcrchomp(buf);
2542 if (buf[0] == '\n' && buf[1] == '\0')
2543 break;
2544 if (skip && (buf[0] == ' ' || buf[0] == '\t'))
2545 continue;
2546 if (g_ascii_strncasecmp(buf, "MIME-Version:", 13) == 0 ||
2547 g_ascii_strncasecmp(buf, "Content-Type:", 13) == 0 ||
2548 g_ascii_strncasecmp(buf, "Content-Transfer-Encoding:", 26) == 0 ||
2549 g_ascii_strncasecmp(buf, "Content-Description:", 20) == 0 ||
2550 g_ascii_strncasecmp(buf, "Content-ID:", 11) == 0 ||
2551 g_ascii_strncasecmp(buf, "Content-Location:", 17) == 0 ||
2552 g_ascii_strncasecmp(buf, "Content-Disposition:", 20) == 0) {
2553 skip = TRUE;
2554 continue;
2556 len = strlen(buf);
2557 if (claws_fwrite(buf, sizeof(gchar), len, fp) < len) {
2558 g_warning("failed to dump %"G_GSIZE_FORMAT" bytes from file", len);
2559 claws_fclose(infp);
2560 return -1;
2562 skip = FALSE;
2564 claws_fclose(infp);
2565 break;
2567 case MIMECONTENT_MEM:
2568 len = strlen(mimeinfo->data.mem);
2569 if (claws_fwrite(mimeinfo->data.mem, sizeof(gchar), len, fp) < len) {
2570 g_warning("failed to dump %"G_GSIZE_FORMAT" bytes from mem", len);
2571 return -1;
2573 break;
2575 default:
2576 break;
2579 childnode = mimeinfo->node->children;
2580 if (childnode == NULL)
2581 return -1;
2583 child = (MimeInfo *) childnode->data;
2584 if (fprintf(fp, "MIME-Version: 1.0\n") < 0) {
2585 g_warning("failed to write mime version");
2586 return -1;
2588 if (procmime_write_mime_header(child, fp) < 0)
2589 return -1;
2590 return procmime_write_mimeinfo(child, fp);
2593 static gint procmime_write_multipart(MimeInfo *mimeinfo, FILE *fp)
2595 FILE *infp;
2596 GNode *childnode;
2597 gchar *boundary, *str, *str2;
2598 gchar buf[BUFFSIZE];
2599 gboolean firstboundary;
2600 size_t len;
2602 debug_print("procmime_write_multipart\n");
2604 boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
2606 switch (mimeinfo->content) {
2607 case MIMECONTENT_FILE:
2608 if ((infp = claws_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2609 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
2610 return -1;
2612 if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
2613 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
2614 claws_fclose(infp);
2615 return -1;
2617 while (claws_fgets(buf, sizeof(buf), infp) == buf) {
2618 if (IS_BOUNDARY(buf, boundary, strlen(boundary)))
2619 break;
2620 len = strlen(buf);
2621 if (claws_fwrite(buf, sizeof(gchar), len, fp) < len) {
2622 g_warning("failed to write %"G_GSIZE_FORMAT, len);
2623 claws_fclose(infp);
2624 return -1;
2627 claws_fclose(infp);
2628 break;
2630 case MIMECONTENT_MEM:
2631 str = g_strdup(mimeinfo->data.mem);
2632 if (((str2 = strstr(str, boundary)) != NULL) && ((str2 - str) >= 2) &&
2633 (*(str2 - 1) == '-') && (*(str2 - 2) == '-'))
2634 *(str2 - 2) = '\0';
2635 len = strlen(str);
2636 if (claws_fwrite(str, sizeof(gchar), len, fp) < len) {
2637 g_warning("failed to write %"G_GSIZE_FORMAT" from mem", len);
2638 g_free(str);
2639 return -1;
2641 g_free(str);
2642 break;
2644 default:
2645 break;
2648 childnode = mimeinfo->node->children;
2649 firstboundary = TRUE;
2650 while (childnode != NULL) {
2651 MimeInfo *child = childnode->data;
2653 if (firstboundary)
2654 firstboundary = FALSE;
2655 else
2656 TRY(fprintf(fp, "\n") >= 0);
2658 TRY(fprintf(fp, "--%s\n", boundary) >= 0);
2660 if (procmime_write_mime_header(child, fp) < 0)
2661 return -1;
2662 if (procmime_write_mimeinfo(child, fp) < 0)
2663 return -1;
2665 childnode = g_node_next_sibling(childnode);
2667 TRY(fprintf(fp, "\n--%s--\n", boundary) >= 0);
2669 return 0;
2672 gint procmime_write_mimeinfo(MimeInfo *mimeinfo, FILE *fp)
2674 FILE *infp;
2675 size_t len;
2676 debug_print("procmime_write_mimeinfo\n");
2678 if (G_NODE_IS_LEAF(mimeinfo->node)) {
2679 switch (mimeinfo->content) {
2680 case MIMECONTENT_FILE:
2681 if ((infp = claws_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2682 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
2683 return -1;
2685 copy_file_part_to_fp(infp, mimeinfo->offset, mimeinfo->length, fp);
2686 claws_fclose(infp);
2687 return 0;
2689 case MIMECONTENT_MEM:
2690 len = strlen(mimeinfo->data.mem);
2691 if (claws_fwrite(mimeinfo->data.mem, sizeof(gchar), len, fp) < len)
2692 return -1;
2693 return 0;
2695 default:
2696 return 0;
2698 } else {
2699 /* Call writer for mime type */
2700 switch (mimeinfo->type) {
2701 case MIMETYPE_MESSAGE:
2702 if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
2703 return procmime_write_message_rfc822(mimeinfo, fp);
2705 break;
2707 case MIMETYPE_MULTIPART:
2708 return procmime_write_multipart(mimeinfo, fp);
2710 default:
2711 break;
2714 return -1;
2717 return 0;
2720 gchar *procmime_get_part_file_name(MimeInfo *mimeinfo)
2722 gchar *base;
2724 if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
2725 base = g_strdup("mimetmp.html");
2726 else {
2727 const gchar *basetmp;
2728 gchar *basename;
2730 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
2731 if (basetmp == NULL)
2732 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
2733 if (basetmp == NULL)
2734 basetmp = "mimetmp";
2735 basename = g_path_get_basename(basetmp);
2736 if (*basename == '\0') {
2737 g_free(basename);
2738 basename = g_strdup("mimetmp");
2740 base = conv_filename_from_utf8(basename);
2741 g_free(basename);
2742 subst_for_shellsafe_filename(base);
2745 return base;
2748 void *procmime_get_part_as_string(MimeInfo *mimeinfo,
2749 gboolean null_terminate)
2751 FILE *infp;
2752 gchar *data;
2753 gint length, readlength;
2755 cm_return_val_if_fail(mimeinfo != NULL, NULL);
2757 if (mimeinfo->encoding_type != ENC_BINARY &&
2758 !procmime_decode_content(mimeinfo))
2759 return NULL;
2761 if (mimeinfo->content == MIMECONTENT_MEM)
2762 return g_strdup(mimeinfo->data.mem);
2764 if ((infp = claws_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2765 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
2766 return NULL;
2769 if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
2770 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
2771 claws_fclose(infp);
2772 return NULL;
2775 length = mimeinfo->length;
2777 data = g_malloc(null_terminate ? length + 1 : length);
2778 if (data == NULL) {
2779 g_warning("could not allocate %d bytes for procmime_get_part_as_string",
2780 (null_terminate ? length + 1 : length));
2781 claws_fclose(infp);
2782 return NULL;
2785 readlength = claws_fread(data, length, 1, infp);
2786 if (readlength <= 0) {
2787 FILE_OP_ERROR(mimeinfo->data.filename, "fread");
2788 g_free(data);
2789 claws_fclose(infp);
2790 return NULL;
2793 claws_fclose(infp);
2795 if (null_terminate)
2796 data[length] = '\0';
2798 return data;
2801 /* Returns an open GInputStream. The caller should just
2802 * read mimeinfo->length bytes from it and then release it. */
2803 GInputStream *procmime_get_part_as_inputstream(MimeInfo *mimeinfo)
2805 cm_return_val_if_fail(mimeinfo != NULL, NULL);
2807 if (mimeinfo->encoding_type != ENC_BINARY &&
2808 !procmime_decode_content(mimeinfo)) {
2809 g_warning("could not decode part");
2810 return NULL;
2812 if (mimeinfo->content == MIMECONTENT_MEM) {
2813 /* NULL for destroy func, since we're not copying
2814 * the data for the stream. */
2815 return g_memory_input_stream_new_from_data(
2816 mimeinfo->data.mem,
2817 mimeinfo->length, NULL);
2818 } else {
2819 return g_memory_input_stream_new_from_data(
2820 procmime_get_part_as_string(mimeinfo, FALSE),
2821 mimeinfo->length, g_free);
2825 GdkPixbuf *procmime_get_part_as_pixbuf(MimeInfo *mimeinfo, GError **error)
2827 GdkPixbuf *pixbuf;
2828 GInputStream *stream;
2830 if (error)
2831 *error = NULL;
2833 stream = procmime_get_part_as_inputstream(mimeinfo);
2834 if (stream == NULL) {
2835 if (error)
2836 *error = g_error_new_literal(G_FILE_ERROR, -1, _("Could not decode part"));
2837 return NULL;
2840 pixbuf = gdk_pixbuf_new_from_stream(stream, NULL, error);
2841 g_object_unref(stream);
2843 if (error && *error != NULL)
2844 return NULL;
2846 return pixbuf;