Remove wrong initialization from max_message_size
[claws.git] / src / procmime.c
blob0a7cd954918b8a6afe8efff4d13d1860868274ba
1 /*
2 * Claws Mail -- a GTK based, lightweight, and fast e-mail client
3 * Copyright (C) 1999-2023 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 {"font", MIMETYPE_FONT},
1407 {"model", MIMETYPE_MODEL},
1408 {"chemical", MIMETYPE_CHEMICAL},
1409 {"application", MIMETYPE_APPLICATION},
1410 {"message", MIMETYPE_MESSAGE},
1411 {"multipart", MIMETYPE_MULTIPART},
1412 {NULL, 0},
1415 const gchar *procmime_get_media_type_str(MimeMediaType type)
1417 struct TypeTable *type_table;
1419 for (type_table = mime_type_table; type_table->str != NULL; type_table++) {
1420 if (type_table->type == type)
1421 return type_table->str;
1423 return NULL;
1426 MimeMediaType procmime_get_media_type(const gchar *str)
1428 struct TypeTable *typetablearray;
1430 for (typetablearray = mime_type_table; typetablearray->str != NULL; typetablearray++)
1431 if (g_ascii_strncasecmp(str, typetablearray->str, strlen(typetablearray->str)) == 0)
1432 return typetablearray->type;
1434 return MIMETYPE_UNKNOWN;
1438 *\brief Safe wrapper for content type string.
1440 *\return const gchar * Pointer to content type string.
1442 gchar *procmime_get_content_type_str(MimeMediaType type,
1443 const char *subtype)
1445 const gchar *type_str = NULL;
1447 if (subtype == NULL || !(type_str = procmime_get_media_type_str(type)))
1448 return g_strdup("unknown");
1449 return g_strdup_printf("%s/%s", type_str, subtype);
1452 static int procmime_parse_mimepart(MimeInfo *parent,
1453 gchar *content_type,
1454 gchar *content_encoding,
1455 gchar *content_description,
1456 gchar *content_id,
1457 gchar *content_disposition,
1458 gchar *content_location,
1459 const gchar *original_msgid,
1460 const gchar *disposition_notification_hdr,
1461 const gchar *filename,
1462 guint offset,
1463 guint length,
1464 gboolean short_scan);
1466 static void procmime_parse_message_rfc822(MimeInfo *mimeinfo, gboolean short_scan)
1468 HeaderEntry hentry[] = {{"Content-Type:", NULL, TRUE},
1469 {"Content-Transfer-Encoding:",
1470 NULL, FALSE},
1471 {"Content-Description:",
1472 NULL, TRUE},
1473 {"Content-ID:",
1474 NULL, TRUE},
1475 {"Content-Disposition:",
1476 NULL, TRUE},
1477 {"Content-Location:",
1478 NULL, TRUE},
1479 {"MIME-Version:",
1480 NULL, TRUE},
1481 {"Original-Message-ID:",
1482 NULL, TRUE},
1483 {"Disposition:",
1484 NULL, TRUE},
1485 {NULL, NULL, FALSE}};
1486 guint content_start, i;
1487 FILE *fp;
1488 gchar *tmp;
1489 gint len = 0;
1491 procmime_decode_content(mimeinfo);
1493 fp = claws_fopen(mimeinfo->data.filename, "rb");
1494 if (fp == NULL) {
1495 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
1496 return;
1498 if (fseek(fp, mimeinfo->offset, SEEK_SET) < 0) {
1499 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
1500 claws_fclose(fp);
1501 return;
1503 procheader_get_header_fields(fp, hentry);
1504 if (hentry[0].body != NULL) {
1505 tmp = conv_unmime_header(hentry[0].body, NULL, FALSE);
1506 g_free(hentry[0].body);
1507 hentry[0].body = tmp;
1509 if (hentry[2].body != NULL) {
1510 tmp = conv_unmime_header(hentry[2].body, NULL, FALSE);
1511 g_free(hentry[2].body);
1512 hentry[2].body = tmp;
1514 if (hentry[4].body != NULL) {
1515 tmp = conv_unmime_header(hentry[4].body, NULL, FALSE);
1516 g_free(hentry[4].body);
1517 hentry[4].body = tmp;
1519 if (hentry[5].body != NULL) {
1520 tmp = conv_unmime_header(hentry[5].body, NULL, FALSE);
1521 g_free(hentry[5].body);
1522 hentry[5].body = tmp;
1524 if (hentry[7].body != NULL) {
1525 tmp = conv_unmime_header(hentry[7].body, NULL, FALSE);
1526 g_free(hentry[7].body);
1527 hentry[7].body = tmp;
1529 if (hentry[8].body != NULL) {
1530 tmp = conv_unmime_header(hentry[8].body, NULL, FALSE);
1531 g_free(hentry[8].body);
1532 hentry[8].body = tmp;
1535 content_start = ftell(fp);
1536 claws_fclose(fp);
1538 len = mimeinfo->length - (content_start - mimeinfo->offset);
1539 if (len < 0)
1540 len = 0;
1541 procmime_parse_mimepart(mimeinfo,
1542 hentry[0].body, hentry[1].body,
1543 hentry[2].body, hentry[3].body,
1544 hentry[4].body, hentry[5].body,
1545 hentry[7].body, hentry[8].body,
1546 mimeinfo->data.filename, content_start,
1547 len, short_scan);
1549 for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1550 g_free(hentry[i].body);
1551 hentry[i].body = NULL;
1555 static void procmime_parse_disposition_notification(MimeInfo *mimeinfo,
1556 const gchar *original_msgid, const gchar *disposition_notification_hdr,
1557 gboolean short_scan)
1559 HeaderEntry hentry[] = {{"Original-Message-ID:", NULL, TRUE},
1560 {"Disposition:", NULL, TRUE},
1561 {NULL, NULL, FALSE}};
1562 guint i;
1563 FILE *fp;
1564 gchar *orig_msg_id = NULL;
1565 gchar *disp = NULL;
1567 procmime_decode_content(mimeinfo);
1569 debug_print("parse disposition notification\n");
1570 fp = claws_fopen(mimeinfo->data.filename, "rb");
1571 if (fp == NULL) {
1572 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
1573 return;
1575 if (fseek(fp, mimeinfo->offset, SEEK_SET) < 0) {
1576 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
1577 claws_fclose(fp);
1578 return;
1581 if (original_msgid && disposition_notification_hdr) {
1582 hentry[0].body = g_strdup(original_msgid);
1583 hentry[1].body = g_strdup(disposition_notification_hdr);
1584 } else {
1585 procheader_get_header_fields(fp, hentry);
1588 claws_fclose(fp);
1590 if (!hentry[0].body || !hentry[1].body) {
1591 debug_print("MsgId %s, Disp %s\n",
1592 hentry[0].body ? hentry[0].body:"(nil)",
1593 hentry[1].body ? hentry[1].body:"(nil)");
1594 goto bail;
1597 orig_msg_id = g_strdup(hentry[0].body);
1598 disp = g_strdup(hentry[1].body);
1600 extract_parenthesis(orig_msg_id, '<', '>');
1601 remove_space(orig_msg_id);
1603 if (strstr(disp, "displayed")) {
1604 /* find sent message, if possible */
1605 MsgInfo *info = NULL;
1606 GList *flist;
1607 debug_print("%s has been displayed.\n", orig_msg_id);
1608 for (flist = folder_get_list(); flist != NULL; flist = g_list_next(flist)) {
1609 FolderItem *outbox = ((Folder *)(flist->data))->outbox;
1610 if (!outbox) {
1611 debug_print("skipping folder with no outbox...\n");
1612 continue;
1614 info = folder_item_get_msginfo_by_msgid(outbox, orig_msg_id);
1615 debug_print("%s %s in %s\n", info?"found":"didn't find", orig_msg_id, outbox->path);
1616 if (info) {
1617 procmsg_msginfo_set_flags(info, MSG_RETRCPT_GOT, 0);
1618 procmsg_msginfo_free(&info);
1622 g_free(orig_msg_id);
1623 g_free(disp);
1624 bail:
1625 for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1626 g_free(hentry[i].body);
1627 hentry[i].body = NULL;
1631 #define GET_HEADERS() { \
1632 procheader_get_header_fields(fp, hentry); \
1633 if (hentry[0].body != NULL) { \
1634 tmp = conv_unmime_header(hentry[0].body, NULL, FALSE); \
1635 g_free(hentry[0].body); \
1636 hentry[0].body = tmp; \
1638 if (hentry[2].body != NULL) { \
1639 tmp = conv_unmime_header(hentry[2].body, NULL, FALSE); \
1640 g_free(hentry[2].body); \
1641 hentry[2].body = tmp; \
1643 if (hentry[4].body != NULL) { \
1644 tmp = conv_unmime_header(hentry[4].body, NULL, FALSE); \
1645 g_free(hentry[4].body); \
1646 hentry[4].body = tmp; \
1648 if (hentry[5].body != NULL) { \
1649 tmp = conv_unmime_header(hentry[5].body, NULL, FALSE); \
1650 g_free(hentry[5].body); \
1651 hentry[5].body = tmp; \
1653 if (hentry[6].body != NULL) { \
1654 tmp = conv_unmime_header(hentry[6].body, NULL, FALSE); \
1655 g_free(hentry[6].body); \
1656 hentry[6].body = tmp; \
1658 if (hentry[7].body != NULL) { \
1659 tmp = conv_unmime_header(hentry[7].body, NULL, FALSE); \
1660 g_free(hentry[7].body); \
1661 hentry[7].body = tmp; \
1665 static void procmime_parse_multipart(MimeInfo *mimeinfo, gboolean short_scan)
1667 HeaderEntry hentry[] = {{"Content-Type:", NULL, TRUE},
1668 {"Content-Transfer-Encoding:",
1669 NULL, FALSE},
1670 {"Content-Description:",
1671 NULL, TRUE},
1672 {"Content-ID:",
1673 NULL, TRUE},
1674 {"Content-Disposition:",
1675 NULL, TRUE},
1676 {"Content-Location:",
1677 NULL, TRUE},
1678 {"Original-Message-ID:",
1679 NULL, TRUE},
1680 {"Disposition:",
1681 NULL, TRUE},
1682 {NULL, NULL, FALSE}};
1683 gchar *tmp;
1684 gchar *boundary;
1685 gint boundary_len = 0, lastoffset = -1, i;
1686 gchar buf[BUFFSIZE];
1687 FILE *fp;
1688 int result = 0;
1689 gboolean start_found = FALSE;
1690 gboolean end_found = FALSE;
1692 boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
1693 if (!boundary)
1694 return;
1695 boundary_len = strlen(boundary);
1697 procmime_decode_content(mimeinfo);
1699 fp = claws_fopen(mimeinfo->data.filename, "rb");
1700 if (fp == NULL) {
1701 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
1702 return;
1705 if (fseek(fp, mimeinfo->offset, SEEK_SET) < 0) {
1706 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
1707 claws_fclose(fp);
1708 return;
1711 while (claws_fgets(buf, sizeof(buf), fp) != NULL && result == 0) {
1712 if (ftell(fp) - 1 > (mimeinfo->offset + mimeinfo->length))
1713 break;
1715 if (IS_BOUNDARY(buf, boundary, boundary_len)) {
1716 start_found = TRUE;
1718 if (lastoffset != -1) {
1719 gint len = (ftell(fp) - strlen(buf)) - lastoffset - 1;
1720 if (len < 0)
1721 len = 0;
1722 result = procmime_parse_mimepart(mimeinfo,
1723 hentry[0].body, hentry[1].body,
1724 hentry[2].body, hentry[3].body,
1725 hentry[4].body, hentry[5].body,
1726 hentry[6].body, hentry[7].body,
1727 mimeinfo->data.filename, lastoffset,
1728 len, short_scan);
1729 if (result == 1 && short_scan)
1730 break;
1734 if (buf[2 + boundary_len] == '-' &&
1735 buf[2 + boundary_len + 1] == '-') {
1736 end_found = TRUE;
1737 break;
1739 for (i = 0; i < (sizeof hentry / sizeof hentry[0]) ; i++) {
1740 g_free(hentry[i].body);
1741 hentry[i].body = NULL;
1743 GET_HEADERS();
1744 lastoffset = ftell(fp);
1748 if (start_found && !end_found && lastoffset != -1) {
1749 gint len = (ftell(fp) - strlen(buf)) - lastoffset - 1;
1751 if (len >= 0) {
1752 result = procmime_parse_mimepart(mimeinfo,
1753 hentry[0].body, hentry[1].body,
1754 hentry[2].body, hentry[3].body,
1755 hentry[4].body, hentry[5].body,
1756 hentry[6].body, hentry[7].body,
1757 mimeinfo->data.filename, lastoffset,
1758 len, short_scan);
1760 mimeinfo->broken = TRUE;
1763 for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1764 g_free(hentry[i].body);
1765 hentry[i].body = NULL;
1767 claws_fclose(fp);
1770 static void parse_parameters(const gchar *parameters, GHashTable *table)
1772 gchar *params, *param, *next;
1773 GSList *convlist = NULL, *concatlist = NULL, *cur;
1775 params = g_strdup(parameters);
1776 param = params;
1777 next = params;
1778 for (; next != NULL; param = next) {
1779 gchar *attribute, *value, *tmp, *down_attr, *orig_down_attr;
1780 gint len;
1781 gboolean convert = FALSE;
1783 next = strchr_with_skip_quote(param, '"', ';');
1784 if (next != NULL) {
1785 next[0] = '\0';
1786 next++;
1789 g_strstrip(param);
1791 attribute = param;
1792 value = strchr(attribute, '=');
1793 if (value == NULL)
1794 continue;
1796 value[0] = '\0';
1797 value++;
1798 while (value[0] != '\0' && value[0] == ' ')
1799 value++;
1801 down_attr = g_utf8_strdown(attribute, -1);
1802 orig_down_attr = down_attr;
1804 len = down_attr ? strlen(down_attr):0;
1805 if (len > 0 && down_attr[len - 1] == '*') {
1806 gchar *srcpos, *dstpos, *endpos;
1808 convert = TRUE;
1809 down_attr[len - 1] = '\0';
1811 srcpos = value;
1812 dstpos = value;
1813 endpos = value + strlen(value);
1814 while (srcpos < endpos) {
1815 if (*srcpos != '%')
1816 *dstpos = *srcpos;
1817 else {
1818 guchar dstvalue;
1820 if (!get_hex_value(&dstvalue, srcpos[1], srcpos[2]))
1821 *dstpos = '?';
1822 else
1823 *dstpos = dstvalue;
1824 srcpos += 2;
1826 srcpos++;
1827 dstpos++;
1829 *dstpos = '\0';
1830 if (value[0] == '"')
1831 extract_quote(value, '"');
1832 } else {
1833 if (value[0] == '"')
1834 extract_quote(value, '"');
1835 else if ((tmp = strchr(value, ' ')) != NULL)
1836 *tmp = '\0';
1839 if (down_attr) {
1840 while (down_attr[0] == ' ')
1841 down_attr++;
1842 while (down_attr[strlen(down_attr)-1] == ' ')
1843 down_attr[strlen(down_attr)-1] = '\0';
1846 while (value[0] != '\0' && value[0] == ' ')
1847 value++;
1848 while (value[strlen(value)-1] == ' ')
1849 value[strlen(value)-1] = '\0';
1851 if (down_attr && strrchr(down_attr, '*') != NULL) {
1852 gchar *tmpattr;
1854 tmpattr = g_strdup(down_attr);
1855 tmp = strrchr(tmpattr, '*');
1856 tmp[0] = '\0';
1858 if ((tmp[1] == '0') && (tmp[2] == '\0') &&
1859 (g_slist_find_custom(concatlist, down_attr, (GCompareFunc)g_strcmp0) == NULL))
1860 concatlist = g_slist_prepend(concatlist, g_strdup(tmpattr));
1862 if (convert && (g_slist_find_custom(convlist, tmpattr, (GCompareFunc)g_strcmp0) == NULL))
1863 convlist = g_slist_prepend(convlist, g_strdup(tmpattr));
1865 g_free(tmpattr);
1866 } else if (convert) {
1867 if (g_slist_find_custom(convlist, down_attr, (GCompareFunc)g_strcmp0) == NULL)
1868 convlist = g_slist_prepend(convlist, g_strdup(down_attr));
1871 if (g_hash_table_lookup(table, down_attr) == NULL)
1872 g_hash_table_insert(table, g_strdup(down_attr), g_strdup(value));
1873 g_free(orig_down_attr);
1876 for (cur = concatlist; cur != NULL; cur = g_slist_next(cur)) {
1877 gchar *attribute, *attrwnum, *partvalue;
1878 gint n = 0;
1879 GString *value;
1881 attribute = (gchar *) cur->data;
1882 value = g_string_sized_new(64);
1884 attrwnum = g_strdup_printf("%s*%d", attribute, n);
1885 while ((partvalue = g_hash_table_lookup(table, attrwnum)) != NULL) {
1886 g_string_append(value, partvalue);
1888 g_hash_table_remove(table, attrwnum);
1889 g_free(attrwnum);
1890 n++;
1891 attrwnum = g_strdup_printf("%s*%d", attribute, n);
1893 g_free(attrwnum);
1895 g_hash_table_insert(table, g_strdup(attribute), g_strdup(value->str));
1896 g_string_free(value, TRUE);
1898 slist_free_strings_full(concatlist);
1900 for (cur = convlist; cur != NULL; cur = g_slist_next(cur)) {
1901 gchar *attribute, *key, *value;
1902 gchar *charset, *lang, *oldvalue, *newvalue;
1904 attribute = (gchar *) cur->data;
1905 if (!g_hash_table_lookup_extended(
1906 table, attribute, (gpointer *)(gchar *) &key, (gpointer *)(gchar *) &value))
1907 continue;
1909 charset = value;
1910 if (charset == NULL)
1911 continue;
1912 lang = strchr(charset, '\'');
1913 if (lang == NULL)
1914 continue;
1915 lang[0] = '\0';
1916 lang++;
1917 oldvalue = strchr(lang, '\'');
1918 if (oldvalue == NULL)
1919 continue;
1920 oldvalue[0] = '\0';
1921 oldvalue++;
1923 newvalue = conv_codeset_strdup(oldvalue, charset, CS_UTF_8);
1925 g_hash_table_remove(table, attribute);
1926 g_free(key);
1927 g_free(value);
1929 g_hash_table_insert(table, g_strdup(attribute), newvalue);
1931 slist_free_strings_full(convlist);
1933 g_free(params);
1936 static void procmime_parse_content_type(const gchar *content_type, MimeInfo *mimeinfo)
1938 cm_return_if_fail(content_type != NULL);
1939 cm_return_if_fail(mimeinfo != NULL);
1941 /* RFC 2045, page 13 says that the mime subtype is MANDATORY;
1942 * if it's not available we use the default Content-Type */
1943 if ((content_type[0] == '\0') || (strchr(content_type, '/') == NULL)) {
1944 mimeinfo->type = MIMETYPE_TEXT;
1945 mimeinfo->subtype = g_strdup("plain");
1946 if (g_hash_table_lookup(mimeinfo->typeparameters,
1947 "charset") == NULL) {
1948 g_hash_table_insert(mimeinfo->typeparameters,
1949 g_strdup("charset"),
1950 g_strdup(
1951 conv_get_locale_charset_str_no_utf8()));
1953 } else {
1954 gchar *type, *subtype, *params;
1956 type = g_strdup(content_type);
1957 subtype = strchr(type, '/') + 1;
1958 *(subtype - 1) = '\0';
1959 if ((params = strchr(subtype, ';')) != NULL) {
1960 params[0] = '\0';
1961 params++;
1964 mimeinfo->type = procmime_get_media_type(type);
1965 mimeinfo->subtype = g_strstrip(g_strdup(subtype));
1967 /* Get mimeinfo->typeparameters */
1968 if (params != NULL)
1969 parse_parameters(params, mimeinfo->typeparameters);
1971 g_free(type);
1975 static void procmime_parse_content_disposition(const gchar *content_disposition, MimeInfo *mimeinfo)
1977 gchar *tmp, *params;
1979 cm_return_if_fail(content_disposition != NULL);
1980 cm_return_if_fail(mimeinfo != NULL);
1982 tmp = g_strdup(content_disposition);
1983 if ((params = strchr(tmp, ';')) != NULL) {
1984 params[0] = '\0';
1985 params++;
1987 g_strstrip(tmp);
1989 if (!g_ascii_strcasecmp(tmp, "inline"))
1990 mimeinfo->disposition = DISPOSITIONTYPE_INLINE;
1991 else if (!g_ascii_strcasecmp(tmp, "attachment"))
1992 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1993 else
1994 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1996 if (params != NULL)
1997 parse_parameters(params, mimeinfo->dispositionparameters);
1999 g_free(tmp);
2003 static void procmime_parse_content_encoding(const gchar *content_encoding, MimeInfo *mimeinfo)
2005 struct EncodingTable *enc_table;
2007 for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
2008 if (g_ascii_strcasecmp(enc_table->str, content_encoding) == 0) {
2009 mimeinfo->encoding_type = enc_table->enc_type;
2010 return;
2013 mimeinfo->encoding_type = ENC_UNKNOWN;
2014 return;
2017 static GSList *registered_parsers = NULL;
2019 static MimeParser *procmime_get_mimeparser_for_type(MimeMediaType type, const gchar *sub_type)
2021 GSList *cur;
2022 for (cur = registered_parsers; cur; cur = cur->next) {
2023 MimeParser *parser = (MimeParser *)cur->data;
2024 if (parser->type == type && !g_strcmp0(parser->sub_type, sub_type))
2025 return parser;
2027 return NULL;
2030 void procmime_mimeparser_register(MimeParser *parser)
2032 if (!procmime_get_mimeparser_for_type(parser->type, parser->sub_type))
2033 registered_parsers = g_slist_append(registered_parsers, parser);
2037 void procmime_mimeparser_unregister(MimeParser *parser)
2039 registered_parsers = g_slist_remove(registered_parsers, parser);
2042 static gboolean procmime_mimeparser_parse(MimeParser *parser, MimeInfo *mimeinfo)
2044 cm_return_val_if_fail(parser->parse != NULL, FALSE);
2045 return parser->parse(parser, mimeinfo);
2048 static int procmime_parse_mimepart(MimeInfo *parent,
2049 gchar *content_type,
2050 gchar *content_encoding,
2051 gchar *content_description,
2052 gchar *content_id,
2053 gchar *content_disposition,
2054 gchar *content_location,
2055 const gchar *original_msgid,
2056 const gchar *disposition_notification_hdr,
2057 const gchar *filename,
2058 guint offset,
2059 guint length,
2060 gboolean short_scan)
2062 MimeInfo *mimeinfo;
2063 MimeParser *parser = NULL;
2064 gboolean parsed = FALSE;
2065 int result = 0;
2067 /* Create MimeInfo */
2068 mimeinfo = procmime_mimeinfo_new();
2069 mimeinfo->content = MIMECONTENT_FILE;
2071 if (parent != NULL) {
2072 if (g_node_depth(parent->node) > 32) {
2073 /* 32 is an arbitrary value
2074 * this avoids DOSsing ourselves
2075 * with enormous messages
2077 procmime_mimeinfo_free_all(&mimeinfo);
2078 return -1;
2080 g_node_append(parent->node, mimeinfo->node);
2082 mimeinfo->data.filename = g_strdup(filename);
2083 mimeinfo->offset = offset;
2084 mimeinfo->length = length;
2086 if (content_type != NULL) {
2087 g_strchomp(content_type);
2088 procmime_parse_content_type(content_type, mimeinfo);
2089 } else {
2090 mimeinfo->type = MIMETYPE_TEXT;
2091 mimeinfo->subtype = g_strdup("plain");
2092 if (g_hash_table_lookup(mimeinfo->typeparameters,
2093 "charset") == NULL) {
2094 g_hash_table_insert(mimeinfo->typeparameters,
2095 g_strdup("charset"),
2096 g_strdup(
2097 conv_get_locale_charset_str_no_utf8()));
2101 if (content_encoding != NULL) {
2102 g_strchomp(content_encoding);
2103 procmime_parse_content_encoding(content_encoding, mimeinfo);
2104 } else {
2105 mimeinfo->encoding_type = ENC_UNKNOWN;
2108 if (content_description != NULL)
2109 mimeinfo->description = g_strdup(content_description);
2110 else
2111 mimeinfo->description = NULL;
2113 if (content_id != NULL)
2114 mimeinfo->id = g_strdup(content_id);
2115 else
2116 mimeinfo->id = NULL;
2118 if (content_location != NULL)
2119 mimeinfo->location = g_strdup(content_location);
2120 else
2121 mimeinfo->location = NULL;
2123 if (content_disposition != NULL) {
2124 g_strchomp(content_disposition);
2125 procmime_parse_content_disposition(content_disposition, mimeinfo);
2126 } else
2127 mimeinfo->disposition = DISPOSITIONTYPE_UNKNOWN;
2129 /* Call parser for mime type */
2130 if ((parser = procmime_get_mimeparser_for_type(mimeinfo->type, mimeinfo->subtype)) != NULL) {
2131 parsed = procmime_mimeparser_parse(parser, mimeinfo);
2133 if (!parsed) {
2134 switch (mimeinfo->type) {
2135 case MIMETYPE_TEXT:
2136 if (g_ascii_strcasecmp(mimeinfo->subtype, "plain") == 0 && short_scan) {
2137 return 1;
2139 break;
2141 case MIMETYPE_MESSAGE:
2142 if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
2143 procmime_parse_message_rfc822(mimeinfo, short_scan);
2145 if (g_ascii_strcasecmp(mimeinfo->subtype, "disposition-notification") == 0) {
2146 procmime_parse_disposition_notification(mimeinfo,
2147 original_msgid, disposition_notification_hdr, short_scan);
2149 break;
2151 case MIMETYPE_MULTIPART:
2152 procmime_parse_multipart(mimeinfo, short_scan);
2153 break;
2155 case MIMETYPE_APPLICATION:
2156 if (g_ascii_strcasecmp(mimeinfo->subtype, "octet-stream") == 0
2157 && original_msgid && *original_msgid
2158 && disposition_notification_hdr && *disposition_notification_hdr) {
2159 procmime_parse_disposition_notification(mimeinfo,
2160 original_msgid, disposition_notification_hdr, short_scan);
2162 break;
2163 default:
2164 break;
2168 return result;
2171 static gchar *typenames[] = {
2172 "text",
2173 "image",
2174 "audio",
2175 "video",
2176 "application",
2177 "message",
2178 "multipart",
2179 "font",
2180 "model",
2181 "chemical",
2182 "unknown",
2185 static gboolean output_func(GNode *node, gpointer data)
2187 guint i, depth;
2188 MimeInfo *mimeinfo = (MimeInfo *) node->data;
2190 depth = g_node_depth(node);
2191 for (i = 0; i < depth; i++)
2192 g_print(" ");
2193 g_print("%s/%s (offset:%d length:%d encoding: %d)\n",
2194 (mimeinfo->type <= MIMETYPE_UNKNOWN)? typenames[mimeinfo->type] : "unknown",
2195 mimeinfo->subtype, mimeinfo->offset, mimeinfo->length, mimeinfo->encoding_type);
2197 return FALSE;
2200 static void output_mime_structure(MimeInfo *mimeinfo, int indent)
2202 g_node_traverse(mimeinfo->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1, output_func, NULL);
2205 static MimeInfo *procmime_scan_file_with_offset(const gchar *filename, int offset, gboolean short_scan)
2207 MimeInfo *mimeinfo;
2208 GStatBuf buf;
2210 if (g_stat(filename, &buf) < 0) {
2211 FILE_OP_ERROR(filename, "stat");
2212 return NULL;
2215 mimeinfo = procmime_mimeinfo_new();
2216 mimeinfo->content = MIMECONTENT_FILE;
2217 mimeinfo->encoding_type = ENC_UNKNOWN;
2218 mimeinfo->type = MIMETYPE_MESSAGE;
2219 mimeinfo->subtype = g_strdup("rfc822");
2220 mimeinfo->data.filename = g_strdup(filename);
2221 mimeinfo->offset = offset;
2222 mimeinfo->length = buf.st_size - offset;
2224 procmime_parse_message_rfc822(mimeinfo, short_scan);
2225 if (debug_get_mode())
2226 output_mime_structure(mimeinfo, 0);
2228 return mimeinfo;
2231 static MimeInfo *procmime_scan_file_full(const gchar *filename, gboolean short_scan)
2233 MimeInfo *mimeinfo;
2235 cm_return_val_if_fail(filename != NULL, NULL);
2237 mimeinfo = procmime_scan_file_with_offset(filename, 0, short_scan);
2239 return mimeinfo;
2242 MimeInfo *procmime_scan_file(const gchar *filename)
2244 return procmime_scan_file_full(filename, FALSE);
2247 static MimeInfo *procmime_scan_file_short(const gchar *filename)
2249 return procmime_scan_file_full(filename, TRUE);
2252 static MimeInfo *procmime_scan_queue_file_full(const gchar *filename, gboolean short_scan)
2254 FILE *fp;
2255 MimeInfo *mimeinfo;
2256 gchar buf[BUFFSIZE];
2257 gint offset = 0;
2259 cm_return_val_if_fail(filename != NULL, NULL);
2261 /* Open file */
2262 if ((fp = claws_fopen(filename, "rb")) == NULL)
2263 return NULL;
2264 /* Skip queue header */
2265 while (claws_fgets(buf, sizeof(buf), fp) != NULL) {
2266 /* new way */
2267 if ((!strncmp(buf, "X-Claws-End-Special-Headers: 1",
2268 strlen("X-Claws-End-Special-Headers:"))) ||
2269 (!strncmp(buf, "X-Sylpheed-End-Special-Headers: 1",
2270 strlen("X-Sylpheed-End-Special-Headers:"))))
2271 break;
2272 /* old way */
2273 if (buf[0] == '\r' || buf[0] == '\n') break;
2274 /* from other mailers */
2275 if (!strncmp(buf, "Date: ", 6)
2276 || !strncmp(buf, "To: ", 4)
2277 || !strncmp(buf, "From: ", 6)
2278 || !strncmp(buf, "Subject: ", 9)) {
2279 rewind(fp);
2280 break;
2283 offset = ftell(fp);
2284 claws_fclose(fp);
2286 mimeinfo = procmime_scan_file_with_offset(filename, offset, short_scan);
2288 return mimeinfo;
2291 MimeInfo *procmime_scan_queue_file(const gchar *filename)
2293 return procmime_scan_queue_file_full(filename, FALSE);
2296 static MimeInfo *procmime_scan_queue_file_short(const gchar *filename)
2298 return procmime_scan_queue_file_full(filename, TRUE);
2301 typedef enum {
2302 ENC_AS_TOKEN,
2303 ENC_AS_QUOTED_STRING,
2304 ENC_AS_EXTENDED,
2305 ENC_AS_ENCWORD
2306 } EncodeAs;
2308 typedef struct _ParametersData {
2309 FILE *fp;
2310 guint len;
2311 gint error;
2312 } ParametersData;
2314 static void write_parameters(gpointer key, gpointer value, gpointer user_data)
2316 gchar *param = key;
2317 gchar *val = value, *valpos, *tmp;
2318 ParametersData *pdata = (ParametersData *)user_data;
2319 GString *buf = g_string_new("");
2320 gint len;
2322 EncodeAs encas = ENC_AS_TOKEN;
2324 for (valpos = val; *valpos != 0; valpos++) {
2325 if (!IS_ASCII(*valpos)) {
2326 encas = ENC_AS_ENCWORD;
2327 break;
2330 /* CTLs */
2331 if (((*valpos >= 0) && (*valpos < 037)) || (*valpos == 0177)) {
2332 encas = ENC_AS_QUOTED_STRING;
2333 continue;
2336 /* tspecials + SPACE */
2337 switch (*valpos) {
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 case '[':
2351 case ']':
2352 case '?':
2353 case '=':
2354 encas = ENC_AS_QUOTED_STRING;
2355 continue;
2359 switch (encas) {
2360 case ENC_AS_TOKEN:
2361 g_string_append_printf(buf, "%s=%s", param, val);
2362 break;
2364 case ENC_AS_QUOTED_STRING:
2365 g_string_append_printf(buf, "%s=\"%s\"", param, val);
2366 break;
2368 #if 0 /* we don't use that for now */
2369 case ENC_AS_EXTENDED:
2370 if (!g_utf8_validate(val, -1, NULL))
2371 g_string_append_printf(buf, "%s*=%s''", param,
2372 conv_get_locale_charset_str());
2373 else
2374 g_string_append_printf(buf, "%s*=%s''", param,
2375 CS_INTERNAL);
2376 for (valpos = val; *valpos != '\0'; valpos++) {
2377 if (IS_ASCII(*valpos) && isalnum(*valpos)) {
2378 g_string_append_printf(buf, "%c", *valpos);
2379 } else {
2380 gchar hexstr[3] = "XX";
2381 get_hex_str(hexstr, *valpos);
2382 g_string_append_printf(buf, "%%%s", hexstr);
2385 break;
2386 #else
2387 case ENC_AS_EXTENDED:
2388 debug_print("Unhandled ENC_AS_EXTENDED.\n");
2389 break;
2390 #endif
2391 case ENC_AS_ENCWORD:
2392 len = MAX(strlen(val)*6, 512);
2393 tmp = g_malloc(len+1);
2394 codeconv_set_strict(TRUE);
2395 conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2396 prefs_common.outgoing_charset);
2397 codeconv_set_strict(FALSE);
2398 if (!tmp || !*tmp) {
2399 codeconv_set_strict(TRUE);
2400 conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2401 conv_get_outgoing_charset_str());
2402 codeconv_set_strict(FALSE);
2404 if (!tmp || !*tmp) {
2405 codeconv_set_strict(TRUE);
2406 conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2407 CS_UTF_8);
2408 codeconv_set_strict(FALSE);
2410 if (!tmp || !*tmp) {
2411 conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2412 CS_UTF_8);
2414 g_string_append_printf(buf, "%s=\"%s\"", param, tmp);
2415 g_free(tmp);
2416 break;
2420 if (buf->str && strlen(buf->str)) {
2421 tmp = strstr(buf->str, "\n");
2422 if (tmp)
2423 len = (tmp - buf->str);
2424 else
2425 len = strlen(buf->str);
2426 if (pdata->len + len > 76) {
2427 if (fprintf(pdata->fp, ";\n %s", buf->str) < 0)
2428 pdata->error = TRUE;
2429 pdata->len = strlen(buf->str) + 1;
2430 } else {
2431 if (fprintf(pdata->fp, "; %s", buf->str) < 0)
2432 pdata->error = TRUE;
2433 pdata->len += strlen(buf->str) + 2;
2436 g_string_free(buf, TRUE);
2439 #define TRY(func) { \
2440 if (!(func)) { \
2441 return -1; \
2445 int procmime_write_mime_header(MimeInfo *mimeinfo, FILE *fp)
2447 struct TypeTable *type_table;
2448 ParametersData *pdata = g_new0(ParametersData, 1);
2449 debug_print("procmime_write_mime_header\n");
2451 pdata->fp = fp;
2452 pdata->error = FALSE;
2453 for (type_table = mime_type_table; type_table->str != NULL; type_table++)
2454 if (mimeinfo->type == type_table->type) {
2455 gchar *buf = g_strdup_printf(
2456 "Content-Type: %s/%s", type_table->str, mimeinfo->subtype);
2457 if (fprintf(fp, "%s", buf) < 0) {
2458 g_free(buf);
2459 g_free(pdata);
2460 return -1;
2462 pdata->len = strlen(buf);
2463 g_free(buf);
2464 break;
2466 g_hash_table_foreach(mimeinfo->typeparameters, write_parameters, pdata);
2467 if (pdata->error == TRUE) {
2468 g_free(pdata);
2469 return -1;
2471 g_free(pdata);
2473 TRY(fprintf(fp, "\n") >= 0);
2475 if (mimeinfo->encoding_type != ENC_UNKNOWN)
2476 TRY(fprintf(fp, "Content-Transfer-Encoding: %s\n", procmime_get_encoding_str(mimeinfo->encoding_type)) >= 0);
2478 if (mimeinfo->description != NULL)
2479 TRY(fprintf(fp, "Content-Description: %s\n", mimeinfo->description) >= 0);
2481 if (mimeinfo->id != NULL)
2482 TRY(fprintf(fp, "Content-ID: %s\n", mimeinfo->id) >= 0);
2484 if (mimeinfo->location != NULL)
2485 TRY(fprintf(fp, "Content-Location: %s\n", mimeinfo->location) >= 0);
2487 if (mimeinfo->disposition != DISPOSITIONTYPE_UNKNOWN) {
2488 ParametersData *pdata = g_new0(ParametersData, 1);
2489 gchar *buf = NULL;
2490 if (mimeinfo->disposition == DISPOSITIONTYPE_INLINE)
2491 buf = g_strdup("Content-Disposition: inline");
2492 else if (mimeinfo->disposition == DISPOSITIONTYPE_ATTACHMENT)
2493 buf = g_strdup("Content-Disposition: attachment");
2494 else
2495 buf = g_strdup("Content-Disposition: unknown");
2497 if (fprintf(fp, "%s", buf) < 0) {
2498 g_free(buf);
2499 g_free(pdata);
2500 return -1;
2502 pdata->len = strlen(buf);
2503 g_free(buf);
2505 pdata->fp = fp;
2506 pdata->error = FALSE;
2507 g_hash_table_foreach(mimeinfo->dispositionparameters, write_parameters, pdata);
2508 if (pdata->error == TRUE) {
2509 g_free(pdata);
2510 return -1;
2512 g_free(pdata);
2513 TRY(fprintf(fp, "\n") >= 0);
2516 TRY(fprintf(fp, "\n") >= 0);
2518 return 0;
2521 static gint procmime_write_message_rfc822(MimeInfo *mimeinfo, FILE *fp)
2523 FILE *infp;
2524 GNode *childnode;
2525 MimeInfo *child;
2526 gchar buf[BUFFSIZE];
2527 gboolean skip = FALSE;
2528 size_t len;
2530 debug_print("procmime_write_message_rfc822\n");
2532 /* write header */
2533 switch (mimeinfo->content) {
2534 case MIMECONTENT_FILE:
2535 if ((infp = claws_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2536 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
2537 return -1;
2539 if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
2540 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
2541 claws_fclose(infp);
2542 return -1;
2544 while (claws_fgets(buf, sizeof(buf), infp) == buf) {
2545 strcrchomp(buf);
2546 if (buf[0] == '\n' && buf[1] == '\0')
2547 break;
2548 if (skip && (buf[0] == ' ' || buf[0] == '\t'))
2549 continue;
2550 if (g_ascii_strncasecmp(buf, "MIME-Version:", 13) == 0 ||
2551 g_ascii_strncasecmp(buf, "Content-Type:", 13) == 0 ||
2552 g_ascii_strncasecmp(buf, "Content-Transfer-Encoding:", 26) == 0 ||
2553 g_ascii_strncasecmp(buf, "Content-Description:", 20) == 0 ||
2554 g_ascii_strncasecmp(buf, "Content-ID:", 11) == 0 ||
2555 g_ascii_strncasecmp(buf, "Content-Location:", 17) == 0 ||
2556 g_ascii_strncasecmp(buf, "Content-Disposition:", 20) == 0) {
2557 skip = TRUE;
2558 continue;
2560 len = strlen(buf);
2561 if (claws_fwrite(buf, sizeof(gchar), len, fp) < len) {
2562 g_warning("failed to dump %"G_GSIZE_FORMAT" bytes from file", len);
2563 claws_fclose(infp);
2564 return -1;
2566 skip = FALSE;
2568 claws_fclose(infp);
2569 break;
2571 case MIMECONTENT_MEM:
2572 len = strlen(mimeinfo->data.mem);
2573 if (claws_fwrite(mimeinfo->data.mem, sizeof(gchar), len, fp) < len) {
2574 g_warning("failed to dump %"G_GSIZE_FORMAT" bytes from mem", len);
2575 return -1;
2577 break;
2579 default:
2580 break;
2583 childnode = mimeinfo->node->children;
2584 if (childnode == NULL)
2585 return -1;
2587 child = (MimeInfo *) childnode->data;
2588 if (fprintf(fp, "MIME-Version: 1.0\n") < 0) {
2589 g_warning("failed to write mime version");
2590 return -1;
2592 if (procmime_write_mime_header(child, fp) < 0)
2593 return -1;
2594 return procmime_write_mimeinfo(child, fp);
2597 static gint procmime_write_multipart(MimeInfo *mimeinfo, FILE *fp)
2599 FILE *infp;
2600 GNode *childnode;
2601 gchar *boundary, *str, *str2;
2602 gchar buf[BUFFSIZE];
2603 gboolean firstboundary;
2604 size_t len;
2606 debug_print("procmime_write_multipart\n");
2608 boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
2610 switch (mimeinfo->content) {
2611 case MIMECONTENT_FILE:
2612 if ((infp = claws_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2613 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
2614 return -1;
2616 if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
2617 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
2618 claws_fclose(infp);
2619 return -1;
2621 while (claws_fgets(buf, sizeof(buf), infp) == buf) {
2622 if (IS_BOUNDARY(buf, boundary, strlen(boundary)))
2623 break;
2624 len = strlen(buf);
2625 if (claws_fwrite(buf, sizeof(gchar), len, fp) < len) {
2626 g_warning("failed to write %"G_GSIZE_FORMAT, len);
2627 claws_fclose(infp);
2628 return -1;
2631 claws_fclose(infp);
2632 break;
2634 case MIMECONTENT_MEM:
2635 str = g_strdup(mimeinfo->data.mem);
2636 if (((str2 = strstr(str, boundary)) != NULL) && ((str2 - str) >= 2) &&
2637 (*(str2 - 1) == '-') && (*(str2 - 2) == '-'))
2638 *(str2 - 2) = '\0';
2639 len = strlen(str);
2640 if (claws_fwrite(str, sizeof(gchar), len, fp) < len) {
2641 g_warning("failed to write %"G_GSIZE_FORMAT" from mem", len);
2642 g_free(str);
2643 return -1;
2645 g_free(str);
2646 break;
2648 default:
2649 break;
2652 childnode = mimeinfo->node->children;
2653 firstboundary = TRUE;
2654 while (childnode != NULL) {
2655 MimeInfo *child = childnode->data;
2657 if (firstboundary)
2658 firstboundary = FALSE;
2659 else
2660 TRY(fprintf(fp, "\n") >= 0);
2662 TRY(fprintf(fp, "--%s\n", boundary) >= 0);
2664 if (procmime_write_mime_header(child, fp) < 0)
2665 return -1;
2666 if (procmime_write_mimeinfo(child, fp) < 0)
2667 return -1;
2669 childnode = g_node_next_sibling(childnode);
2671 TRY(fprintf(fp, "\n--%s--\n", boundary) >= 0);
2673 return 0;
2676 gint procmime_write_mimeinfo(MimeInfo *mimeinfo, FILE *fp)
2678 FILE *infp;
2679 size_t len;
2680 debug_print("procmime_write_mimeinfo\n");
2682 if (G_NODE_IS_LEAF(mimeinfo->node)) {
2683 switch (mimeinfo->content) {
2684 case MIMECONTENT_FILE:
2685 if ((infp = claws_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2686 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
2687 return -1;
2689 copy_file_part_to_fp(infp, mimeinfo->offset, mimeinfo->length, fp);
2690 claws_fclose(infp);
2691 return 0;
2693 case MIMECONTENT_MEM:
2694 len = strlen(mimeinfo->data.mem);
2695 if (claws_fwrite(mimeinfo->data.mem, sizeof(gchar), len, fp) < len)
2696 return -1;
2697 return 0;
2699 default:
2700 return 0;
2702 } else {
2703 /* Call writer for mime type */
2704 switch (mimeinfo->type) {
2705 case MIMETYPE_MESSAGE:
2706 if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
2707 return procmime_write_message_rfc822(mimeinfo, fp);
2709 break;
2711 case MIMETYPE_MULTIPART:
2712 return procmime_write_multipart(mimeinfo, fp);
2714 default:
2715 break;
2718 return -1;
2721 return 0;
2724 gchar *procmime_get_part_file_name(MimeInfo *mimeinfo)
2726 gchar *base;
2728 if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
2729 base = g_strdup("mimetmp.html");
2730 else {
2731 const gchar *basetmp;
2732 gchar *basename;
2734 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
2735 if (basetmp == NULL)
2736 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
2737 if (basetmp == NULL)
2738 basetmp = "mimetmp";
2739 basename = g_path_get_basename(basetmp);
2740 if (*basename == '\0') {
2741 g_free(basename);
2742 basename = g_strdup("mimetmp");
2744 base = conv_filename_from_utf8(basename);
2745 g_free(basename);
2746 subst_for_shellsafe_filename(base);
2749 return base;
2752 void *procmime_get_part_as_string(MimeInfo *mimeinfo,
2753 gboolean null_terminate)
2755 FILE *infp;
2756 gchar *data;
2757 gint length, readlength;
2759 cm_return_val_if_fail(mimeinfo != NULL, NULL);
2761 if (mimeinfo->encoding_type != ENC_BINARY &&
2762 !procmime_decode_content(mimeinfo))
2763 return NULL;
2765 if (mimeinfo->content == MIMECONTENT_MEM)
2766 return g_strdup(mimeinfo->data.mem);
2768 if ((infp = claws_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2769 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
2770 return NULL;
2773 if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
2774 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
2775 claws_fclose(infp);
2776 return NULL;
2779 length = mimeinfo->length;
2781 data = g_malloc(null_terminate ? length + 1 : length);
2782 if (data == NULL) {
2783 g_warning("could not allocate %d bytes for procmime_get_part_as_string",
2784 (null_terminate ? length + 1 : length));
2785 claws_fclose(infp);
2786 return NULL;
2789 readlength = claws_fread(data, length, 1, infp);
2790 if (readlength <= 0) {
2791 FILE_OP_ERROR(mimeinfo->data.filename, "fread");
2792 g_free(data);
2793 claws_fclose(infp);
2794 return NULL;
2797 claws_fclose(infp);
2799 if (null_terminate)
2800 data[length] = '\0';
2802 return data;
2805 /* Returns an open GInputStream. The caller should just
2806 * read mimeinfo->length bytes from it and then release it. */
2807 GInputStream *procmime_get_part_as_inputstream(MimeInfo *mimeinfo)
2809 cm_return_val_if_fail(mimeinfo != NULL, NULL);
2811 if (mimeinfo->encoding_type != ENC_BINARY &&
2812 !procmime_decode_content(mimeinfo)) {
2813 g_warning("could not decode part");
2814 return NULL;
2816 if (mimeinfo->content == MIMECONTENT_MEM) {
2817 /* NULL for destroy func, since we're not copying
2818 * the data for the stream. */
2819 return g_memory_input_stream_new_from_data(
2820 mimeinfo->data.mem,
2821 mimeinfo->length, NULL);
2822 } else {
2823 return g_memory_input_stream_new_from_data(
2824 procmime_get_part_as_string(mimeinfo, FALSE),
2825 mimeinfo->length, g_free);
2829 GdkPixbuf *procmime_get_part_as_pixbuf(MimeInfo *mimeinfo, GError **error)
2831 GdkPixbuf *pixbuf;
2832 GInputStream *stream;
2834 if (error)
2835 *error = NULL;
2837 stream = procmime_get_part_as_inputstream(mimeinfo);
2838 if (stream == NULL) {
2839 if (error)
2840 *error = g_error_new_literal(G_FILE_ERROR, -1, _("Could not decode part"));
2841 return NULL;
2844 pixbuf = gdk_pixbuf_new_from_stream(stream, NULL, error);
2845 g_object_unref(stream);
2847 if (error && *error != NULL)
2848 return NULL;
2850 return pixbuf;