2 * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
3 * Copyright (C) 1999-2016 Hiroyuki Yamamoto & The Claws Mail Team
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/>.
21 #include "claws-features.h"
29 #include <glib/gi18n.h>
35 #include <sys/types.h>
41 #include "procheader.h"
42 #include "quoted-printable.h"
49 #include "prefs_common.h"
50 #include "prefs_gtk.h"
51 #include "alertpanel.h"
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);
62 MimeInfo *procmime_mimeinfo_new(void)
66 mimeinfo = g_new0(MimeInfo, 1);
68 mimeinfo->content = MIMECONTENT_EMPTY;
69 mimeinfo->data.filename = NULL;
71 mimeinfo->type = MIMETYPE_UNKNOWN;
72 mimeinfo->encoding_type = ENC_UNKNOWN;
73 mimeinfo->typeparameters = g_hash_table_new(g_str_hash, g_str_equal);
75 mimeinfo->disposition = DISPOSITIONTYPE_UNKNOWN;
76 mimeinfo->dispositionparameters
77 = g_hash_table_new(g_str_hash, g_str_equal);
79 mimeinfo->node = g_node_new(mimeinfo);
84 static gboolean procmime_mimeinfo_parameters_destroy(gpointer key, gpointer value, gpointer user_data)
92 static gchar *forced_charset = NULL;
94 void procmime_force_charset(const gchar *str)
96 g_free(forced_charset);
97 forced_charset = NULL;
99 forced_charset = g_strdup(str);
102 static EncodingType forced_encoding = 0;
104 void procmime_force_encoding(EncodingType encoding)
106 forced_encoding = encoding;
109 static gboolean free_func(GNode *node, gpointer data)
111 MimeInfo *mimeinfo = (MimeInfo *) node->data;
113 switch (mimeinfo->content) {
114 case MIMECONTENT_FILE:
116 claws_unlink(mimeinfo->data.filename);
117 g_free(mimeinfo->data.filename);
120 case MIMECONTENT_MEM:
122 g_free(mimeinfo->data.mem);
127 g_free(mimeinfo->subtype);
128 g_free(mimeinfo->description);
129 g_free(mimeinfo->id);
130 g_free(mimeinfo->location);
132 g_hash_table_foreach_remove(mimeinfo->typeparameters,
133 procmime_mimeinfo_parameters_destroy, NULL);
134 g_hash_table_destroy(mimeinfo->typeparameters);
135 g_hash_table_foreach_remove(mimeinfo->dispositionparameters,
136 procmime_mimeinfo_parameters_destroy, NULL);
137 g_hash_table_destroy(mimeinfo->dispositionparameters);
139 if (mimeinfo->privacy)
140 privacy_free_privacydata(mimeinfo->privacy);
147 void procmime_mimeinfo_free_all(MimeInfo **mimeinfo_ptr)
149 MimeInfo *mimeinfo = *mimeinfo_ptr;
155 node = mimeinfo->node;
156 g_node_traverse(node, G_IN_ORDER, G_TRAVERSE_ALL, -1, free_func, NULL);
158 g_node_destroy(node);
160 *mimeinfo_ptr = NULL;
163 MimeInfo *procmime_mimeinfo_parent(MimeInfo *mimeinfo)
165 cm_return_val_if_fail(mimeinfo != NULL, NULL);
166 cm_return_val_if_fail(mimeinfo->node != NULL, NULL);
168 if (mimeinfo->node->parent == NULL)
170 return (MimeInfo *) mimeinfo->node->parent->data;
173 MimeInfo *procmime_mimeinfo_next(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->children)
179 return (MimeInfo *) mimeinfo->node->children->data;
180 if (mimeinfo->node->next)
181 return (MimeInfo *) mimeinfo->node->next->data;
183 if (mimeinfo->node->parent == NULL)
186 while (mimeinfo->node->parent != NULL) {
187 mimeinfo = (MimeInfo *) mimeinfo->node->parent->data;
188 if (mimeinfo->node->next)
189 return (MimeInfo *) mimeinfo->node->next->data;
195 MimeInfo *procmime_scan_message(MsgInfo *msginfo)
200 filename = procmsg_get_message_file_path(msginfo);
201 if (!filename || !is_file_exist(filename)) {
206 if (!folder_has_parent_of_type(msginfo->folder, F_QUEUE) &&
207 !folder_has_parent_of_type(msginfo->folder, F_DRAFT))
208 mimeinfo = procmime_scan_file(filename);
210 mimeinfo = procmime_scan_queue_file(filename);
216 MimeInfo *procmime_scan_message_short(MsgInfo *msginfo)
221 filename = procmsg_get_message_file_path(msginfo);
222 if (!filename || !is_file_exist(filename)) {
227 if (!folder_has_parent_of_type(msginfo->folder, F_QUEUE) &&
228 !folder_has_parent_of_type(msginfo->folder, F_DRAFT))
229 mimeinfo = procmime_scan_file_short(filename);
231 mimeinfo = procmime_scan_queue_file_short(filename);
239 H_CONTENT_TRANSFER_ENCODING = 0,
241 H_CONTENT_DISPOSITION = 2,
242 H_CONTENT_DESCRIPTION = 3,
246 const gchar *procmime_mimeinfo_get_parameter(MimeInfo *mimeinfo, const gchar *name)
250 cm_return_val_if_fail(mimeinfo != NULL, NULL);
251 cm_return_val_if_fail(name != NULL, NULL);
253 value = g_hash_table_lookup(mimeinfo->dispositionparameters, name);
255 value = g_hash_table_lookup(mimeinfo->typeparameters, name);
260 #define FLUSH_LASTLINE() { \
261 if (*lastline != '\0') { \
263 strretchomp(lastline); \
264 llen = strlen(lastline); \
265 if (lastline[llen-1] == ' ' && !account_signatures_matchlist_str_found(lastline, "%s") && \
266 !(llen == 2 && lastline[1] == ' ' && strchr(prefs_common.quote_chars, lastline[0]))) { \
267 /* this is flowed */ \
269 lastline[llen-1] = '\0'; \
270 if (claws_fputs(lastline, outfp) == EOF) \
273 if (claws_fputs(lastline, outfp) == EOF) \
275 if (claws_fputs("\n", outfp) == EOF) \
279 strcpy(lastline, buf); \
282 gboolean procmime_decode_content(MimeInfo *mimeinfo)
289 gboolean tmp_file = FALSE;
290 gboolean flowed = FALSE;
291 gboolean delsp = FALSE;
292 gboolean err = FALSE;
296 cm_return_val_if_fail(mimeinfo != NULL, FALSE);
298 EncodingType encoding = forced_encoding
300 : mimeinfo->encoding_type;
301 gchar lastline[BUFFSIZE];
302 memset(lastline, 0, BUFFSIZE);
304 if (prefs_common.respect_flowed_format &&
305 mimeinfo->type == MIMETYPE_TEXT &&
306 !strcasecmp(mimeinfo->subtype, "plain")) {
307 if (procmime_mimeinfo_get_parameter(mimeinfo, "format") != NULL &&
308 !strcasecmp(procmime_mimeinfo_get_parameter(mimeinfo, "format"),"flowed"))
311 procmime_mimeinfo_get_parameter(mimeinfo, "delsp") != NULL &&
312 !strcasecmp(procmime_mimeinfo_get_parameter(mimeinfo, "delsp"),"yes"))
317 encoding == ENC_UNKNOWN ||
318 encoding == ENC_BINARY ||
319 encoding == ENC_7BIT ||
324 if (mimeinfo->type == MIMETYPE_MULTIPART || mimeinfo->type == MIMETYPE_MESSAGE)
327 if (mimeinfo->data.filename == NULL)
330 infp = claws_fopen(mimeinfo->data.filename, "rb");
332 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
335 if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
336 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
341 outfp = get_tmpfile_in_dir(get_mime_tmp_dir(), &tmpfilename);
349 readend = mimeinfo->offset + mimeinfo->length;
351 account_signatures_matchlist_create(); /* FLUSH_LASTLINE will use it */
354 if (encoding == ENC_QUOTED_PRINTABLE) {
355 while ((ftell(infp) < readend) && (claws_fgets(buf, sizeof(buf), infp) != NULL)) {
357 len = qp_decode_line(buf);
360 if (claws_fwrite(buf, 1, len, outfp) < len)
368 } else if (encoding == ENC_BASE64) {
369 gchar outbuf[BUFFSIZE];
370 gint len, inlen, inread;
371 gboolean got_error = FALSE;
372 gboolean uncanonicalize = FALSE;
374 gboolean null_bytes = FALSE;
375 gboolean starting = TRUE;
377 if (mimeinfo->type == MIMETYPE_TEXT ||
378 mimeinfo->type == MIMETYPE_MESSAGE) {
379 uncanonicalize = TRUE;
380 tmpfp = my_tmpfile();
382 perror("my_tmpfile");
391 while ((inlen = MIN(readend - ftell(infp), sizeof(buf))) > 0 && !err) {
392 inread = claws_fread(buf, 1, inlen, infp);
393 len = g_base64_decode_step(buf, inlen, outbuf, &state, &save);
394 if (uncanonicalize == TRUE && strlen(outbuf) < len && starting) {
395 uncanonicalize = FALSE;
399 if (((inread != inlen) || len < 0) && !got_error) {
400 g_warning("Bad BASE64 content.");
401 if (claws_fwrite(_("[Error decoding BASE64]\n"),
403 strlen(_("[Error decoding BASE64]\n")),
404 tmpfp) < strlen(_("[Error decoding BASE64]\n")))
405 g_warning("error decoding BASE64");
408 } else if (len >= 0) {
409 /* print out the error message only once
412 /* we won't uncanonicalize, output to outfp directly */
413 if (claws_fwrite(outbuf, sizeof(gchar), len, outfp) < len)
416 if (claws_fwrite(outbuf, sizeof(gchar), len, tmpfp) < len)
423 if (uncanonicalize) {
425 while (claws_fgets(buf, sizeof(buf), tmpfp) != NULL) {
427 if (claws_fputs(buf, outfp) == EOF)
433 } else if (encoding == ENC_X_UUENCODE) {
434 gchar outbuf[BUFFSIZE];
436 gboolean flag = FALSE;
438 while ((ftell(infp) < readend) && (claws_fgets(buf, sizeof(buf), infp) != NULL)) {
439 if (!flag && strncmp(buf,"begin ", 6)) continue;
442 len = fromuutobits(outbuf, buf);
445 g_warning("Bad UUENCODE content (%d)", len);
448 if (claws_fwrite(outbuf, sizeof(gchar), len, outfp) < len)
454 while ((ftell(infp) < readend) && (claws_fgets(buf, sizeof(buf), infp) != NULL)) {
456 if (claws_fputs(buf, outfp) == EOF)
465 g_warning("write error");
471 account_signatures_matchlist_delete();
477 if (g_stat(tmpfilename, &statbuf) < 0) {
478 FILE_OP_ERROR(tmpfilename, "stat");
483 claws_unlink(mimeinfo->data.filename);
484 g_free(mimeinfo->data.filename);
485 mimeinfo->data.filename = tmpfilename;
486 mimeinfo->tmp = TRUE;
487 mimeinfo->offset = 0;
488 mimeinfo->length = statbuf.st_size;
489 mimeinfo->encoding_type = ENC_BINARY;
494 #define B64_LINE_SIZE 57
495 #define B64_BUFFSIZE 77
497 gboolean procmime_encode_content(MimeInfo *mimeinfo, EncodingType encoding)
499 FILE *infp = NULL, *outfp;
503 gboolean err = FALSE;
505 if (mimeinfo->content == MIMECONTENT_EMPTY)
508 if (mimeinfo->encoding_type != ENC_UNKNOWN &&
509 mimeinfo->encoding_type != ENC_BINARY &&
510 mimeinfo->encoding_type != ENC_7BIT &&
511 mimeinfo->encoding_type != ENC_8BIT)
512 if(!procmime_decode_content(mimeinfo))
515 outfp = get_tmpfile_in_dir(get_mime_tmp_dir(), &tmpfilename);
521 if (mimeinfo->content == MIMECONTENT_FILE && mimeinfo->data.filename) {
522 if ((infp = claws_fopen(mimeinfo->data.filename, "rb")) == NULL) {
523 g_warning("Can't open file %s", mimeinfo->data.filename);
527 } else if (mimeinfo->content == MIMECONTENT_MEM) {
528 infp = str_open_as_stream(mimeinfo->data.mem);
535 g_warning("Unknown mimeinfo");
539 if (encoding == ENC_BASE64) {
540 gchar inbuf[B64_LINE_SIZE], *out;
542 gchar *tmp_file = NULL;
544 if (mimeinfo->type == MIMETYPE_TEXT ||
545 mimeinfo->type == MIMETYPE_MESSAGE) {
546 if (mimeinfo->content == MIMECONTENT_FILE) {
547 tmp_file = get_tmp_file();
548 if (canonicalize_file(mimeinfo->data.filename, tmp_file) < 0) {
554 if ((tmp_fp = claws_fopen(tmp_file, "rb")) == NULL) {
555 FILE_OP_ERROR(tmp_file, "claws_fopen");
556 claws_unlink(tmp_file);
563 gchar *out = canonicalize_str(mimeinfo->data.mem);
565 infp = str_open_as_stream(out);
575 while ((len = claws_fread(inbuf, sizeof(gchar),
576 B64_LINE_SIZE, tmp_fp))
578 out = g_base64_encode(inbuf, B64_LINE_SIZE);
579 if (claws_fputs(out, outfp) == EOF)
582 if (claws_fputc('\n', outfp) == EOF)
585 if (len > 0 && claws_feof(tmp_fp)) {
586 out = g_base64_encode(inbuf, len);
587 if (claws_fputs(out, outfp) == EOF)
590 if (claws_fputc('\n', outfp) == EOF)
595 claws_fclose(tmp_fp);
596 claws_unlink(tmp_file);
599 } else if (encoding == ENC_QUOTED_PRINTABLE) {
600 gchar inbuf[BUFFSIZE], outbuf[BUFFSIZE * 4];
602 while (claws_fgets(inbuf, sizeof(inbuf), infp) != NULL) {
603 qp_encode_line(outbuf, inbuf);
605 if (!strncmp("From ", outbuf, sizeof("From ")-1)) {
606 gchar *tmpbuf = outbuf;
608 tmpbuf += sizeof("From ")-1;
610 if (claws_fputs("=46rom ", outfp) == EOF)
612 if (claws_fputs(tmpbuf, outfp) == EOF)
615 if (claws_fputs(outbuf, outfp) == EOF)
622 while (claws_fgets(buf, sizeof(buf), infp) != NULL) {
624 if (claws_fputs(buf, outfp) == EOF)
635 if (mimeinfo->content == MIMECONTENT_FILE) {
636 if (mimeinfo->tmp && (mimeinfo->data.filename != NULL))
637 claws_unlink(mimeinfo->data.filename);
638 g_free(mimeinfo->data.filename);
639 } else if (mimeinfo->content == MIMECONTENT_MEM) {
640 if (mimeinfo->tmp && (mimeinfo->data.mem != NULL))
641 g_free(mimeinfo->data.mem);
644 if (g_stat(tmpfilename, &statbuf) < 0) {
645 FILE_OP_ERROR(tmpfilename, "stat");
648 mimeinfo->content = MIMECONTENT_FILE;
649 mimeinfo->data.filename = tmpfilename;
650 mimeinfo->tmp = TRUE;
651 mimeinfo->offset = 0;
652 mimeinfo->length = statbuf.st_size;
653 mimeinfo->encoding_type = encoding;
658 static gint procmime_get_part_to_stream(FILE *outfp, MimeInfo *mimeinfo)
662 gint restlength, readlength;
663 gint saved_errno = 0;
665 cm_return_val_if_fail(outfp != NULL, -1);
666 cm_return_val_if_fail(mimeinfo != NULL, -1);
668 if (mimeinfo->encoding_type != ENC_BINARY && !procmime_decode_content(mimeinfo))
671 if ((infp = claws_fopen(mimeinfo->data.filename, "rb")) == NULL) {
673 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
674 return -(saved_errno);
676 if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
678 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
680 return -(saved_errno);
683 restlength = mimeinfo->length;
685 while ((restlength > 0) && ((readlength = claws_fread(buf, 1, restlength > BUFFSIZE ? BUFFSIZE : restlength, infp)) > 0)) {
686 if (claws_fwrite(buf, 1, readlength, outfp) != readlength) {
689 return -(saved_errno);
691 restlength -= readlength;
700 gint procmime_get_part(const gchar *outfile, MimeInfo *mimeinfo)
704 gint saved_errno = 0;
706 cm_return_val_if_fail(outfile != NULL, -1);
708 if ((outfp = claws_fopen(outfile, "wb")) == NULL) {
710 FILE_OP_ERROR(outfile, "claws_fopen");
711 return -(saved_errno);
714 result = procmime_get_part_to_stream(outfp, mimeinfo);
716 if (claws_fclose(outfp) == EOF) {
718 FILE_OP_ERROR(outfile, "claws_fclose");
719 claws_unlink(outfile);
720 return -(saved_errno);
726 gboolean procmime_scan_text_content(MimeInfo *mimeinfo,
727 gboolean (*scan_callback)(const gchar *str, gpointer cb_data),
731 const gchar *src_codeset;
732 gboolean conv_fail = FALSE;
735 gboolean scan_ret = FALSE;
736 gchar *tmpfile = NULL;
739 cm_return_val_if_fail(mimeinfo != NULL, TRUE);
740 cm_return_val_if_fail(scan_callback != NULL, TRUE);
742 if (!procmime_decode_content(mimeinfo))
746 tmpfp = fmemopen(NULL, mimeinfo->length * 2, "w+");
748 tmpfile = procmime_get_tmp_file_name(mimeinfo);
749 if (tmpfile == NULL) {
750 g_warning("no filename\n");
754 tmpfp = claws_fopen(tmpfile, "w+");
759 FILE_OP_ERROR(tmpfile, "open");
763 if ((r = procmime_get_part_to_stream(tmpfp, mimeinfo)) < 0) {
764 g_warning("procmime_get_part_to_stream error %d\n", r);
769 src_codeset = forced_charset
771 procmime_mimeinfo_get_parameter(mimeinfo, "charset");
773 /* use supersets transparently when possible */
774 if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_ISO_8859_1))
775 src_codeset = CS_WINDOWS_1252;
776 else if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_X_GBK))
777 src_codeset = CS_GB18030;
778 else if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_GBK))
779 src_codeset = CS_GB18030;
780 else if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_GB2312))
781 src_codeset = CS_GB18030;
782 else if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_X_VIET_VPS))
783 src_codeset = CS_WINDOWS_874;
785 if (mimeinfo->type == MIMETYPE_TEXT && !g_ascii_strcasecmp(mimeinfo->subtype, "html")) {
786 SC_HTMLParser *parser;
789 conv = conv_code_converter_new(src_codeset);
790 parser = sc_html_parser_new(tmpfp, conv);
791 while ((str = sc_html_parse(parser)) != NULL) {
792 if ((scan_ret = scan_callback(str, cb_data)) == TRUE)
795 sc_html_parser_destroy(parser);
796 conv_code_converter_destroy(conv);
797 } else if (mimeinfo->type == MIMETYPE_TEXT && !g_ascii_strcasecmp(mimeinfo->subtype, "enriched")) {
801 conv = conv_code_converter_new(src_codeset);
802 parser = ertf_parser_new(tmpfp, conv);
803 while ((str = ertf_parse(parser)) != NULL) {
804 if ((scan_ret = scan_callback(str, cb_data)) == TRUE)
807 ertf_parser_destroy(parser);
808 conv_code_converter_destroy(conv);
809 } else if (mimeinfo->type == MIMETYPE_TEXT && mimeinfo->disposition != DISPOSITIONTYPE_ATTACHMENT) {
810 while (claws_fgets(buf, sizeof(buf), tmpfp) != NULL) {
811 str = conv_codeset_strdup(buf, src_codeset, CS_UTF_8);
813 if ((scan_ret = scan_callback(str, cb_data)) == TRUE) {
820 if ((scan_ret = scan_callback(buf, cb_data)) == TRUE)
827 g_warning("procmime_get_text_content(): Code conversion failed.");
832 claws_unlink(tmpfile);
839 static gboolean scan_fputs_cb(const gchar *str, gpointer fp)
841 if (claws_fputs(str, (FILE *)fp) == EOF)
847 FILE *procmime_get_text_content(MimeInfo *mimeinfo)
852 if ((outfp = my_tmpfile()) == NULL) {
853 perror("my_tmpfile");
857 err = procmime_scan_text_content(mimeinfo, scan_fputs_cb, outfp);
868 FILE *procmime_get_binary_content(MimeInfo *mimeinfo)
872 gchar *tmpfile = NULL;
875 cm_return_val_if_fail(mimeinfo != NULL, NULL);
877 if (!procmime_decode_content(mimeinfo))
881 outfp = fmemopen(NULL, mimeinfo->length * 2, "w+");
883 tmpfile = procmime_get_tmp_file_name(mimeinfo);
884 if (tmpfile == NULL) {
885 g_warning("no filename\n");
889 outfp = claws_fopen(tmpfile, "w+");
891 if (tmpfile != NULL) {
897 if (procmime_get_part_to_stream(outfp, mimeinfo) < 0) {
904 /* search the first text part of (multipart) MIME message,
905 decode, convert it and output to outfp. */
906 FILE *procmime_get_first_text_content(MsgInfo *msginfo)
909 MimeInfo *mimeinfo, *partinfo;
910 gboolean empty_ok = FALSE, short_scan = TRUE;
912 cm_return_val_if_fail(msginfo != NULL, NULL);
914 /* first we try to short-scan (for speed), refusing empty parts */
917 mimeinfo = procmime_scan_message_short(msginfo);
919 mimeinfo = procmime_scan_message(msginfo);
920 if (!mimeinfo) return NULL;
923 while (partinfo && (partinfo->type != MIMETYPE_TEXT ||
924 (partinfo->length == 0 && !empty_ok))) {
925 partinfo = procmime_mimeinfo_next(partinfo);
928 outfp = procmime_get_text_content(partinfo);
929 else if (!empty_ok && short_scan) {
930 /* if short scan didn't find a non-empty part, rescan
931 * fully for non-empty parts
934 procmime_mimeinfo_free_all(&mimeinfo);
936 } else if (!empty_ok && !short_scan) {
937 /* if full scan didn't find a non-empty part, rescan
938 * accepting empty parts
941 procmime_mimeinfo_free_all(&mimeinfo);
944 procmime_mimeinfo_free_all(&mimeinfo);
950 static gboolean find_encrypted_func(GNode *node, gpointer data)
952 MimeInfo *mimeinfo = (MimeInfo *) node->data;
953 MimeInfo **encinfo = (MimeInfo **) data;
955 if (privacy_mimeinfo_is_encrypted(mimeinfo)) {
963 static MimeInfo *find_encrypted_part(MimeInfo *rootinfo)
965 MimeInfo *encinfo = NULL;
967 g_node_traverse(rootinfo->node, G_IN_ORDER, G_TRAVERSE_ALL, -1,
968 find_encrypted_func, &encinfo);
973 /* search the first encrypted text part of (multipart) MIME message,
974 decode, convert it and output to outfp. */
975 FILE *procmime_get_first_encrypted_text_content(MsgInfo *msginfo)
978 MimeInfo *mimeinfo, *partinfo, *encinfo;
980 cm_return_val_if_fail(msginfo != NULL, NULL);
982 mimeinfo = procmime_scan_message(msginfo);
988 if ((encinfo = find_encrypted_part(partinfo)) != NULL) {
989 debug_print("decrypting message part\n");
990 if (privacy_mimeinfo_decrypt(encinfo) < 0) {
991 alertpanel_error(_("Couldn't decrypt: %s"),
992 privacy_get_error());
997 while (partinfo && partinfo->type != MIMETYPE_TEXT) {
998 partinfo = procmime_mimeinfo_next(partinfo);
999 if (privacy_mimeinfo_is_signed(partinfo))
1000 procmsg_msginfo_set_flags(msginfo, 0, MSG_SIGNED);
1004 outfp = procmime_get_text_content(partinfo);
1006 procmime_mimeinfo_free_all(&mimeinfo);
1011 gboolean procmime_msginfo_is_encrypted(MsgInfo *msginfo)
1013 MimeInfo *mimeinfo, *partinfo;
1014 gboolean result = FALSE;
1016 cm_return_val_if_fail(msginfo != NULL, FALSE);
1018 mimeinfo = procmime_scan_message(msginfo);
1023 partinfo = mimeinfo;
1024 result = (find_encrypted_part(partinfo) != NULL);
1025 procmime_mimeinfo_free_all(&mimeinfo);
1030 gchar *procmime_get_tmp_file_name(MimeInfo *mimeinfo)
1032 static guint32 id = 0;
1037 cm_return_val_if_fail(mimeinfo != NULL, NULL);
1039 g_snprintf(f_prefix, sizeof(f_prefix), "%08x.", id++);
1041 if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
1042 base = g_strdup("mimetmp.html");
1044 const gchar *basetmp;
1046 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
1047 if (basetmp == NULL)
1048 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
1049 if (basetmp == NULL)
1050 basetmp = "mimetmp";
1051 basetmp = g_path_get_basename(basetmp);
1052 if (*basetmp == '\0')
1053 basetmp = g_strdup("mimetmp");
1054 base = conv_filename_from_utf8(basetmp);
1055 g_free((gchar*)basetmp);
1056 subst_for_shellsafe_filename(base);
1059 filename = g_strconcat(get_mime_tmp_dir(), G_DIR_SEPARATOR_S,
1060 f_prefix, base, NULL);
1067 static GList *mime_type_list = NULL;
1069 gchar *procmime_get_mime_type(const gchar *filename)
1075 static GHashTable *mime_type_table = NULL;
1076 MimeType *mime_type;
1078 if (!mime_type_table) {
1079 mime_type_table = procmime_get_mime_type_table();
1080 if (!mime_type_table) return NULL;
1084 if (filename == NULL)
1087 base = g_path_get_basename(filename);
1088 if ((p = strrchr(base, '.')) != NULL)
1089 ext = g_utf8_strdown(p + 1, -1);
1091 ext = g_utf8_strdown(base, -1);
1095 mime_type = g_hash_table_lookup(mime_type_table, ext);
1099 str = g_strconcat(mime_type->type, "/", mime_type->sub_type,
1101 debug_print("got type %s for %s\n", str, ext);
1108 gchar *str = get_content_type_from_registry_with_ext(ext);
1115 static guint procmime_str_hash(gconstpointer gptr)
1117 guint hash_result = 0;
1120 for (str = gptr; str && *str; str++) {
1121 if (isupper(*str)) hash_result += (*str + ' ');
1122 else hash_result += *str;
1128 static gint procmime_str_equal(gconstpointer gptr1, gconstpointer gptr2)
1130 const char *str1 = gptr1;
1131 const char *str2 = gptr2;
1133 return !g_utf8_collate(str1, str2);
1136 static GHashTable *procmime_get_mime_type_table(void)
1138 GHashTable *table = NULL;
1140 MimeType *mime_type;
1143 if (!mime_type_list) {
1144 mime_type_list = procmime_get_mime_type_list();
1145 if (!mime_type_list) return NULL;
1148 table = g_hash_table_new(procmime_str_hash, procmime_str_equal);
1150 for (cur = mime_type_list; cur != NULL; cur = cur->next) {
1154 mime_type = (MimeType *)cur->data;
1156 if (!mime_type->extension) continue;
1158 exts = g_strsplit(mime_type->extension, " ", 16);
1159 for (i = 0; exts[i] != NULL; i++) {
1160 /* Don't overwrite previously inserted extension */
1161 if (!g_hash_table_lookup(table, exts[i])) {
1162 key = g_strdup(exts[i]);
1163 g_hash_table_insert(table, key, mime_type);
1172 GList *procmime_get_mime_type_list(void)
1176 gchar buf[BUFFSIZE];
1179 MimeType *mime_type;
1180 gboolean fp_is_glob_file = TRUE;
1183 return mime_type_list;
1185 #if defined(__NetBSD__) || defined(__OpenBSD__) || defined(__FreeBSD__)
1186 if ((fp = claws_fopen(DATAROOTDIR "/mime/globs", "rb")) == NULL)
1188 if ((fp = claws_fopen("/usr/share/mime/globs", "rb")) == NULL)
1191 fp_is_glob_file = FALSE;
1192 if ((fp = claws_fopen("/etc/mime.types", "rb")) == NULL) {
1193 if ((fp = claws_fopen(SYSCONFDIR "/mime.types", "rb"))
1195 FILE_OP_ERROR(SYSCONFDIR "/mime.types",
1202 while (claws_fgets(buf, sizeof(buf), fp) != NULL) {
1203 p = strchr(buf, '#');
1209 if (fp_is_glob_file) {
1210 while (*p && !g_ascii_isspace(*p) && (*p!=':')) p++;
1212 while (*p && !g_ascii_isspace(*p)) p++;
1219 delim = strchr(buf, '/');
1220 if (delim == NULL) continue;
1223 mime_type = g_new(MimeType, 1);
1224 mime_type->type = g_strdup(buf);
1225 mime_type->sub_type = g_strdup(delim + 1);
1227 if (fp_is_glob_file) {
1228 while (*p && (g_ascii_isspace(*p)||(*p=='*')||(*p=='.'))) p++;
1230 while (*p && g_ascii_isspace(*p)) p++;
1234 mime_type->extension = g_utf8_strdown(p, -1);
1236 mime_type->extension = NULL;
1238 list = g_list_append(list, mime_type);
1244 g_warning("Can't read mime.types");
1249 EncodingType procmime_get_encoding_for_charset(const gchar *charset)
1253 else if (!g_ascii_strncasecmp(charset, "ISO-2022-", 9) ||
1254 !g_ascii_strcasecmp(charset, "US-ASCII"))
1256 else if (!g_ascii_strcasecmp(charset, "ISO-8859-5") ||
1257 !g_ascii_strncasecmp(charset, "KOI8-", 5) ||
1258 !g_ascii_strcasecmp(charset, "X-MAC-CYRILLIC") ||
1259 !g_ascii_strcasecmp(charset, "MAC-CYRILLIC") ||
1260 !g_ascii_strcasecmp(charset, "Windows-1251"))
1262 else if (!g_ascii_strncasecmp(charset, "ISO-8859-", 9))
1263 return ENC_QUOTED_PRINTABLE;
1264 else if (!g_ascii_strncasecmp(charset, "UTF-8", 5))
1265 return ENC_QUOTED_PRINTABLE;
1270 EncodingType procmime_get_encoding_for_text_file(const gchar *file, gboolean *has_binary)
1273 guchar buf[BUFFSIZE];
1275 size_t octet_chars = 0;
1276 size_t total_len = 0;
1277 gfloat octet_percentage;
1278 gboolean force_b64 = FALSE;
1280 if ((fp = claws_fopen(file, "rb")) == NULL) {
1281 FILE_OP_ERROR(file, "claws_fopen");
1285 while ((len = claws_fread(buf, sizeof(guchar), sizeof(buf), fp)) > 0) {
1289 for (p = buf, i = 0; i < len; ++p, ++i) {
1303 octet_percentage = (gfloat)octet_chars / (gfloat)total_len;
1305 octet_percentage = 0.0;
1307 debug_print("procmime_get_encoding_for_text_file(): "
1308 "8bit chars: %zd / %zd (%f%%)\n", octet_chars, total_len,
1309 100.0 * octet_percentage);
1311 if (octet_percentage > 0.20 || force_b64) {
1312 debug_print("using BASE64\n");
1314 } else if (octet_chars > 0) {
1315 debug_print("using quoted-printable\n");
1316 return ENC_QUOTED_PRINTABLE;
1318 debug_print("using 7bit\n");
1323 struct EncodingTable
1326 EncodingType enc_type;
1329 struct EncodingTable encoding_table[] = {
1332 {"binary", ENC_BINARY},
1333 {"quoted-printable", ENC_QUOTED_PRINTABLE},
1334 {"base64", ENC_BASE64},
1335 {"x-uuencode", ENC_UNKNOWN},
1336 {NULL, ENC_UNKNOWN},
1339 const gchar *procmime_get_encoding_str(EncodingType encoding)
1341 struct EncodingTable *enc_table;
1343 for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1344 if (enc_table->enc_type == encoding)
1345 return enc_table->str;
1350 /* --- NEW MIME STUFF --- */
1357 static struct TypeTable mime_type_table[] = {
1358 {"text", MIMETYPE_TEXT},
1359 {"image", MIMETYPE_IMAGE},
1360 {"audio", MIMETYPE_AUDIO},
1361 {"video", MIMETYPE_VIDEO},
1362 {"application", MIMETYPE_APPLICATION},
1363 {"message", MIMETYPE_MESSAGE},
1364 {"multipart", MIMETYPE_MULTIPART},
1368 const gchar *procmime_get_media_type_str(MimeMediaType type)
1370 struct TypeTable *type_table;
1372 for (type_table = mime_type_table; type_table->str != NULL; type_table++) {
1373 if (type_table->type == type)
1374 return type_table->str;
1379 MimeMediaType procmime_get_media_type(const gchar *str)
1381 struct TypeTable *typetablearray;
1383 for (typetablearray = mime_type_table; typetablearray->str != NULL; typetablearray++)
1384 if (g_ascii_strncasecmp(str, typetablearray->str, strlen(typetablearray->str)) == 0)
1385 return typetablearray->type;
1387 return MIMETYPE_UNKNOWN;
1391 *\brief Safe wrapper for content type string.
1393 *\return const gchar * Pointer to content type string.
1395 gchar *procmime_get_content_type_str(MimeMediaType type,
1396 const char *subtype)
1398 const gchar *type_str = NULL;
1400 if (subtype == NULL || !(type_str = procmime_get_media_type_str(type)))
1401 return g_strdup("unknown");
1402 return g_strdup_printf("%s/%s", type_str, subtype);
1405 static int procmime_parse_mimepart(MimeInfo *parent,
1406 gchar *content_type,
1407 gchar *content_encoding,
1408 gchar *content_description,
1410 gchar *content_disposition,
1411 gchar *content_location,
1412 const gchar *original_msgid,
1413 const gchar *disposition_notification_hdr,
1414 const gchar *filename,
1417 gboolean short_scan);
1419 static void procmime_parse_message_rfc822(MimeInfo *mimeinfo, gboolean short_scan)
1421 HeaderEntry hentry[] = {{"Content-Type:", NULL, TRUE},
1422 {"Content-Transfer-Encoding:",
1424 {"Content-Description:",
1428 {"Content-Disposition:",
1430 {"Content-Location:",
1434 {"Original-Message-ID:",
1438 {NULL, NULL, FALSE}};
1439 guint content_start, i;
1444 procmime_decode_content(mimeinfo);
1446 fp = claws_fopen(mimeinfo->data.filename, "rb");
1448 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
1451 if (fseek(fp, mimeinfo->offset, SEEK_SET) < 0) {
1452 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
1456 procheader_get_header_fields(fp, hentry);
1457 if (hentry[0].body != NULL) {
1458 tmp = conv_unmime_header(hentry[0].body, NULL, FALSE);
1459 g_free(hentry[0].body);
1460 hentry[0].body = tmp;
1462 if (hentry[2].body != NULL) {
1463 tmp = conv_unmime_header(hentry[2].body, NULL, FALSE);
1464 g_free(hentry[2].body);
1465 hentry[2].body = tmp;
1467 if (hentry[4].body != NULL) {
1468 tmp = conv_unmime_header(hentry[4].body, NULL, FALSE);
1469 g_free(hentry[4].body);
1470 hentry[4].body = tmp;
1472 if (hentry[5].body != NULL) {
1473 tmp = conv_unmime_header(hentry[5].body, NULL, FALSE);
1474 g_free(hentry[5].body);
1475 hentry[5].body = tmp;
1477 if (hentry[7].body != NULL) {
1478 tmp = conv_unmime_header(hentry[7].body, NULL, FALSE);
1479 g_free(hentry[7].body);
1480 hentry[7].body = tmp;
1482 if (hentry[8].body != NULL) {
1483 tmp = conv_unmime_header(hentry[8].body, NULL, FALSE);
1484 g_free(hentry[8].body);
1485 hentry[8].body = tmp;
1488 content_start = ftell(fp);
1491 len = mimeinfo->length - (content_start - mimeinfo->offset);
1494 procmime_parse_mimepart(mimeinfo,
1495 hentry[0].body, hentry[1].body,
1496 hentry[2].body, hentry[3].body,
1497 hentry[4].body, hentry[5].body,
1498 hentry[7].body, hentry[8].body,
1499 mimeinfo->data.filename, content_start,
1502 for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1503 g_free(hentry[i].body);
1504 hentry[i].body = NULL;
1508 static void procmime_parse_disposition_notification(MimeInfo *mimeinfo,
1509 const gchar *original_msgid, const gchar *disposition_notification_hdr,
1510 gboolean short_scan)
1512 HeaderEntry hentry[] = {{"Original-Message-ID:", NULL, TRUE},
1513 {"Disposition:", NULL, TRUE},
1514 {NULL, NULL, FALSE}};
1517 gchar *orig_msg_id = NULL;
1520 procmime_decode_content(mimeinfo);
1522 debug_print("parse disposition notification\n");
1523 fp = claws_fopen(mimeinfo->data.filename, "rb");
1525 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
1528 if (fseek(fp, mimeinfo->offset, SEEK_SET) < 0) {
1529 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
1534 if (original_msgid && disposition_notification_hdr) {
1535 hentry[0].body = g_strdup(original_msgid);
1536 hentry[1].body = g_strdup(disposition_notification_hdr);
1538 procheader_get_header_fields(fp, hentry);
1543 if (!hentry[0].body || !hentry[1].body) {
1544 debug_print("MsgId %s, Disp %s\n",
1545 hentry[0].body ? hentry[0].body:"(nil)",
1546 hentry[1].body ? hentry[1].body:"(nil)");
1550 orig_msg_id = g_strdup(hentry[0].body);
1551 disp = g_strdup(hentry[1].body);
1553 extract_parenthesis(orig_msg_id, '<', '>');
1554 remove_space(orig_msg_id);
1556 if (strstr(disp, "displayed")) {
1557 /* find sent message, if possible */
1558 MsgInfo *info = NULL;
1560 debug_print("%s has been displayed.\n", orig_msg_id);
1561 for (flist = folder_get_list(); flist != NULL; flist = g_list_next(flist)) {
1562 FolderItem *outbox = ((Folder *)(flist->data))->outbox;
1564 debug_print("skipping folder with no outbox...\n");
1567 info = folder_item_get_msginfo_by_msgid(outbox, orig_msg_id);
1568 debug_print("%s %s in %s\n", info?"found":"didn't find", orig_msg_id, outbox->path);
1570 procmsg_msginfo_set_flags(info, MSG_RETRCPT_GOT, 0);
1571 procmsg_msginfo_free(&info);
1575 g_free(orig_msg_id);
1578 for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1579 g_free(hentry[i].body);
1580 hentry[i].body = NULL;
1584 #define GET_HEADERS() { \
1585 procheader_get_header_fields(fp, hentry); \
1586 if (hentry[0].body != NULL) { \
1587 tmp = conv_unmime_header(hentry[0].body, NULL, FALSE); \
1588 g_free(hentry[0].body); \
1589 hentry[0].body = tmp; \
1591 if (hentry[2].body != NULL) { \
1592 tmp = conv_unmime_header(hentry[2].body, NULL, FALSE); \
1593 g_free(hentry[2].body); \
1594 hentry[2].body = tmp; \
1596 if (hentry[4].body != NULL) { \
1597 tmp = conv_unmime_header(hentry[4].body, NULL, FALSE); \
1598 g_free(hentry[4].body); \
1599 hentry[4].body = tmp; \
1601 if (hentry[5].body != NULL) { \
1602 tmp = conv_unmime_header(hentry[5].body, NULL, FALSE); \
1603 g_free(hentry[5].body); \
1604 hentry[5].body = tmp; \
1606 if (hentry[6].body != NULL) { \
1607 tmp = conv_unmime_header(hentry[6].body, NULL, FALSE); \
1608 g_free(hentry[6].body); \
1609 hentry[6].body = tmp; \
1611 if (hentry[7].body != NULL) { \
1612 tmp = conv_unmime_header(hentry[7].body, NULL, FALSE); \
1613 g_free(hentry[7].body); \
1614 hentry[7].body = tmp; \
1618 static void procmime_parse_multipart(MimeInfo *mimeinfo, gboolean short_scan)
1620 HeaderEntry hentry[] = {{"Content-Type:", NULL, TRUE},
1621 {"Content-Transfer-Encoding:",
1623 {"Content-Description:",
1627 {"Content-Disposition:",
1629 {"Content-Location:",
1631 {"Original-Message-ID:",
1635 {NULL, NULL, FALSE}};
1638 gint boundary_len = 0, lastoffset = -1, i;
1639 gchar buf[BUFFSIZE];
1642 gboolean start_found = FALSE;
1643 gboolean end_found = FALSE;
1645 boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
1648 boundary_len = strlen(boundary);
1650 procmime_decode_content(mimeinfo);
1652 fp = claws_fopen(mimeinfo->data.filename, "rb");
1654 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
1658 if (fseek(fp, mimeinfo->offset, SEEK_SET) < 0) {
1659 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
1664 while (claws_fgets(buf, sizeof(buf), fp) != NULL && result == 0) {
1665 if (ftell(fp) - 1 > (mimeinfo->offset + mimeinfo->length))
1668 if (IS_BOUNDARY(buf, boundary, boundary_len)) {
1671 if (lastoffset != -1) {
1672 gint len = (ftell(fp) - strlen(buf)) - lastoffset - 1;
1675 result = procmime_parse_mimepart(mimeinfo,
1676 hentry[0].body, hentry[1].body,
1677 hentry[2].body, hentry[3].body,
1678 hentry[4].body, hentry[5].body,
1679 hentry[6].body, hentry[7].body,
1680 mimeinfo->data.filename, lastoffset,
1682 if (result == 1 && short_scan)
1687 if (buf[2 + boundary_len] == '-' &&
1688 buf[2 + boundary_len + 1] == '-') {
1692 for (i = 0; i < (sizeof hentry / sizeof hentry[0]) ; i++) {
1693 g_free(hentry[i].body);
1694 hentry[i].body = NULL;
1697 lastoffset = ftell(fp);
1701 if (start_found && !end_found && lastoffset != -1) {
1702 gint len = (ftell(fp) - strlen(buf)) - lastoffset - 1;
1705 result = procmime_parse_mimepart(mimeinfo,
1706 hentry[0].body, hentry[1].body,
1707 hentry[2].body, hentry[3].body,
1708 hentry[4].body, hentry[5].body,
1709 hentry[6].body, hentry[7].body,
1710 mimeinfo->data.filename, lastoffset,
1713 mimeinfo->broken = TRUE;
1716 for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1717 g_free(hentry[i].body);
1718 hentry[i].body = NULL;
1723 static void parse_parameters(const gchar *parameters, GHashTable *table)
1725 gchar *params, *param, *next;
1726 GSList *convlist = NULL, *concatlist = NULL, *cur;
1728 params = g_strdup(parameters);
1731 for (; next != NULL; param = next) {
1732 gchar *attribute, *value, *tmp, *down_attr, *orig_down_attr;
1734 gboolean convert = FALSE;
1736 next = strchr_with_skip_quote(param, '"', ';');
1745 value = strchr(attribute, '=');
1751 while (value[0] != '\0' && value[0] == ' ')
1754 down_attr = g_utf8_strdown(attribute, -1);
1755 orig_down_attr = down_attr;
1757 len = down_attr ? strlen(down_attr):0;
1758 if (len > 0 && down_attr[len - 1] == '*') {
1759 gchar *srcpos, *dstpos, *endpos;
1762 down_attr[len - 1] = '\0';
1766 endpos = value + strlen(value);
1767 while (srcpos < endpos) {
1773 if (!get_hex_value(&dstvalue, srcpos[1], srcpos[2]))
1783 if (value[0] == '"')
1784 extract_quote(value, '"');
1786 if (value[0] == '"')
1787 extract_quote(value, '"');
1788 else if ((tmp = strchr(value, ' ')) != NULL)
1793 while (down_attr[0] == ' ')
1795 while (down_attr[strlen(down_attr)-1] == ' ')
1796 down_attr[strlen(down_attr)-1] = '\0';
1799 while (value[0] != '\0' && value[0] == ' ')
1801 while (value[strlen(value)-1] == ' ')
1802 value[strlen(value)-1] = '\0';
1804 if (down_attr && strrchr(down_attr, '*') != NULL) {
1807 tmpattr = g_strdup(down_attr);
1808 tmp = strrchr(tmpattr, '*');
1811 if ((tmp[1] == '0') && (tmp[2] == '\0') &&
1812 (g_slist_find_custom(concatlist, down_attr, (GCompareFunc)g_strcmp0) == NULL))
1813 concatlist = g_slist_prepend(concatlist, g_strdup(tmpattr));
1815 if (convert && (g_slist_find_custom(convlist, tmpattr, (GCompareFunc)g_strcmp0) == NULL))
1816 convlist = g_slist_prepend(convlist, g_strdup(tmpattr));
1819 } else if (convert) {
1820 if (g_slist_find_custom(convlist, down_attr, (GCompareFunc)g_strcmp0) == NULL)
1821 convlist = g_slist_prepend(convlist, g_strdup(down_attr));
1824 if (g_hash_table_lookup(table, down_attr) == NULL)
1825 g_hash_table_insert(table, g_strdup(down_attr), g_strdup(value));
1826 g_free(orig_down_attr);
1829 for (cur = concatlist; cur != NULL; cur = g_slist_next(cur)) {
1830 gchar *attribute, *attrwnum, *partvalue;
1834 attribute = (gchar *) cur->data;
1835 value = g_string_sized_new(64);
1837 attrwnum = g_strdup_printf("%s*%d", attribute, n);
1838 while ((partvalue = g_hash_table_lookup(table, attrwnum)) != NULL) {
1839 g_string_append(value, partvalue);
1841 g_hash_table_remove(table, attrwnum);
1844 attrwnum = g_strdup_printf("%s*%d", attribute, n);
1848 g_hash_table_insert(table, g_strdup(attribute), g_strdup(value->str));
1849 g_string_free(value, TRUE);
1851 slist_free_strings_full(concatlist);
1853 for (cur = convlist; cur != NULL; cur = g_slist_next(cur)) {
1854 gchar *attribute, *key, *value;
1855 gchar *charset, *lang, *oldvalue, *newvalue;
1857 attribute = (gchar *) cur->data;
1858 if (!g_hash_table_lookup_extended(
1859 table, attribute, (gpointer *)(gchar *) &key, (gpointer *)(gchar *) &value))
1863 if (charset == NULL)
1865 lang = strchr(charset, '\'');
1870 oldvalue = strchr(lang, '\'');
1871 if (oldvalue == NULL)
1876 newvalue = conv_codeset_strdup(oldvalue, charset, CS_UTF_8);
1878 g_hash_table_remove(table, attribute);
1882 g_hash_table_insert(table, g_strdup(attribute), newvalue);
1884 slist_free_strings_full(convlist);
1889 static void procmime_parse_content_type(const gchar *content_type, MimeInfo *mimeinfo)
1891 cm_return_if_fail(content_type != NULL);
1892 cm_return_if_fail(mimeinfo != NULL);
1894 /* RFC 2045, page 13 says that the mime subtype is MANDATORY;
1895 * if it's not available we use the default Content-Type */
1896 if ((content_type[0] == '\0') || (strchr(content_type, '/') == NULL)) {
1897 mimeinfo->type = MIMETYPE_TEXT;
1898 mimeinfo->subtype = g_strdup("plain");
1899 if (g_hash_table_lookup(mimeinfo->typeparameters,
1900 "charset") == NULL) {
1901 g_hash_table_insert(mimeinfo->typeparameters,
1902 g_strdup("charset"),
1904 conv_get_locale_charset_str_no_utf8()));
1907 gchar *type, *subtype, *params;
1909 type = g_strdup(content_type);
1910 subtype = strchr(type, '/') + 1;
1911 *(subtype - 1) = '\0';
1912 if ((params = strchr(subtype, ';')) != NULL) {
1917 mimeinfo->type = procmime_get_media_type(type);
1918 mimeinfo->subtype = g_strstrip(g_strdup(subtype));
1920 /* Get mimeinfo->typeparameters */
1922 parse_parameters(params, mimeinfo->typeparameters);
1928 static void procmime_parse_content_disposition(const gchar *content_disposition, MimeInfo *mimeinfo)
1930 gchar *tmp, *params;
1932 cm_return_if_fail(content_disposition != NULL);
1933 cm_return_if_fail(mimeinfo != NULL);
1935 tmp = g_strdup(content_disposition);
1936 if ((params = strchr(tmp, ';')) != NULL) {
1942 if (!g_ascii_strcasecmp(tmp, "inline"))
1943 mimeinfo->disposition = DISPOSITIONTYPE_INLINE;
1944 else if (!g_ascii_strcasecmp(tmp, "attachment"))
1945 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1947 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1950 parse_parameters(params, mimeinfo->dispositionparameters);
1956 static void procmime_parse_content_encoding(const gchar *content_encoding, MimeInfo *mimeinfo)
1958 struct EncodingTable *enc_table;
1960 for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1961 if (g_ascii_strcasecmp(enc_table->str, content_encoding) == 0) {
1962 mimeinfo->encoding_type = enc_table->enc_type;
1966 mimeinfo->encoding_type = ENC_UNKNOWN;
1970 static GSList *registered_parsers = NULL;
1972 static MimeParser *procmime_get_mimeparser_for_type(MimeMediaType type, const gchar *sub_type)
1975 for (cur = registered_parsers; cur; cur = cur->next) {
1976 MimeParser *parser = (MimeParser *)cur->data;
1977 if (parser->type == type && !strcmp2(parser->sub_type, sub_type))
1983 void procmime_mimeparser_register(MimeParser *parser)
1985 if (!procmime_get_mimeparser_for_type(parser->type, parser->sub_type))
1986 registered_parsers = g_slist_append(registered_parsers, parser);
1990 void procmime_mimeparser_unregister(MimeParser *parser)
1992 registered_parsers = g_slist_remove(registered_parsers, parser);
1995 static gboolean procmime_mimeparser_parse(MimeParser *parser, MimeInfo *mimeinfo)
1997 cm_return_val_if_fail(parser->parse != NULL, FALSE);
1998 return parser->parse(parser, mimeinfo);
2001 static int procmime_parse_mimepart(MimeInfo *parent,
2002 gchar *content_type,
2003 gchar *content_encoding,
2004 gchar *content_description,
2006 gchar *content_disposition,
2007 gchar *content_location,
2008 const gchar *original_msgid,
2009 const gchar *disposition_notification_hdr,
2010 const gchar *filename,
2013 gboolean short_scan)
2016 MimeParser *parser = NULL;
2017 gboolean parsed = FALSE;
2020 /* Create MimeInfo */
2021 mimeinfo = procmime_mimeinfo_new();
2022 mimeinfo->content = MIMECONTENT_FILE;
2024 if (parent != NULL) {
2025 if (g_node_depth(parent->node) > 32) {
2026 /* 32 is an arbitrary value
2027 * this avoids DOSsing ourselves
2028 * with enormous messages
2030 procmime_mimeinfo_free_all(&mimeinfo);
2033 g_node_append(parent->node, mimeinfo->node);
2035 mimeinfo->data.filename = g_strdup(filename);
2036 mimeinfo->offset = offset;
2037 mimeinfo->length = length;
2039 if (content_type != NULL) {
2040 g_strchomp(content_type);
2041 procmime_parse_content_type(content_type, mimeinfo);
2043 mimeinfo->type = MIMETYPE_TEXT;
2044 mimeinfo->subtype = g_strdup("plain");
2045 if (g_hash_table_lookup(mimeinfo->typeparameters,
2046 "charset") == NULL) {
2047 g_hash_table_insert(mimeinfo->typeparameters,
2048 g_strdup("charset"),
2050 conv_get_locale_charset_str_no_utf8()));
2054 if (content_encoding != NULL) {
2055 g_strchomp(content_encoding);
2056 procmime_parse_content_encoding(content_encoding, mimeinfo);
2058 mimeinfo->encoding_type = ENC_UNKNOWN;
2061 if (content_description != NULL)
2062 mimeinfo->description = g_strdup(content_description);
2064 mimeinfo->description = NULL;
2066 if (content_id != NULL)
2067 mimeinfo->id = g_strdup(content_id);
2069 mimeinfo->id = NULL;
2071 if (content_location != NULL)
2072 mimeinfo->location = g_strdup(content_location);
2074 mimeinfo->location = NULL;
2076 if (content_disposition != NULL) {
2077 g_strchomp(content_disposition);
2078 procmime_parse_content_disposition(content_disposition, mimeinfo);
2080 mimeinfo->disposition = DISPOSITIONTYPE_UNKNOWN;
2082 /* Call parser for mime type */
2083 if ((parser = procmime_get_mimeparser_for_type(mimeinfo->type, mimeinfo->subtype)) != NULL) {
2084 parsed = procmime_mimeparser_parse(parser, mimeinfo);
2087 switch (mimeinfo->type) {
2089 if (g_ascii_strcasecmp(mimeinfo->subtype, "plain") == 0 && short_scan) {
2094 case MIMETYPE_MESSAGE:
2095 if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
2096 procmime_parse_message_rfc822(mimeinfo, short_scan);
2098 if (g_ascii_strcasecmp(mimeinfo->subtype, "disposition-notification") == 0) {
2099 procmime_parse_disposition_notification(mimeinfo,
2100 original_msgid, disposition_notification_hdr, short_scan);
2104 case MIMETYPE_MULTIPART:
2105 procmime_parse_multipart(mimeinfo, short_scan);
2108 case MIMETYPE_APPLICATION:
2109 if (g_ascii_strcasecmp(mimeinfo->subtype, "octet-stream") == 0
2110 && original_msgid && *original_msgid
2111 && disposition_notification_hdr && *disposition_notification_hdr) {
2112 procmime_parse_disposition_notification(mimeinfo,
2113 original_msgid, disposition_notification_hdr, short_scan);
2124 static gchar *typenames[] = {
2135 static gboolean output_func(GNode *node, gpointer data)
2138 MimeInfo *mimeinfo = (MimeInfo *) node->data;
2140 depth = g_node_depth(node);
2141 for (i = 0; i < depth; i++)
2143 g_print("%s/%s (offset:%d length:%d encoding: %d)\n", typenames[mimeinfo->type], mimeinfo->subtype, mimeinfo->offset, mimeinfo->length, mimeinfo->encoding_type);
2148 static void output_mime_structure(MimeInfo *mimeinfo, int indent)
2150 g_node_traverse(mimeinfo->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1, output_func, NULL);
2153 static MimeInfo *procmime_scan_file_with_offset(const gchar *filename, int offset, gboolean short_scan)
2158 if (g_stat(filename, &buf) < 0) {
2159 FILE_OP_ERROR(filename, "stat");
2163 mimeinfo = procmime_mimeinfo_new();
2164 mimeinfo->content = MIMECONTENT_FILE;
2165 mimeinfo->encoding_type = ENC_UNKNOWN;
2166 mimeinfo->type = MIMETYPE_MESSAGE;
2167 mimeinfo->subtype = g_strdup("rfc822");
2168 mimeinfo->data.filename = g_strdup(filename);
2169 mimeinfo->offset = offset;
2170 mimeinfo->length = buf.st_size - offset;
2172 procmime_parse_message_rfc822(mimeinfo, short_scan);
2173 if (debug_get_mode())
2174 output_mime_structure(mimeinfo, 0);
2179 static MimeInfo *procmime_scan_file_full(const gchar *filename, gboolean short_scan)
2183 cm_return_val_if_fail(filename != NULL, NULL);
2185 mimeinfo = procmime_scan_file_with_offset(filename, 0, short_scan);
2190 MimeInfo *procmime_scan_file(const gchar *filename)
2192 return procmime_scan_file_full(filename, FALSE);
2195 static MimeInfo *procmime_scan_file_short(const gchar *filename)
2197 return procmime_scan_file_full(filename, TRUE);
2200 static MimeInfo *procmime_scan_queue_file_full(const gchar *filename, gboolean short_scan)
2204 gchar buf[BUFFSIZE];
2207 cm_return_val_if_fail(filename != NULL, NULL);
2210 if ((fp = claws_fopen(filename, "rb")) == NULL)
2212 /* Skip queue header */
2213 while (claws_fgets(buf, sizeof(buf), fp) != NULL) {
2215 if ((!strncmp(buf, "X-Claws-End-Special-Headers: 1",
2216 strlen("X-Claws-End-Special-Headers:"))) ||
2217 (!strncmp(buf, "X-Sylpheed-End-Special-Headers: 1",
2218 strlen("X-Sylpheed-End-Special-Headers:"))))
2221 if (buf[0] == '\r' || buf[0] == '\n') break;
2222 /* from other mailers */
2223 if (!strncmp(buf, "Date: ", 6)
2224 || !strncmp(buf, "To: ", 4)
2225 || !strncmp(buf, "From: ", 6)
2226 || !strncmp(buf, "Subject: ", 9)) {
2234 mimeinfo = procmime_scan_file_with_offset(filename, offset, short_scan);
2239 MimeInfo *procmime_scan_queue_file(const gchar *filename)
2241 return procmime_scan_queue_file_full(filename, FALSE);
2244 static MimeInfo *procmime_scan_queue_file_short(const gchar *filename)
2246 return procmime_scan_queue_file_full(filename, TRUE);
2251 ENC_AS_QUOTED_STRING,
2256 typedef struct _ParametersData {
2262 static void write_parameters(gpointer key, gpointer value, gpointer user_data)
2265 gchar *val = value, *valpos, *tmp;
2266 ParametersData *pdata = (ParametersData *)user_data;
2267 GString *buf = g_string_new("");
2270 EncodeAs encas = ENC_AS_TOKEN;
2272 for (valpos = val; *valpos != 0; valpos++) {
2273 if (!IS_ASCII(*valpos)) {
2274 encas = ENC_AS_ENCWORD;
2279 if (((*valpos >= 0) && (*valpos < 037)) || (*valpos == 0177)) {
2280 encas = ENC_AS_QUOTED_STRING;
2284 /* tspecials + SPACE */
2302 encas = ENC_AS_QUOTED_STRING;
2309 g_string_append_printf(buf, "%s=%s", param, val);
2312 case ENC_AS_QUOTED_STRING:
2313 g_string_append_printf(buf, "%s=\"%s\"", param, val);
2316 #if 0 /* we don't use that for now */
2317 case ENC_AS_EXTENDED:
2318 if (!g_utf8_validate(val, -1, NULL))
2319 g_string_append_printf(buf, "%s*=%s''", param,
2320 conv_get_locale_charset_str());
2322 g_string_append_printf(buf, "%s*=%s''", param,
2324 for (valpos = val; *valpos != '\0'; valpos++) {
2325 if (IS_ASCII(*valpos) && isalnum(*valpos)) {
2326 g_string_append_printf(buf, "%c", *valpos);
2328 gchar hexstr[3] = "XX";
2329 get_hex_str(hexstr, *valpos);
2330 g_string_append_printf(buf, "%%%s", hexstr);
2335 case ENC_AS_EXTENDED:
2336 debug_print("Unhandled ENC_AS_EXTENDED.\n");
2339 case ENC_AS_ENCWORD:
2340 len = MAX(strlen(val)*6, 512);
2341 tmp = g_malloc(len+1);
2342 codeconv_set_strict(TRUE);
2343 conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2344 prefs_common.outgoing_charset);
2345 codeconv_set_strict(FALSE);
2346 if (!tmp || !*tmp) {
2347 codeconv_set_strict(TRUE);
2348 conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2349 conv_get_outgoing_charset_str());
2350 codeconv_set_strict(FALSE);
2352 if (!tmp || !*tmp) {
2353 codeconv_set_strict(TRUE);
2354 conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2356 codeconv_set_strict(FALSE);
2358 if (!tmp || !*tmp) {
2359 conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2362 g_string_append_printf(buf, "%s=\"%s\"", param, tmp);
2368 if (buf->str && strlen(buf->str)) {
2369 tmp = strstr(buf->str, "\n");
2371 len = (tmp - buf->str);
2373 len = strlen(buf->str);
2374 if (pdata->len + len > 76) {
2375 if (fprintf(pdata->fp, ";\n %s", buf->str) < 0)
2376 pdata->error = TRUE;
2377 pdata->len = strlen(buf->str) + 1;
2379 if (fprintf(pdata->fp, "; %s", buf->str) < 0)
2380 pdata->error = TRUE;
2381 pdata->len += strlen(buf->str) + 2;
2384 g_string_free(buf, TRUE);
2387 #define TRY(func) { \
2393 int procmime_write_mime_header(MimeInfo *mimeinfo, FILE *fp)
2395 struct TypeTable *type_table;
2396 ParametersData *pdata = g_new0(ParametersData, 1);
2397 debug_print("procmime_write_mime_header\n");
2400 pdata->error = FALSE;
2401 for (type_table = mime_type_table; type_table->str != NULL; type_table++)
2402 if (mimeinfo->type == type_table->type) {
2403 gchar *buf = g_strdup_printf(
2404 "Content-Type: %s/%s", type_table->str, mimeinfo->subtype);
2405 if (fprintf(fp, "%s", buf) < 0) {
2410 pdata->len = strlen(buf);
2414 g_hash_table_foreach(mimeinfo->typeparameters, write_parameters, pdata);
2415 if (pdata->error == TRUE) {
2421 TRY(fprintf(fp, "\n") >= 0);
2423 if (mimeinfo->encoding_type != ENC_UNKNOWN)
2424 TRY(fprintf(fp, "Content-Transfer-Encoding: %s\n", procmime_get_encoding_str(mimeinfo->encoding_type)) >= 0);
2426 if (mimeinfo->description != NULL)
2427 TRY(fprintf(fp, "Content-Description: %s\n", mimeinfo->description) >= 0);
2429 if (mimeinfo->id != NULL)
2430 TRY(fprintf(fp, "Content-ID: %s\n", mimeinfo->id) >= 0);
2432 if (mimeinfo->location != NULL)
2433 TRY(fprintf(fp, "Content-Location: %s\n", mimeinfo->location) >= 0);
2435 if (mimeinfo->disposition != DISPOSITIONTYPE_UNKNOWN) {
2436 ParametersData *pdata = g_new0(ParametersData, 1);
2438 if (mimeinfo->disposition == DISPOSITIONTYPE_INLINE)
2439 buf = g_strdup("Content-Disposition: inline");
2440 else if (mimeinfo->disposition == DISPOSITIONTYPE_ATTACHMENT)
2441 buf = g_strdup("Content-Disposition: attachment");
2443 buf = g_strdup("Content-Disposition: unknown");
2445 if (fprintf(fp, "%s", buf) < 0) {
2450 pdata->len = strlen(buf);
2454 pdata->error = FALSE;
2455 g_hash_table_foreach(mimeinfo->dispositionparameters, write_parameters, pdata);
2456 if (pdata->error == TRUE) {
2461 TRY(fprintf(fp, "\n") >= 0);
2464 TRY(fprintf(fp, "\n") >= 0);
2469 static gint procmime_write_message_rfc822(MimeInfo *mimeinfo, FILE *fp)
2474 gchar buf[BUFFSIZE];
2475 gboolean skip = FALSE;;
2478 debug_print("procmime_write_message_rfc822\n");
2481 switch (mimeinfo->content) {
2482 case MIMECONTENT_FILE:
2483 if ((infp = claws_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2484 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
2487 if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
2488 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
2492 while (claws_fgets(buf, sizeof(buf), infp) == buf) {
2494 if (buf[0] == '\n' && buf[1] == '\0')
2496 if (skip && (buf[0] == ' ' || buf[0] == '\t'))
2498 if (g_ascii_strncasecmp(buf, "MIME-Version:", 13) == 0 ||
2499 g_ascii_strncasecmp(buf, "Content-Type:", 13) == 0 ||
2500 g_ascii_strncasecmp(buf, "Content-Transfer-Encoding:", 26) == 0 ||
2501 g_ascii_strncasecmp(buf, "Content-Description:", 20) == 0 ||
2502 g_ascii_strncasecmp(buf, "Content-ID:", 11) == 0 ||
2503 g_ascii_strncasecmp(buf, "Content-Location:", 17) == 0 ||
2504 g_ascii_strncasecmp(buf, "Content-Disposition:", 20) == 0) {
2509 if (claws_fwrite(buf, sizeof(gchar), len, fp) < len) {
2510 g_warning("failed to dump %zd bytes from file", len);
2519 case MIMECONTENT_MEM:
2520 len = strlen(mimeinfo->data.mem);
2521 if (claws_fwrite(mimeinfo->data.mem, sizeof(gchar), len, fp) < len) {
2522 g_warning("failed to dump %zd bytes from mem", len);
2531 childnode = mimeinfo->node->children;
2532 if (childnode == NULL)
2535 child = (MimeInfo *) childnode->data;
2536 if (fprintf(fp, "MIME-Version: 1.0\n") < 0) {
2537 g_warning("failed to write mime version");
2540 if (procmime_write_mime_header(child, fp) < 0)
2542 return procmime_write_mimeinfo(child, fp);
2545 static gint procmime_write_multipart(MimeInfo *mimeinfo, FILE *fp)
2549 gchar *boundary, *str, *str2;
2550 gchar buf[BUFFSIZE];
2551 gboolean firstboundary;
2554 debug_print("procmime_write_multipart\n");
2556 boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
2558 switch (mimeinfo->content) {
2559 case MIMECONTENT_FILE:
2560 if ((infp = claws_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2561 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
2564 if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
2565 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
2569 while (claws_fgets(buf, sizeof(buf), infp) == buf) {
2570 if (IS_BOUNDARY(buf, boundary, strlen(boundary)))
2573 if (claws_fwrite(buf, sizeof(gchar), len, fp) < len) {
2574 g_warning("failed to write %zd", len);
2582 case MIMECONTENT_MEM:
2583 str = g_strdup(mimeinfo->data.mem);
2584 if (((str2 = strstr(str, boundary)) != NULL) && ((str2 - str) >= 2) &&
2585 (*(str2 - 1) == '-') && (*(str2 - 2) == '-'))
2588 if (claws_fwrite(str, sizeof(gchar), len, fp) < len) {
2589 g_warning("failed to write %zd from mem", len);
2600 childnode = mimeinfo->node->children;
2601 firstboundary = TRUE;
2602 while (childnode != NULL) {
2603 MimeInfo *child = childnode->data;
2606 firstboundary = FALSE;
2608 TRY(fprintf(fp, "\n") >= 0);
2610 TRY(fprintf(fp, "--%s\n", boundary) >= 0);
2612 if (procmime_write_mime_header(child, fp) < 0)
2614 if (procmime_write_mimeinfo(child, fp) < 0)
2617 childnode = g_node_next_sibling(childnode);
2619 TRY(fprintf(fp, "\n--%s--\n", boundary) >= 0);
2624 gint procmime_write_mimeinfo(MimeInfo *mimeinfo, FILE *fp)
2628 debug_print("procmime_write_mimeinfo\n");
2630 if (G_NODE_IS_LEAF(mimeinfo->node)) {
2631 switch (mimeinfo->content) {
2632 case MIMECONTENT_FILE:
2633 if ((infp = claws_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2634 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
2637 copy_file_part_to_fp(infp, mimeinfo->offset, mimeinfo->length, fp);
2641 case MIMECONTENT_MEM:
2642 len = strlen(mimeinfo->data.mem);
2643 if (claws_fwrite(mimeinfo->data.mem, sizeof(gchar), len, fp) < len)
2651 /* Call writer for mime type */
2652 switch (mimeinfo->type) {
2653 case MIMETYPE_MESSAGE:
2654 if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
2655 return procmime_write_message_rfc822(mimeinfo, fp);
2659 case MIMETYPE_MULTIPART:
2660 return procmime_write_multipart(mimeinfo, fp);
2672 gchar *procmime_get_part_file_name(MimeInfo *mimeinfo)
2676 if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
2677 base = g_strdup("mimetmp.html");
2679 const gchar *basetmp;
2682 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
2683 if (basetmp == NULL)
2684 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
2685 if (basetmp == NULL)
2686 basetmp = "mimetmp";
2687 basename = g_path_get_basename(basetmp);
2688 if (*basename == '\0') {
2690 basename = g_strdup("mimetmp");
2692 base = conv_filename_from_utf8(basename);
2694 subst_for_shellsafe_filename(base);