for release 3.17.5
[claws.git] / src / procmime.c
blobda5f13f1e2534a08896d1a9841de94cb8511799c
1 /*
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/>.
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 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)
64 MimeInfo *mimeinfo;
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);
81 return mimeinfo;
84 static gboolean procmime_mimeinfo_parameters_destroy(gpointer key, gpointer value, gpointer user_data)
86 g_free(key);
87 g_free(value);
89 return TRUE;
92 static gchar *forced_charset = NULL;
94 void procmime_force_charset(const gchar *str)
96 g_free(forced_charset);
97 forced_charset = NULL;
98 if (str)
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:
115 if (mimeinfo->tmp)
116 claws_unlink(mimeinfo->data.filename);
117 g_free(mimeinfo->data.filename);
118 break;
120 case MIMECONTENT_MEM:
121 if (mimeinfo->tmp)
122 g_free(mimeinfo->data.mem);
123 default:
124 break;
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);
142 g_free(mimeinfo);
144 return FALSE;
147 void procmime_mimeinfo_free_all(MimeInfo **mimeinfo_ptr)
149 MimeInfo *mimeinfo = *mimeinfo_ptr;
150 GNode *node;
152 if (!mimeinfo)
153 return;
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)
169 return 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)
184 return 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;
192 return NULL;
195 MimeInfo *procmime_scan_message(MsgInfo *msginfo)
197 gchar *filename;
198 MimeInfo *mimeinfo;
200 filename = procmsg_get_message_file_path(msginfo);
201 if (!filename || !is_file_exist(filename)) {
202 g_free(filename);
203 return NULL;
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);
209 else
210 mimeinfo = procmime_scan_queue_file(filename);
211 g_free(filename);
213 return mimeinfo;
216 MimeInfo *procmime_scan_message_short(MsgInfo *msginfo)
218 gchar *filename;
219 MimeInfo *mimeinfo;
221 filename = procmsg_get_message_file_path(msginfo);
222 if (!filename || !is_file_exist(filename)) {
223 g_free(filename);
224 return NULL;
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);
230 else
231 mimeinfo = procmime_scan_queue_file_short(filename);
232 g_free(filename);
234 return mimeinfo;
237 enum
239 H_CONTENT_TRANSFER_ENCODING = 0,
240 H_CONTENT_TYPE = 1,
241 H_CONTENT_DISPOSITION = 2,
242 H_CONTENT_DESCRIPTION = 3,
243 H_SUBJECT = 4
246 const gchar *procmime_mimeinfo_get_parameter(MimeInfo *mimeinfo, const gchar *name)
248 const gchar *value;
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);
254 if (value == NULL)
255 value = g_hash_table_lookup(mimeinfo->typeparameters, name);
257 return value;
260 #define FLUSH_LASTLINE() { \
261 if (*lastline != '\0') { \
262 gint llen = 0; \
263 strretchomp(lastline); \
264 llen = strlen(lastline); \
265 if (lastline[llen-1] == ' ' && !account_sigsep_matchlist_str_found(lastline, "%s") && \
266 !(llen == 2 && lastline[1] == ' ' && strchr(prefs_common.quote_chars, lastline[0]))) { \
267 /* this is flowed */ \
268 if (delsp) \
269 lastline[llen-1] = '\0'; \
270 if (claws_fputs(lastline, outfp) == EOF) \
271 err = TRUE; \
272 } else { \
273 if (claws_fputs(lastline, outfp) == EOF) \
274 err = TRUE; \
275 if (claws_fputs("\n", outfp) == EOF) \
276 err = TRUE; \
279 strcpy(lastline, buf); \
282 gboolean procmime_decode_content(MimeInfo *mimeinfo)
284 gchar buf[BUFFSIZE];
285 gint readend;
286 gchar *tmpfilename;
287 FILE *outfp, *infp;
288 GStatBuf statbuf;
289 gboolean tmp_file = FALSE;
290 gboolean flowed = FALSE;
291 gboolean delsp = FALSE;
292 gboolean err = FALSE;
293 gint state = 0;
294 guint save = 0;
296 cm_return_val_if_fail(mimeinfo != NULL, FALSE);
298 EncodingType encoding = forced_encoding
299 ? 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"))
309 flowed = TRUE;
310 if (flowed &&
311 procmime_mimeinfo_get_parameter(mimeinfo, "delsp") != NULL &&
312 !strcasecmp(procmime_mimeinfo_get_parameter(mimeinfo, "delsp"),"yes"))
313 delsp = TRUE;
316 if (!flowed && (
317 encoding == ENC_UNKNOWN ||
318 encoding == ENC_BINARY ||
319 encoding == ENC_7BIT ||
320 encoding == ENC_8BIT
322 return TRUE;
324 if (mimeinfo->type == MIMETYPE_MULTIPART || mimeinfo->type == MIMETYPE_MESSAGE)
325 return TRUE;
327 if (mimeinfo->data.filename == NULL)
328 return FALSE;
330 infp = claws_fopen(mimeinfo->data.filename, "rb");
331 if (!infp) {
332 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
333 return FALSE;
335 if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
336 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
337 claws_fclose(infp);
338 return FALSE;
341 outfp = get_tmpfile_in_dir(get_mime_tmp_dir(), &tmpfilename);
342 if (!outfp) {
343 perror("tmpfile");
344 claws_fclose(infp);
345 return FALSE;
348 tmp_file = TRUE;
349 readend = mimeinfo->offset + mimeinfo->length;
351 account_sigsep_matchlist_create(); /* FLUSH_LASTLINE will use it */
353 *buf = '\0';
354 if (encoding == ENC_QUOTED_PRINTABLE) {
355 while ((ftell(infp) < readend) && (claws_fgets(buf, sizeof(buf), infp) != NULL)) {
356 gint len;
357 len = qp_decode_line(buf);
358 buf[len] = '\0';
359 if (!flowed) {
360 if (claws_fwrite(buf, 1, len, outfp) < len)
361 err = TRUE;
362 } else {
363 FLUSH_LASTLINE();
366 if (flowed)
367 FLUSH_LASTLINE();
368 } else if (encoding == ENC_BASE64) {
369 gchar outbuf[BUFFSIZE + 1];
370 gint len, inlen, inread;
371 gboolean got_error = FALSE;
372 gboolean uncanonicalize = FALSE;
373 FILE *tmpfp = NULL;
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();
381 if (!tmpfp) {
382 perror("my_tmpfile");
383 if (tmp_file)
384 claws_fclose(outfp);
385 claws_fclose(infp);
386 return FALSE;
388 } else
389 tmpfp = outfp;
391 while ((inlen = MIN(readend - ftell(infp), sizeof(buf))) > 0 && !err) {
392 inread = claws_fread(buf, 1, inlen, infp);
393 memset(outbuf, 0, sizeof(buf));
394 len = g_base64_decode_step(buf, inlen, outbuf, &state, &save);
395 if (uncanonicalize == TRUE && strlen(outbuf) < len && starting) {
396 uncanonicalize = FALSE;
397 null_bytes = TRUE;
399 starting = FALSE;
400 if (((inread != inlen) || len < 0) && !got_error) {
401 g_warning("Bad BASE64 content.");
402 if (claws_fwrite(_("[Error decoding BASE64]\n"),
403 sizeof(gchar),
404 strlen(_("[Error decoding BASE64]\n")),
405 tmpfp) < strlen(_("[Error decoding BASE64]\n")))
406 g_warning("error decoding BASE64");
407 got_error = TRUE;
408 continue;
409 } else if (len >= 0) {
410 /* print out the error message only once
411 * per block */
412 if (null_bytes) {
413 /* we won't uncanonicalize, output to outfp directly */
414 if (claws_fwrite(outbuf, sizeof(gchar), len, outfp) < len)
415 err = TRUE;
416 } else {
417 if (claws_fwrite(outbuf, sizeof(gchar), len, tmpfp) < len)
418 err = TRUE;
420 got_error = FALSE;
424 if (uncanonicalize) {
425 rewind(tmpfp);
426 while (claws_fgets(buf, sizeof(buf), tmpfp) != NULL) {
427 strcrchomp(buf);
428 if (claws_fputs(buf, outfp) == EOF)
429 err = TRUE;
432 if (tmpfp != outfp) {
433 claws_fclose(tmpfp);
435 } else if (encoding == ENC_X_UUENCODE) {
436 gchar outbuf[BUFFSIZE];
437 gint len;
438 gboolean flag = FALSE;
440 while ((ftell(infp) < readend) && (claws_fgets(buf, sizeof(buf), infp) != NULL)) {
441 if (!flag && strncmp(buf,"begin ", 6)) continue;
443 if (flag) {
444 len = fromuutobits(outbuf, buf);
445 if (len <= 0) {
446 if (len < 0)
447 g_warning("Bad UUENCODE content (%d)", len);
448 break;
450 if (claws_fwrite(outbuf, sizeof(gchar), len, outfp) < len)
451 err = TRUE;
452 } else
453 flag = TRUE;
455 } else {
456 while ((ftell(infp) < readend) && (claws_fgets(buf, sizeof(buf), infp) != NULL)) {
457 if (!flowed) {
458 if (claws_fputs(buf, outfp) == EOF)
459 err = TRUE;
460 } else {
461 FLUSH_LASTLINE();
464 if (flowed)
465 FLUSH_LASTLINE();
466 if (err == TRUE)
467 g_warning("write error");
470 claws_fclose(outfp);
471 claws_fclose(infp);
473 account_sigsep_matchlist_delete();
475 if (err == TRUE) {
476 return FALSE;
479 if (g_stat(tmpfilename, &statbuf) < 0) {
480 FILE_OP_ERROR(tmpfilename, "stat");
481 return FALSE;
484 if (mimeinfo->tmp)
485 claws_unlink(mimeinfo->data.filename);
486 g_free(mimeinfo->data.filename);
487 mimeinfo->data.filename = tmpfilename;
488 mimeinfo->tmp = TRUE;
489 mimeinfo->offset = 0;
490 mimeinfo->length = statbuf.st_size;
491 mimeinfo->encoding_type = ENC_BINARY;
493 return TRUE;
496 #define B64_LINE_SIZE 57
497 #define B64_BUFFSIZE 77
499 gboolean procmime_encode_content(MimeInfo *mimeinfo, EncodingType encoding)
501 FILE *infp = NULL, *outfp;
502 gint len;
503 gchar *tmpfilename;
504 GStatBuf statbuf;
505 gboolean err = FALSE;
507 if (mimeinfo->content == MIMECONTENT_EMPTY)
508 return TRUE;
510 if (mimeinfo->encoding_type != ENC_UNKNOWN &&
511 mimeinfo->encoding_type != ENC_BINARY &&
512 mimeinfo->encoding_type != ENC_7BIT &&
513 mimeinfo->encoding_type != ENC_8BIT)
514 if(!procmime_decode_content(mimeinfo))
515 return FALSE;
517 outfp = get_tmpfile_in_dir(get_mime_tmp_dir(), &tmpfilename);
518 if (!outfp) {
519 perror("tmpfile");
520 return FALSE;
523 if (mimeinfo->content == MIMECONTENT_FILE && mimeinfo->data.filename) {
524 if ((infp = claws_fopen(mimeinfo->data.filename, "rb")) == NULL) {
525 g_warning("Can't open file %s", mimeinfo->data.filename);
526 claws_fclose(outfp);
527 return FALSE;
529 } else if (mimeinfo->content == MIMECONTENT_MEM) {
530 infp = str_open_as_stream(mimeinfo->data.mem);
531 if (infp == NULL) {
532 claws_fclose(outfp);
533 return FALSE;
535 } else {
536 claws_fclose(outfp);
537 g_warning("Unknown mimeinfo");
538 return FALSE;
541 if (encoding == ENC_BASE64) {
542 gchar inbuf[B64_LINE_SIZE], *out;
543 FILE *tmp_fp = infp;
544 gchar *tmp_file = NULL;
546 if (mimeinfo->type == MIMETYPE_TEXT ||
547 mimeinfo->type == MIMETYPE_MESSAGE) {
548 if (mimeinfo->content == MIMECONTENT_FILE) {
549 tmp_file = get_tmp_file();
550 if (canonicalize_file(mimeinfo->data.filename, tmp_file) < 0) {
551 g_free(tmp_file);
552 claws_fclose(infp);
553 claws_fclose(outfp);
554 return FALSE;
556 if ((tmp_fp = claws_fopen(tmp_file, "rb")) == NULL) {
557 FILE_OP_ERROR(tmp_file, "claws_fopen");
558 claws_unlink(tmp_file);
559 g_free(tmp_file);
560 claws_fclose(infp);
561 claws_fclose(outfp);
562 return FALSE;
564 } else {
565 gchar *out = canonicalize_str(mimeinfo->data.mem);
566 claws_fclose(infp);
567 infp = str_open_as_stream(out);
568 tmp_fp = infp;
569 g_free(out);
570 if (infp == NULL) {
571 claws_fclose(outfp);
572 return FALSE;
577 while ((len = claws_fread(inbuf, sizeof(gchar),
578 B64_LINE_SIZE, tmp_fp))
579 == B64_LINE_SIZE) {
580 out = g_base64_encode(inbuf, B64_LINE_SIZE);
581 if (claws_fputs(out, outfp) == EOF)
582 err = TRUE;
583 g_free(out);
584 if (claws_fputc('\n', outfp) == EOF)
585 err = TRUE;
587 if (len > 0 && claws_feof(tmp_fp)) {
588 out = g_base64_encode(inbuf, len);
589 if (claws_fputs(out, outfp) == EOF)
590 err = TRUE;
591 g_free(out);
592 if (claws_fputc('\n', outfp) == EOF)
593 err = TRUE;
596 if (tmp_file) {
597 claws_fclose(tmp_fp);
598 claws_unlink(tmp_file);
599 g_free(tmp_file);
601 } else if (encoding == ENC_QUOTED_PRINTABLE) {
602 gchar inbuf[BUFFSIZE], outbuf[BUFFSIZE * 4];
604 while (claws_fgets(inbuf, sizeof(inbuf), infp) != NULL) {
605 qp_encode_line(outbuf, inbuf);
607 if (!strncmp("From ", outbuf, sizeof("From ")-1)) {
608 gchar *tmpbuf = outbuf;
610 tmpbuf += sizeof("From ")-1;
612 if (claws_fputs("=46rom ", outfp) == EOF)
613 err = TRUE;
614 if (claws_fputs(tmpbuf, outfp) == EOF)
615 err = TRUE;
616 } else {
617 if (claws_fputs(outbuf, outfp) == EOF)
618 err = TRUE;
621 } else {
622 gchar buf[BUFFSIZE];
624 while (claws_fgets(buf, sizeof(buf), infp) != NULL) {
625 strcrchomp(buf);
626 if (claws_fputs(buf, outfp) == EOF)
627 err = TRUE;
631 claws_fclose(outfp);
632 claws_fclose(infp);
634 if (err == TRUE)
635 return FALSE;
637 if (mimeinfo->content == MIMECONTENT_FILE) {
638 if (mimeinfo->tmp && (mimeinfo->data.filename != NULL))
639 claws_unlink(mimeinfo->data.filename);
640 g_free(mimeinfo->data.filename);
641 } else if (mimeinfo->content == MIMECONTENT_MEM) {
642 if (mimeinfo->tmp && (mimeinfo->data.mem != NULL))
643 g_free(mimeinfo->data.mem);
646 if (g_stat(tmpfilename, &statbuf) < 0) {
647 FILE_OP_ERROR(tmpfilename, "stat");
648 return FALSE;
650 mimeinfo->content = MIMECONTENT_FILE;
651 mimeinfo->data.filename = tmpfilename;
652 mimeinfo->tmp = TRUE;
653 mimeinfo->offset = 0;
654 mimeinfo->length = statbuf.st_size;
655 mimeinfo->encoding_type = encoding;
657 return TRUE;
660 static gint procmime_get_part_to_stream(FILE *outfp, MimeInfo *mimeinfo)
662 FILE *infp;
663 gchar buf[BUFFSIZE];
664 gint restlength, readlength;
665 gint saved_errno = 0;
667 cm_return_val_if_fail(outfp != NULL, -1);
668 cm_return_val_if_fail(mimeinfo != NULL, -1);
670 if (mimeinfo->encoding_type != ENC_BINARY && !procmime_decode_content(mimeinfo))
671 return -EINVAL;
673 if ((infp = claws_fopen(mimeinfo->data.filename, "rb")) == NULL) {
674 saved_errno = errno;
675 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
676 return -(saved_errno);
678 if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
679 saved_errno = errno;
680 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
681 claws_fclose(infp);
682 return -(saved_errno);
685 restlength = mimeinfo->length;
687 while ((restlength > 0) && ((readlength = claws_fread(buf, 1, restlength > BUFFSIZE ? BUFFSIZE : restlength, infp)) > 0)) {
688 if (claws_fwrite(buf, 1, readlength, outfp) != readlength) {
689 saved_errno = errno;
690 claws_fclose(infp);
691 return -(saved_errno);
693 restlength -= readlength;
696 claws_fclose(infp);
697 rewind(outfp);
699 return 0;
702 gint procmime_get_part(const gchar *outfile, MimeInfo *mimeinfo)
704 FILE *outfp;
705 gint result;
706 gint saved_errno = 0;
708 cm_return_val_if_fail(outfile != NULL, -1);
710 if ((outfp = claws_fopen(outfile, "wb")) == NULL) {
711 saved_errno = errno;
712 FILE_OP_ERROR(outfile, "claws_fopen");
713 return -(saved_errno);
716 result = procmime_get_part_to_stream(outfp, mimeinfo);
718 if (claws_fclose(outfp) == EOF) {
719 saved_errno = errno;
720 FILE_OP_ERROR(outfile, "claws_fclose");
721 claws_unlink(outfile);
722 return -(saved_errno);
725 return result;
728 gboolean procmime_scan_text_content(MimeInfo *mimeinfo,
729 gboolean (*scan_callback)(const gchar *str, gpointer cb_data),
730 gpointer cb_data)
732 FILE *tmpfp;
733 const gchar *src_codeset;
734 gboolean conv_fail = FALSE;
735 gchar buf[BUFFSIZE];
736 gchar *str;
737 gboolean scan_ret = FALSE;
738 int r;
740 cm_return_val_if_fail(mimeinfo != NULL, TRUE);
741 cm_return_val_if_fail(scan_callback != NULL, TRUE);
743 if (!procmime_decode_content(mimeinfo))
744 return TRUE;
746 tmpfp = my_tmpfile();
748 if (tmpfp == NULL) {
749 FILE_OP_ERROR("tmpfile", "open");
750 return TRUE;
753 if ((r = procmime_get_part_to_stream(tmpfp, mimeinfo)) < 0) {
754 g_warning("procmime_get_part_to_stream error %d\n", r);
755 return TRUE;
758 src_codeset = forced_charset
759 ? forced_charset :
760 procmime_mimeinfo_get_parameter(mimeinfo, "charset");
762 /* use supersets transparently when possible */
763 if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_ISO_8859_1))
764 src_codeset = CS_WINDOWS_1252;
765 else if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_X_GBK))
766 src_codeset = CS_GB18030;
767 else if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_GBK))
768 src_codeset = CS_GB18030;
769 else if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_GB2312))
770 src_codeset = CS_GB18030;
771 else if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_X_VIET_VPS))
772 src_codeset = CS_WINDOWS_874;
774 if (mimeinfo->type == MIMETYPE_TEXT && !g_ascii_strcasecmp(mimeinfo->subtype, "html")) {
775 SC_HTMLParser *parser;
776 CodeConverter *conv;
778 conv = conv_code_converter_new(src_codeset);
779 parser = sc_html_parser_new(tmpfp, conv);
780 while ((str = sc_html_parse(parser)) != NULL) {
781 if ((scan_ret = scan_callback(str, cb_data)) == TRUE)
782 break;
784 sc_html_parser_destroy(parser);
785 conv_code_converter_destroy(conv);
786 } else if (mimeinfo->type == MIMETYPE_TEXT && !g_ascii_strcasecmp(mimeinfo->subtype, "enriched")) {
787 ERTFParser *parser;
788 CodeConverter *conv;
790 conv = conv_code_converter_new(src_codeset);
791 parser = ertf_parser_new(tmpfp, conv);
792 while ((str = ertf_parse(parser)) != NULL) {
793 if ((scan_ret = scan_callback(str, cb_data)) == TRUE)
794 break;
796 ertf_parser_destroy(parser);
797 conv_code_converter_destroy(conv);
798 } else if (mimeinfo->type == MIMETYPE_TEXT && mimeinfo->disposition != DISPOSITIONTYPE_ATTACHMENT) {
799 while (claws_fgets(buf, sizeof(buf), tmpfp) != NULL) {
800 str = conv_codeset_strdup(buf, src_codeset, CS_UTF_8);
801 if (str) {
802 if ((scan_ret = scan_callback(str, cb_data)) == TRUE) {
803 g_free(str);
804 break;
806 g_free(str);
807 } else {
808 conv_fail = TRUE;
809 if ((scan_ret = scan_callback(buf, cb_data)) == TRUE)
810 break;
815 if (conv_fail)
816 g_warning("procmime_get_text_content(): Code conversion failed.");
818 claws_fclose(tmpfp);
820 return scan_ret;
823 static gboolean scan_fputs_cb(const gchar *str, gpointer fp)
825 if (claws_fputs(str, (FILE *)fp) == EOF)
826 return TRUE;
828 return FALSE;
831 FILE *procmime_get_text_content(MimeInfo *mimeinfo)
833 FILE *outfp;
834 gboolean err;
836 if ((outfp = my_tmpfile()) == NULL) {
837 perror("my_tmpfile");
838 return NULL;
841 err = procmime_scan_text_content(mimeinfo, scan_fputs_cb, outfp);
843 rewind(outfp);
844 if (err == TRUE) {
845 claws_fclose(outfp);
846 return NULL;
848 return outfp;
852 FILE *procmime_get_binary_content(MimeInfo *mimeinfo)
854 FILE *outfp;
856 cm_return_val_if_fail(mimeinfo != NULL, NULL);
858 if (!procmime_decode_content(mimeinfo))
859 return NULL;
861 outfp = my_tmpfile();
863 if (procmime_get_part_to_stream(outfp, mimeinfo) < 0) {
864 return NULL;
867 return outfp;
870 /* search the first text part of (multipart) MIME message,
871 decode, convert it and output to outfp. */
872 FILE *procmime_get_first_text_content(MsgInfo *msginfo)
874 FILE *outfp = NULL;
875 MimeInfo *mimeinfo, *partinfo;
876 gboolean empty_ok = FALSE, short_scan = TRUE;
878 cm_return_val_if_fail(msginfo != NULL, NULL);
880 /* first we try to short-scan (for speed), refusing empty parts */
881 scan_again:
882 if (short_scan)
883 mimeinfo = procmime_scan_message_short(msginfo);
884 else
885 mimeinfo = procmime_scan_message(msginfo);
886 if (!mimeinfo) return NULL;
888 partinfo = mimeinfo;
889 while (partinfo && (partinfo->type != MIMETYPE_TEXT ||
890 (partinfo->length == 0 && !empty_ok))) {
891 partinfo = procmime_mimeinfo_next(partinfo);
893 if (partinfo)
894 outfp = procmime_get_text_content(partinfo);
895 else if (!empty_ok && short_scan) {
896 /* if short scan didn't find a non-empty part, rescan
897 * fully for non-empty parts
899 short_scan = FALSE;
900 procmime_mimeinfo_free_all(&mimeinfo);
901 goto scan_again;
902 } else if (!empty_ok && !short_scan) {
903 /* if full scan didn't find a non-empty part, rescan
904 * accepting empty parts
906 empty_ok = TRUE;
907 procmime_mimeinfo_free_all(&mimeinfo);
908 goto scan_again;
910 procmime_mimeinfo_free_all(&mimeinfo);
912 return outfp;
916 static gboolean find_encrypted_func(GNode *node, gpointer data)
918 MimeInfo *mimeinfo = (MimeInfo *) node->data;
919 MimeInfo **encinfo = (MimeInfo **) data;
921 if (privacy_mimeinfo_is_encrypted(mimeinfo)) {
922 *encinfo = mimeinfo;
923 return TRUE;
926 return FALSE;
929 static MimeInfo *find_encrypted_part(MimeInfo *rootinfo)
931 MimeInfo *encinfo = NULL;
933 g_node_traverse(rootinfo->node, G_IN_ORDER, G_TRAVERSE_ALL, -1,
934 find_encrypted_func, &encinfo);
936 return encinfo;
939 /* search the first encrypted text part of (multipart) MIME message,
940 decode, convert it and output to outfp. */
941 FILE *procmime_get_first_encrypted_text_content(MsgInfo *msginfo)
943 FILE *outfp = NULL;
944 MimeInfo *mimeinfo, *partinfo, *encinfo;
946 cm_return_val_if_fail(msginfo != NULL, NULL);
948 mimeinfo = procmime_scan_message(msginfo);
949 if (!mimeinfo) {
950 return NULL;
953 partinfo = mimeinfo;
954 if ((encinfo = find_encrypted_part(partinfo)) != NULL) {
955 debug_print("decrypting message part\n");
956 if (privacy_mimeinfo_decrypt(encinfo) < 0) {
957 alertpanel_error(_("Couldn't decrypt: %s"),
958 privacy_get_error());
959 return NULL;
962 partinfo = mimeinfo;
963 while (partinfo && partinfo->type != MIMETYPE_TEXT) {
964 partinfo = procmime_mimeinfo_next(partinfo);
965 if (privacy_mimeinfo_is_signed(partinfo))
966 procmsg_msginfo_set_flags(msginfo, 0, MSG_SIGNED);
969 if (partinfo)
970 outfp = procmime_get_text_content(partinfo);
972 procmime_mimeinfo_free_all(&mimeinfo);
974 return outfp;
977 gboolean procmime_msginfo_is_encrypted(MsgInfo *msginfo)
979 MimeInfo *mimeinfo, *partinfo;
980 gboolean result = FALSE;
982 cm_return_val_if_fail(msginfo != NULL, FALSE);
984 mimeinfo = procmime_scan_message(msginfo);
985 if (!mimeinfo) {
986 return FALSE;
989 partinfo = mimeinfo;
990 result = (find_encrypted_part(partinfo) != NULL);
991 procmime_mimeinfo_free_all(&mimeinfo);
993 return result;
996 gchar *procmime_get_tmp_file_name(MimeInfo *mimeinfo)
998 static guint32 id = 0;
999 gchar *base;
1000 gchar *filename;
1001 gchar f_prefix[10];
1003 cm_return_val_if_fail(mimeinfo != NULL, NULL);
1005 g_snprintf(f_prefix, sizeof(f_prefix), "%08x.", id++);
1007 if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
1008 base = g_strdup("mimetmp.html");
1009 else {
1010 const gchar *basetmp;
1012 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
1013 if (basetmp == NULL)
1014 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
1015 if (basetmp == NULL)
1016 basetmp = "mimetmp";
1017 basetmp = g_path_get_basename(basetmp);
1018 if (*basetmp == '\0')
1019 basetmp = g_strdup("mimetmp");
1020 base = conv_filename_from_utf8(basetmp);
1021 g_free((gchar*)basetmp);
1022 subst_for_shellsafe_filename(base);
1025 filename = g_strconcat(get_mime_tmp_dir(), G_DIR_SEPARATOR_S,
1026 f_prefix, base, NULL);
1028 g_free(base);
1030 return filename;
1033 static GList *mime_type_list = NULL;
1035 gchar *procmime_get_mime_type(const gchar *filename)
1037 const gchar *p;
1038 gchar *ext = NULL;
1039 gchar *base;
1040 #ifndef G_OS_WIN32
1041 static GHashTable *mime_type_table = NULL;
1042 MimeType *mime_type;
1044 if (!mime_type_table) {
1045 mime_type_table = procmime_get_mime_type_table();
1046 if (!mime_type_table) return NULL;
1048 #endif
1050 if (filename == NULL)
1051 return NULL;
1053 base = g_path_get_basename(filename);
1054 if ((p = strrchr(base, '.')) != NULL)
1055 ext = g_utf8_strdown(p + 1, -1);
1056 else
1057 ext = g_utf8_strdown(base, -1);
1058 g_free(base);
1060 #ifndef G_OS_WIN32
1061 mime_type = g_hash_table_lookup(mime_type_table, ext);
1063 if (mime_type) {
1064 gchar *str;
1065 str = g_strconcat(mime_type->type, "/", mime_type->sub_type,
1066 NULL);
1067 debug_print("got type %s for %s\n", str, ext);
1068 g_free(ext);
1069 return str;
1071 g_free(ext);
1072 return NULL;
1073 #else
1074 gchar *str = get_content_type_from_registry_with_ext(ext);
1076 g_free(ext);
1077 return str;
1078 #endif
1081 static guint procmime_str_hash(gconstpointer gptr)
1083 guint hash_result = 0;
1084 const char *str;
1086 for (str = gptr; str && *str; str++) {
1087 if (isupper(*str)) hash_result += (*str + ' ');
1088 else hash_result += *str;
1091 return hash_result;
1094 static gint procmime_str_equal(gconstpointer gptr1, gconstpointer gptr2)
1096 const char *str1 = gptr1;
1097 const char *str2 = gptr2;
1099 return !g_utf8_collate(str1, str2);
1102 static GHashTable *procmime_get_mime_type_table(void)
1104 GHashTable *table = NULL;
1105 GList *cur;
1106 MimeType *mime_type;
1107 gchar **exts;
1109 if (!mime_type_list) {
1110 mime_type_list = procmime_get_mime_type_list();
1111 if (!mime_type_list) return NULL;
1114 table = g_hash_table_new(procmime_str_hash, procmime_str_equal);
1116 for (cur = mime_type_list; cur != NULL; cur = cur->next) {
1117 gint i;
1118 gchar *key;
1120 mime_type = (MimeType *)cur->data;
1122 if (!mime_type->extension) continue;
1124 exts = g_strsplit(mime_type->extension, " ", 16);
1125 for (i = 0; exts[i] != NULL; i++) {
1126 /* Don't overwrite previously inserted extension */
1127 if (!g_hash_table_lookup(table, exts[i])) {
1128 key = g_strdup(exts[i]);
1129 g_hash_table_insert(table, key, mime_type);
1132 g_strfreev(exts);
1135 return table;
1138 GList *procmime_get_mime_type_list(void)
1140 GList *list = NULL;
1141 FILE *fp;
1142 gchar buf[BUFFSIZE];
1143 gchar *p;
1144 gchar *delim;
1145 MimeType *mime_type;
1146 gboolean fp_is_glob_file = TRUE;
1148 if (mime_type_list)
1149 return mime_type_list;
1151 #if defined(__NetBSD__) || defined(__OpenBSD__) || defined(__FreeBSD__)
1152 if ((fp = claws_fopen(DATAROOTDIR "/mime/globs", "rb")) == NULL)
1153 #else
1154 if ((fp = claws_fopen("/usr/share/mime/globs", "rb")) == NULL)
1155 #endif
1157 fp_is_glob_file = FALSE;
1158 if ((fp = claws_fopen("/etc/mime.types", "rb")) == NULL) {
1159 if ((fp = claws_fopen(SYSCONFDIR "/mime.types", "rb"))
1160 == NULL) {
1161 FILE_OP_ERROR(SYSCONFDIR "/mime.types",
1162 "claws_fopen");
1163 return NULL;
1168 while (claws_fgets(buf, sizeof(buf), fp) != NULL) {
1169 p = strchr(buf, '#');
1170 if (p) *p = '\0';
1171 g_strstrip(buf);
1173 p = buf;
1175 if (fp_is_glob_file) {
1176 while (*p && !g_ascii_isspace(*p) && (*p!=':')) p++;
1177 } else {
1178 while (*p && !g_ascii_isspace(*p)) p++;
1181 if (*p) {
1182 *p = '\0';
1183 p++;
1185 delim = strchr(buf, '/');
1186 if (delim == NULL) continue;
1187 *delim = '\0';
1189 mime_type = g_new(MimeType, 1);
1190 mime_type->type = g_strdup(buf);
1191 mime_type->sub_type = g_strdup(delim + 1);
1193 if (fp_is_glob_file) {
1194 while (*p && (g_ascii_isspace(*p)||(*p=='*')||(*p=='.'))) p++;
1195 } else {
1196 while (*p && g_ascii_isspace(*p)) p++;
1199 if (*p)
1200 mime_type->extension = g_utf8_strdown(p, -1);
1201 else
1202 mime_type->extension = NULL;
1204 list = g_list_append(list, mime_type);
1207 claws_fclose(fp);
1209 if (!list)
1210 g_warning("Can't read mime.types");
1212 return list;
1215 EncodingType procmime_get_encoding_for_charset(const gchar *charset)
1217 if (!charset)
1218 return ENC_8BIT;
1219 else if (!g_ascii_strncasecmp(charset, "ISO-2022-", 9) ||
1220 !g_ascii_strcasecmp(charset, "US-ASCII"))
1221 return ENC_7BIT;
1222 else if (!g_ascii_strcasecmp(charset, "ISO-8859-5") ||
1223 !g_ascii_strncasecmp(charset, "KOI8-", 5) ||
1224 !g_ascii_strcasecmp(charset, "X-MAC-CYRILLIC") ||
1225 !g_ascii_strcasecmp(charset, "MAC-CYRILLIC") ||
1226 !g_ascii_strcasecmp(charset, "Windows-1251"))
1227 return ENC_8BIT;
1228 else if (!g_ascii_strncasecmp(charset, "ISO-8859-", 9))
1229 return ENC_QUOTED_PRINTABLE;
1230 else if (!g_ascii_strncasecmp(charset, "UTF-8", 5))
1231 return ENC_QUOTED_PRINTABLE;
1232 else
1233 return ENC_8BIT;
1236 EncodingType procmime_get_encoding_for_text_file(const gchar *file, gboolean *has_binary)
1238 FILE *fp;
1239 guchar buf[BUFFSIZE];
1240 size_t len;
1241 size_t octet_chars = 0;
1242 size_t total_len = 0;
1243 gfloat octet_percentage;
1244 gboolean force_b64 = FALSE;
1246 if ((fp = claws_fopen(file, "rb")) == NULL) {
1247 FILE_OP_ERROR(file, "claws_fopen");
1248 return ENC_UNKNOWN;
1251 while ((len = claws_fread(buf, sizeof(guchar), sizeof(buf), fp)) > 0) {
1252 guchar *p;
1253 gint i;
1255 for (p = buf, i = 0; i < len; ++p, ++i) {
1256 if (*p & 0x80)
1257 ++octet_chars;
1258 if (*p == '\0') {
1259 force_b64 = TRUE;
1260 *has_binary = TRUE;
1263 total_len += len;
1266 claws_fclose(fp);
1268 if (total_len > 0)
1269 octet_percentage = (gfloat)octet_chars / (gfloat)total_len;
1270 else
1271 octet_percentage = 0.0;
1273 debug_print("procmime_get_encoding_for_text_file(): "
1274 "8bit chars: %"G_GSIZE_FORMAT" / %"G_GSIZE_FORMAT" (%f%%)\n", octet_chars, total_len,
1275 100.0 * octet_percentage);
1277 if (octet_percentage > 0.20 || force_b64) {
1278 debug_print("using BASE64\n");
1279 return ENC_BASE64;
1280 } else if (octet_chars > 0) {
1281 debug_print("using quoted-printable\n");
1282 return ENC_QUOTED_PRINTABLE;
1283 } else {
1284 debug_print("using 7bit\n");
1285 return ENC_7BIT;
1289 struct EncodingTable
1291 gchar *str;
1292 EncodingType enc_type;
1295 struct EncodingTable encoding_table[] = {
1296 {"7bit", ENC_7BIT},
1297 {"8bit", ENC_8BIT},
1298 {"binary", ENC_BINARY},
1299 {"quoted-printable", ENC_QUOTED_PRINTABLE},
1300 {"base64", ENC_BASE64},
1301 {"x-uuencode", ENC_UNKNOWN},
1302 {NULL, ENC_UNKNOWN},
1305 const gchar *procmime_get_encoding_str(EncodingType encoding)
1307 struct EncodingTable *enc_table;
1309 for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1310 if (enc_table->enc_type == encoding)
1311 return enc_table->str;
1313 return NULL;
1316 /* --- NEW MIME STUFF --- */
1317 struct TypeTable
1319 gchar *str;
1320 MimeMediaType type;
1323 static struct TypeTable mime_type_table[] = {
1324 {"text", MIMETYPE_TEXT},
1325 {"image", MIMETYPE_IMAGE},
1326 {"audio", MIMETYPE_AUDIO},
1327 {"video", MIMETYPE_VIDEO},
1328 {"model", MIMETYPE_MODEL},
1329 {"application", MIMETYPE_APPLICATION},
1330 {"message", MIMETYPE_MESSAGE},
1331 {"multipart", MIMETYPE_MULTIPART},
1332 {NULL, 0},
1335 const gchar *procmime_get_media_type_str(MimeMediaType type)
1337 struct TypeTable *type_table;
1339 for (type_table = mime_type_table; type_table->str != NULL; type_table++) {
1340 if (type_table->type == type)
1341 return type_table->str;
1343 return NULL;
1346 MimeMediaType procmime_get_media_type(const gchar *str)
1348 struct TypeTable *typetablearray;
1350 for (typetablearray = mime_type_table; typetablearray->str != NULL; typetablearray++)
1351 if (g_ascii_strncasecmp(str, typetablearray->str, strlen(typetablearray->str)) == 0)
1352 return typetablearray->type;
1354 return MIMETYPE_UNKNOWN;
1358 *\brief Safe wrapper for content type string.
1360 *\return const gchar * Pointer to content type string.
1362 gchar *procmime_get_content_type_str(MimeMediaType type,
1363 const char *subtype)
1365 const gchar *type_str = NULL;
1367 if (subtype == NULL || !(type_str = procmime_get_media_type_str(type)))
1368 return g_strdup("unknown");
1369 return g_strdup_printf("%s/%s", type_str, subtype);
1372 static int procmime_parse_mimepart(MimeInfo *parent,
1373 gchar *content_type,
1374 gchar *content_encoding,
1375 gchar *content_description,
1376 gchar *content_id,
1377 gchar *content_disposition,
1378 gchar *content_location,
1379 const gchar *original_msgid,
1380 const gchar *disposition_notification_hdr,
1381 const gchar *filename,
1382 guint offset,
1383 guint length,
1384 gboolean short_scan);
1386 static void procmime_parse_message_rfc822(MimeInfo *mimeinfo, gboolean short_scan)
1388 HeaderEntry hentry[] = {{"Content-Type:", NULL, TRUE},
1389 {"Content-Transfer-Encoding:",
1390 NULL, FALSE},
1391 {"Content-Description:",
1392 NULL, TRUE},
1393 {"Content-ID:",
1394 NULL, TRUE},
1395 {"Content-Disposition:",
1396 NULL, TRUE},
1397 {"Content-Location:",
1398 NULL, TRUE},
1399 {"MIME-Version:",
1400 NULL, TRUE},
1401 {"Original-Message-ID:",
1402 NULL, TRUE},
1403 {"Disposition:",
1404 NULL, TRUE},
1405 {NULL, NULL, FALSE}};
1406 guint content_start, i;
1407 FILE *fp;
1408 gchar *tmp;
1409 gint len = 0;
1411 procmime_decode_content(mimeinfo);
1413 fp = claws_fopen(mimeinfo->data.filename, "rb");
1414 if (fp == NULL) {
1415 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
1416 return;
1418 if (fseek(fp, mimeinfo->offset, SEEK_SET) < 0) {
1419 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
1420 claws_fclose(fp);
1421 return;
1423 procheader_get_header_fields(fp, hentry);
1424 if (hentry[0].body != NULL) {
1425 tmp = conv_unmime_header(hentry[0].body, NULL, FALSE);
1426 g_free(hentry[0].body);
1427 hentry[0].body = tmp;
1429 if (hentry[2].body != NULL) {
1430 tmp = conv_unmime_header(hentry[2].body, NULL, FALSE);
1431 g_free(hentry[2].body);
1432 hentry[2].body = tmp;
1434 if (hentry[4].body != NULL) {
1435 tmp = conv_unmime_header(hentry[4].body, NULL, FALSE);
1436 g_free(hentry[4].body);
1437 hentry[4].body = tmp;
1439 if (hentry[5].body != NULL) {
1440 tmp = conv_unmime_header(hentry[5].body, NULL, FALSE);
1441 g_free(hentry[5].body);
1442 hentry[5].body = tmp;
1444 if (hentry[7].body != NULL) {
1445 tmp = conv_unmime_header(hentry[7].body, NULL, FALSE);
1446 g_free(hentry[7].body);
1447 hentry[7].body = tmp;
1449 if (hentry[8].body != NULL) {
1450 tmp = conv_unmime_header(hentry[8].body, NULL, FALSE);
1451 g_free(hentry[8].body);
1452 hentry[8].body = tmp;
1455 content_start = ftell(fp);
1456 claws_fclose(fp);
1458 len = mimeinfo->length - (content_start - mimeinfo->offset);
1459 if (len < 0)
1460 len = 0;
1461 procmime_parse_mimepart(mimeinfo,
1462 hentry[0].body, hentry[1].body,
1463 hentry[2].body, hentry[3].body,
1464 hentry[4].body, hentry[5].body,
1465 hentry[7].body, hentry[8].body,
1466 mimeinfo->data.filename, content_start,
1467 len, short_scan);
1469 for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1470 g_free(hentry[i].body);
1471 hentry[i].body = NULL;
1475 static void procmime_parse_disposition_notification(MimeInfo *mimeinfo,
1476 const gchar *original_msgid, const gchar *disposition_notification_hdr,
1477 gboolean short_scan)
1479 HeaderEntry hentry[] = {{"Original-Message-ID:", NULL, TRUE},
1480 {"Disposition:", NULL, TRUE},
1481 {NULL, NULL, FALSE}};
1482 guint i;
1483 FILE *fp;
1484 gchar *orig_msg_id = NULL;
1485 gchar *disp = NULL;
1487 procmime_decode_content(mimeinfo);
1489 debug_print("parse disposition notification\n");
1490 fp = claws_fopen(mimeinfo->data.filename, "rb");
1491 if (fp == NULL) {
1492 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
1493 return;
1495 if (fseek(fp, mimeinfo->offset, SEEK_SET) < 0) {
1496 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
1497 claws_fclose(fp);
1498 return;
1501 if (original_msgid && disposition_notification_hdr) {
1502 hentry[0].body = g_strdup(original_msgid);
1503 hentry[1].body = g_strdup(disposition_notification_hdr);
1504 } else {
1505 procheader_get_header_fields(fp, hentry);
1508 claws_fclose(fp);
1510 if (!hentry[0].body || !hentry[1].body) {
1511 debug_print("MsgId %s, Disp %s\n",
1512 hentry[0].body ? hentry[0].body:"(nil)",
1513 hentry[1].body ? hentry[1].body:"(nil)");
1514 goto bail;
1517 orig_msg_id = g_strdup(hentry[0].body);
1518 disp = g_strdup(hentry[1].body);
1520 extract_parenthesis(orig_msg_id, '<', '>');
1521 remove_space(orig_msg_id);
1523 if (strstr(disp, "displayed")) {
1524 /* find sent message, if possible */
1525 MsgInfo *info = NULL;
1526 GList *flist;
1527 debug_print("%s has been displayed.\n", orig_msg_id);
1528 for (flist = folder_get_list(); flist != NULL; flist = g_list_next(flist)) {
1529 FolderItem *outbox = ((Folder *)(flist->data))->outbox;
1530 if (!outbox) {
1531 debug_print("skipping folder with no outbox...\n");
1532 continue;
1534 info = folder_item_get_msginfo_by_msgid(outbox, orig_msg_id);
1535 debug_print("%s %s in %s\n", info?"found":"didn't find", orig_msg_id, outbox->path);
1536 if (info) {
1537 procmsg_msginfo_set_flags(info, MSG_RETRCPT_GOT, 0);
1538 procmsg_msginfo_free(&info);
1542 g_free(orig_msg_id);
1543 g_free(disp);
1544 bail:
1545 for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1546 g_free(hentry[i].body);
1547 hentry[i].body = NULL;
1551 #define GET_HEADERS() { \
1552 procheader_get_header_fields(fp, hentry); \
1553 if (hentry[0].body != NULL) { \
1554 tmp = conv_unmime_header(hentry[0].body, NULL, FALSE); \
1555 g_free(hentry[0].body); \
1556 hentry[0].body = tmp; \
1558 if (hentry[2].body != NULL) { \
1559 tmp = conv_unmime_header(hentry[2].body, NULL, FALSE); \
1560 g_free(hentry[2].body); \
1561 hentry[2].body = tmp; \
1563 if (hentry[4].body != NULL) { \
1564 tmp = conv_unmime_header(hentry[4].body, NULL, FALSE); \
1565 g_free(hentry[4].body); \
1566 hentry[4].body = tmp; \
1568 if (hentry[5].body != NULL) { \
1569 tmp = conv_unmime_header(hentry[5].body, NULL, FALSE); \
1570 g_free(hentry[5].body); \
1571 hentry[5].body = tmp; \
1573 if (hentry[6].body != NULL) { \
1574 tmp = conv_unmime_header(hentry[6].body, NULL, FALSE); \
1575 g_free(hentry[6].body); \
1576 hentry[6].body = tmp; \
1578 if (hentry[7].body != NULL) { \
1579 tmp = conv_unmime_header(hentry[7].body, NULL, FALSE); \
1580 g_free(hentry[7].body); \
1581 hentry[7].body = tmp; \
1585 static void procmime_parse_multipart(MimeInfo *mimeinfo, gboolean short_scan)
1587 HeaderEntry hentry[] = {{"Content-Type:", NULL, TRUE},
1588 {"Content-Transfer-Encoding:",
1589 NULL, FALSE},
1590 {"Content-Description:",
1591 NULL, TRUE},
1592 {"Content-ID:",
1593 NULL, TRUE},
1594 {"Content-Disposition:",
1595 NULL, TRUE},
1596 {"Content-Location:",
1597 NULL, TRUE},
1598 {"Original-Message-ID:",
1599 NULL, TRUE},
1600 {"Disposition:",
1601 NULL, TRUE},
1602 {NULL, NULL, FALSE}};
1603 gchar *tmp;
1604 gchar *boundary;
1605 gint boundary_len = 0, lastoffset = -1, i;
1606 gchar buf[BUFFSIZE];
1607 FILE *fp;
1608 int result = 0;
1609 gboolean start_found = FALSE;
1610 gboolean end_found = FALSE;
1612 boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
1613 if (!boundary)
1614 return;
1615 boundary_len = strlen(boundary);
1617 procmime_decode_content(mimeinfo);
1619 fp = claws_fopen(mimeinfo->data.filename, "rb");
1620 if (fp == NULL) {
1621 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
1622 return;
1625 if (fseek(fp, mimeinfo->offset, SEEK_SET) < 0) {
1626 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
1627 claws_fclose(fp);
1628 return;
1631 while (claws_fgets(buf, sizeof(buf), fp) != NULL && result == 0) {
1632 if (ftell(fp) - 1 > (mimeinfo->offset + mimeinfo->length))
1633 break;
1635 if (IS_BOUNDARY(buf, boundary, boundary_len)) {
1636 start_found = TRUE;
1638 if (lastoffset != -1) {
1639 gint len = (ftell(fp) - strlen(buf)) - lastoffset - 1;
1640 if (len < 0)
1641 len = 0;
1642 result = procmime_parse_mimepart(mimeinfo,
1643 hentry[0].body, hentry[1].body,
1644 hentry[2].body, hentry[3].body,
1645 hentry[4].body, hentry[5].body,
1646 hentry[6].body, hentry[7].body,
1647 mimeinfo->data.filename, lastoffset,
1648 len, short_scan);
1649 if (result == 1 && short_scan)
1650 break;
1654 if (buf[2 + boundary_len] == '-' &&
1655 buf[2 + boundary_len + 1] == '-') {
1656 end_found = TRUE;
1657 break;
1659 for (i = 0; i < (sizeof hentry / sizeof hentry[0]) ; i++) {
1660 g_free(hentry[i].body);
1661 hentry[i].body = NULL;
1663 GET_HEADERS();
1664 lastoffset = ftell(fp);
1668 if (start_found && !end_found && lastoffset != -1) {
1669 gint len = (ftell(fp) - strlen(buf)) - lastoffset - 1;
1671 if (len >= 0) {
1672 result = procmime_parse_mimepart(mimeinfo,
1673 hentry[0].body, hentry[1].body,
1674 hentry[2].body, hentry[3].body,
1675 hentry[4].body, hentry[5].body,
1676 hentry[6].body, hentry[7].body,
1677 mimeinfo->data.filename, lastoffset,
1678 len, short_scan);
1680 mimeinfo->broken = TRUE;
1683 for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1684 g_free(hentry[i].body);
1685 hentry[i].body = NULL;
1687 claws_fclose(fp);
1690 static void parse_parameters(const gchar *parameters, GHashTable *table)
1692 gchar *params, *param, *next;
1693 GSList *convlist = NULL, *concatlist = NULL, *cur;
1695 params = g_strdup(parameters);
1696 param = params;
1697 next = params;
1698 for (; next != NULL; param = next) {
1699 gchar *attribute, *value, *tmp, *down_attr, *orig_down_attr;
1700 gint len;
1701 gboolean convert = FALSE;
1703 next = strchr_with_skip_quote(param, '"', ';');
1704 if (next != NULL) {
1705 next[0] = '\0';
1706 next++;
1709 g_strstrip(param);
1711 attribute = param;
1712 value = strchr(attribute, '=');
1713 if (value == NULL)
1714 continue;
1716 value[0] = '\0';
1717 value++;
1718 while (value[0] != '\0' && value[0] == ' ')
1719 value++;
1721 down_attr = g_utf8_strdown(attribute, -1);
1722 orig_down_attr = down_attr;
1724 len = down_attr ? strlen(down_attr):0;
1725 if (len > 0 && down_attr[len - 1] == '*') {
1726 gchar *srcpos, *dstpos, *endpos;
1728 convert = TRUE;
1729 down_attr[len - 1] = '\0';
1731 srcpos = value;
1732 dstpos = value;
1733 endpos = value + strlen(value);
1734 while (srcpos < endpos) {
1735 if (*srcpos != '%')
1736 *dstpos = *srcpos;
1737 else {
1738 guchar dstvalue;
1740 if (!get_hex_value(&dstvalue, srcpos[1], srcpos[2]))
1741 *dstpos = '?';
1742 else
1743 *dstpos = dstvalue;
1744 srcpos += 2;
1746 srcpos++;
1747 dstpos++;
1749 *dstpos = '\0';
1750 if (value[0] == '"')
1751 extract_quote(value, '"');
1752 } else {
1753 if (value[0] == '"')
1754 extract_quote(value, '"');
1755 else if ((tmp = strchr(value, ' ')) != NULL)
1756 *tmp = '\0';
1759 if (down_attr) {
1760 while (down_attr[0] == ' ')
1761 down_attr++;
1762 while (down_attr[strlen(down_attr)-1] == ' ')
1763 down_attr[strlen(down_attr)-1] = '\0';
1766 while (value[0] != '\0' && value[0] == ' ')
1767 value++;
1768 while (value[strlen(value)-1] == ' ')
1769 value[strlen(value)-1] = '\0';
1771 if (down_attr && strrchr(down_attr, '*') != NULL) {
1772 gchar *tmpattr;
1774 tmpattr = g_strdup(down_attr);
1775 tmp = strrchr(tmpattr, '*');
1776 tmp[0] = '\0';
1778 if ((tmp[1] == '0') && (tmp[2] == '\0') &&
1779 (g_slist_find_custom(concatlist, down_attr, (GCompareFunc)g_strcmp0) == NULL))
1780 concatlist = g_slist_prepend(concatlist, g_strdup(tmpattr));
1782 if (convert && (g_slist_find_custom(convlist, tmpattr, (GCompareFunc)g_strcmp0) == NULL))
1783 convlist = g_slist_prepend(convlist, g_strdup(tmpattr));
1785 g_free(tmpattr);
1786 } else if (convert) {
1787 if (g_slist_find_custom(convlist, down_attr, (GCompareFunc)g_strcmp0) == NULL)
1788 convlist = g_slist_prepend(convlist, g_strdup(down_attr));
1791 if (g_hash_table_lookup(table, down_attr) == NULL)
1792 g_hash_table_insert(table, g_strdup(down_attr), g_strdup(value));
1793 g_free(orig_down_attr);
1796 for (cur = concatlist; cur != NULL; cur = g_slist_next(cur)) {
1797 gchar *attribute, *attrwnum, *partvalue;
1798 gint n = 0;
1799 GString *value;
1801 attribute = (gchar *) cur->data;
1802 value = g_string_sized_new(64);
1804 attrwnum = g_strdup_printf("%s*%d", attribute, n);
1805 while ((partvalue = g_hash_table_lookup(table, attrwnum)) != NULL) {
1806 g_string_append(value, partvalue);
1808 g_hash_table_remove(table, attrwnum);
1809 g_free(attrwnum);
1810 n++;
1811 attrwnum = g_strdup_printf("%s*%d", attribute, n);
1813 g_free(attrwnum);
1815 g_hash_table_insert(table, g_strdup(attribute), g_strdup(value->str));
1816 g_string_free(value, TRUE);
1818 slist_free_strings_full(concatlist);
1820 for (cur = convlist; cur != NULL; cur = g_slist_next(cur)) {
1821 gchar *attribute, *key, *value;
1822 gchar *charset, *lang, *oldvalue, *newvalue;
1824 attribute = (gchar *) cur->data;
1825 if (!g_hash_table_lookup_extended(
1826 table, attribute, (gpointer *)(gchar *) &key, (gpointer *)(gchar *) &value))
1827 continue;
1829 charset = value;
1830 if (charset == NULL)
1831 continue;
1832 lang = strchr(charset, '\'');
1833 if (lang == NULL)
1834 continue;
1835 lang[0] = '\0';
1836 lang++;
1837 oldvalue = strchr(lang, '\'');
1838 if (oldvalue == NULL)
1839 continue;
1840 oldvalue[0] = '\0';
1841 oldvalue++;
1843 newvalue = conv_codeset_strdup(oldvalue, charset, CS_UTF_8);
1845 g_hash_table_remove(table, attribute);
1846 g_free(key);
1847 g_free(value);
1849 g_hash_table_insert(table, g_strdup(attribute), newvalue);
1851 slist_free_strings_full(convlist);
1853 g_free(params);
1856 static void procmime_parse_content_type(const gchar *content_type, MimeInfo *mimeinfo)
1858 cm_return_if_fail(content_type != NULL);
1859 cm_return_if_fail(mimeinfo != NULL);
1861 /* RFC 2045, page 13 says that the mime subtype is MANDATORY;
1862 * if it's not available we use the default Content-Type */
1863 if ((content_type[0] == '\0') || (strchr(content_type, '/') == NULL)) {
1864 mimeinfo->type = MIMETYPE_TEXT;
1865 mimeinfo->subtype = g_strdup("plain");
1866 if (g_hash_table_lookup(mimeinfo->typeparameters,
1867 "charset") == NULL) {
1868 g_hash_table_insert(mimeinfo->typeparameters,
1869 g_strdup("charset"),
1870 g_strdup(
1871 conv_get_locale_charset_str_no_utf8()));
1873 } else {
1874 gchar *type, *subtype, *params;
1876 type = g_strdup(content_type);
1877 subtype = strchr(type, '/') + 1;
1878 *(subtype - 1) = '\0';
1879 if ((params = strchr(subtype, ';')) != NULL) {
1880 params[0] = '\0';
1881 params++;
1884 mimeinfo->type = procmime_get_media_type(type);
1885 mimeinfo->subtype = g_strstrip(g_strdup(subtype));
1887 /* Get mimeinfo->typeparameters */
1888 if (params != NULL)
1889 parse_parameters(params, mimeinfo->typeparameters);
1891 g_free(type);
1895 static void procmime_parse_content_disposition(const gchar *content_disposition, MimeInfo *mimeinfo)
1897 gchar *tmp, *params;
1899 cm_return_if_fail(content_disposition != NULL);
1900 cm_return_if_fail(mimeinfo != NULL);
1902 tmp = g_strdup(content_disposition);
1903 if ((params = strchr(tmp, ';')) != NULL) {
1904 params[0] = '\0';
1905 params++;
1907 g_strstrip(tmp);
1909 if (!g_ascii_strcasecmp(tmp, "inline"))
1910 mimeinfo->disposition = DISPOSITIONTYPE_INLINE;
1911 else if (!g_ascii_strcasecmp(tmp, "attachment"))
1912 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1913 else
1914 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1916 if (params != NULL)
1917 parse_parameters(params, mimeinfo->dispositionparameters);
1919 g_free(tmp);
1923 static void procmime_parse_content_encoding(const gchar *content_encoding, MimeInfo *mimeinfo)
1925 struct EncodingTable *enc_table;
1927 for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1928 if (g_ascii_strcasecmp(enc_table->str, content_encoding) == 0) {
1929 mimeinfo->encoding_type = enc_table->enc_type;
1930 return;
1933 mimeinfo->encoding_type = ENC_UNKNOWN;
1934 return;
1937 static GSList *registered_parsers = NULL;
1939 static MimeParser *procmime_get_mimeparser_for_type(MimeMediaType type, const gchar *sub_type)
1941 GSList *cur;
1942 for (cur = registered_parsers; cur; cur = cur->next) {
1943 MimeParser *parser = (MimeParser *)cur->data;
1944 if (parser->type == type && !g_strcmp0(parser->sub_type, sub_type))
1945 return parser;
1947 return NULL;
1950 void procmime_mimeparser_register(MimeParser *parser)
1952 if (!procmime_get_mimeparser_for_type(parser->type, parser->sub_type))
1953 registered_parsers = g_slist_append(registered_parsers, parser);
1957 void procmime_mimeparser_unregister(MimeParser *parser)
1959 registered_parsers = g_slist_remove(registered_parsers, parser);
1962 static gboolean procmime_mimeparser_parse(MimeParser *parser, MimeInfo *mimeinfo)
1964 cm_return_val_if_fail(parser->parse != NULL, FALSE);
1965 return parser->parse(parser, mimeinfo);
1968 static int procmime_parse_mimepart(MimeInfo *parent,
1969 gchar *content_type,
1970 gchar *content_encoding,
1971 gchar *content_description,
1972 gchar *content_id,
1973 gchar *content_disposition,
1974 gchar *content_location,
1975 const gchar *original_msgid,
1976 const gchar *disposition_notification_hdr,
1977 const gchar *filename,
1978 guint offset,
1979 guint length,
1980 gboolean short_scan)
1982 MimeInfo *mimeinfo;
1983 MimeParser *parser = NULL;
1984 gboolean parsed = FALSE;
1985 int result = 0;
1987 /* Create MimeInfo */
1988 mimeinfo = procmime_mimeinfo_new();
1989 mimeinfo->content = MIMECONTENT_FILE;
1991 if (parent != NULL) {
1992 if (g_node_depth(parent->node) > 32) {
1993 /* 32 is an arbitrary value
1994 * this avoids DOSsing ourselves
1995 * with enormous messages
1997 procmime_mimeinfo_free_all(&mimeinfo);
1998 return -1;
2000 g_node_append(parent->node, mimeinfo->node);
2002 mimeinfo->data.filename = g_strdup(filename);
2003 mimeinfo->offset = offset;
2004 mimeinfo->length = length;
2006 if (content_type != NULL) {
2007 g_strchomp(content_type);
2008 procmime_parse_content_type(content_type, mimeinfo);
2009 } else {
2010 mimeinfo->type = MIMETYPE_TEXT;
2011 mimeinfo->subtype = g_strdup("plain");
2012 if (g_hash_table_lookup(mimeinfo->typeparameters,
2013 "charset") == NULL) {
2014 g_hash_table_insert(mimeinfo->typeparameters,
2015 g_strdup("charset"),
2016 g_strdup(
2017 conv_get_locale_charset_str_no_utf8()));
2021 if (content_encoding != NULL) {
2022 g_strchomp(content_encoding);
2023 procmime_parse_content_encoding(content_encoding, mimeinfo);
2024 } else {
2025 mimeinfo->encoding_type = ENC_UNKNOWN;
2028 if (content_description != NULL)
2029 mimeinfo->description = g_strdup(content_description);
2030 else
2031 mimeinfo->description = NULL;
2033 if (content_id != NULL)
2034 mimeinfo->id = g_strdup(content_id);
2035 else
2036 mimeinfo->id = NULL;
2038 if (content_location != NULL)
2039 mimeinfo->location = g_strdup(content_location);
2040 else
2041 mimeinfo->location = NULL;
2043 if (content_disposition != NULL) {
2044 g_strchomp(content_disposition);
2045 procmime_parse_content_disposition(content_disposition, mimeinfo);
2046 } else
2047 mimeinfo->disposition = DISPOSITIONTYPE_UNKNOWN;
2049 /* Call parser for mime type */
2050 if ((parser = procmime_get_mimeparser_for_type(mimeinfo->type, mimeinfo->subtype)) != NULL) {
2051 parsed = procmime_mimeparser_parse(parser, mimeinfo);
2053 if (!parsed) {
2054 switch (mimeinfo->type) {
2055 case MIMETYPE_TEXT:
2056 if (g_ascii_strcasecmp(mimeinfo->subtype, "plain") == 0 && short_scan) {
2057 return 1;
2059 break;
2061 case MIMETYPE_MESSAGE:
2062 if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
2063 procmime_parse_message_rfc822(mimeinfo, short_scan);
2065 if (g_ascii_strcasecmp(mimeinfo->subtype, "disposition-notification") == 0) {
2066 procmime_parse_disposition_notification(mimeinfo,
2067 original_msgid, disposition_notification_hdr, short_scan);
2069 break;
2071 case MIMETYPE_MULTIPART:
2072 procmime_parse_multipart(mimeinfo, short_scan);
2073 break;
2075 case MIMETYPE_APPLICATION:
2076 if (g_ascii_strcasecmp(mimeinfo->subtype, "octet-stream") == 0
2077 && original_msgid && *original_msgid
2078 && disposition_notification_hdr && *disposition_notification_hdr) {
2079 procmime_parse_disposition_notification(mimeinfo,
2080 original_msgid, disposition_notification_hdr, short_scan);
2082 break;
2083 default:
2084 break;
2088 return result;
2091 static gchar *typenames[] = {
2092 "text",
2093 "image",
2094 "audio",
2095 "video",
2096 "application",
2097 "message",
2098 "multipart",
2099 "unknown",
2102 static gboolean output_func(GNode *node, gpointer data)
2104 guint i, depth;
2105 MimeInfo *mimeinfo = (MimeInfo *) node->data;
2107 depth = g_node_depth(node);
2108 for (i = 0; i < depth; i++)
2109 g_print(" ");
2110 g_print("%s/%s (offset:%d length:%d encoding: %d)\n", typenames[mimeinfo->type], mimeinfo->subtype, mimeinfo->offset, mimeinfo->length, mimeinfo->encoding_type);
2112 return FALSE;
2115 static void output_mime_structure(MimeInfo *mimeinfo, int indent)
2117 g_node_traverse(mimeinfo->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1, output_func, NULL);
2120 static MimeInfo *procmime_scan_file_with_offset(const gchar *filename, int offset, gboolean short_scan)
2122 MimeInfo *mimeinfo;
2123 GStatBuf buf;
2125 if (g_stat(filename, &buf) < 0) {
2126 FILE_OP_ERROR(filename, "stat");
2127 return NULL;
2130 mimeinfo = procmime_mimeinfo_new();
2131 mimeinfo->content = MIMECONTENT_FILE;
2132 mimeinfo->encoding_type = ENC_UNKNOWN;
2133 mimeinfo->type = MIMETYPE_MESSAGE;
2134 mimeinfo->subtype = g_strdup("rfc822");
2135 mimeinfo->data.filename = g_strdup(filename);
2136 mimeinfo->offset = offset;
2137 mimeinfo->length = buf.st_size - offset;
2139 procmime_parse_message_rfc822(mimeinfo, short_scan);
2140 if (debug_get_mode())
2141 output_mime_structure(mimeinfo, 0);
2143 return mimeinfo;
2146 static MimeInfo *procmime_scan_file_full(const gchar *filename, gboolean short_scan)
2148 MimeInfo *mimeinfo;
2150 cm_return_val_if_fail(filename != NULL, NULL);
2152 mimeinfo = procmime_scan_file_with_offset(filename, 0, short_scan);
2154 return mimeinfo;
2157 MimeInfo *procmime_scan_file(const gchar *filename)
2159 return procmime_scan_file_full(filename, FALSE);
2162 static MimeInfo *procmime_scan_file_short(const gchar *filename)
2164 return procmime_scan_file_full(filename, TRUE);
2167 static MimeInfo *procmime_scan_queue_file_full(const gchar *filename, gboolean short_scan)
2169 FILE *fp;
2170 MimeInfo *mimeinfo;
2171 gchar buf[BUFFSIZE];
2172 gint offset = 0;
2174 cm_return_val_if_fail(filename != NULL, NULL);
2176 /* Open file */
2177 if ((fp = claws_fopen(filename, "rb")) == NULL)
2178 return NULL;
2179 /* Skip queue header */
2180 while (claws_fgets(buf, sizeof(buf), fp) != NULL) {
2181 /* new way */
2182 if ((!strncmp(buf, "X-Claws-End-Special-Headers: 1",
2183 strlen("X-Claws-End-Special-Headers:"))) ||
2184 (!strncmp(buf, "X-Sylpheed-End-Special-Headers: 1",
2185 strlen("X-Sylpheed-End-Special-Headers:"))))
2186 break;
2187 /* old way */
2188 if (buf[0] == '\r' || buf[0] == '\n') break;
2189 /* from other mailers */
2190 if (!strncmp(buf, "Date: ", 6)
2191 || !strncmp(buf, "To: ", 4)
2192 || !strncmp(buf, "From: ", 6)
2193 || !strncmp(buf, "Subject: ", 9)) {
2194 rewind(fp);
2195 break;
2198 offset = ftell(fp);
2199 claws_fclose(fp);
2201 mimeinfo = procmime_scan_file_with_offset(filename, offset, short_scan);
2203 return mimeinfo;
2206 MimeInfo *procmime_scan_queue_file(const gchar *filename)
2208 return procmime_scan_queue_file_full(filename, FALSE);
2211 static MimeInfo *procmime_scan_queue_file_short(const gchar *filename)
2213 return procmime_scan_queue_file_full(filename, TRUE);
2216 typedef enum {
2217 ENC_AS_TOKEN,
2218 ENC_AS_QUOTED_STRING,
2219 ENC_AS_EXTENDED,
2220 ENC_AS_ENCWORD
2221 } EncodeAs;
2223 typedef struct _ParametersData {
2224 FILE *fp;
2225 guint len;
2226 gint error;
2227 } ParametersData;
2229 static void write_parameters(gpointer key, gpointer value, gpointer user_data)
2231 gchar *param = key;
2232 gchar *val = value, *valpos, *tmp;
2233 ParametersData *pdata = (ParametersData *)user_data;
2234 GString *buf = g_string_new("");
2235 gint len;
2237 EncodeAs encas = ENC_AS_TOKEN;
2239 for (valpos = val; *valpos != 0; valpos++) {
2240 if (!IS_ASCII(*valpos)) {
2241 encas = ENC_AS_ENCWORD;
2242 break;
2245 /* CTLs */
2246 if (((*valpos >= 0) && (*valpos < 037)) || (*valpos == 0177)) {
2247 encas = ENC_AS_QUOTED_STRING;
2248 continue;
2251 /* tspecials + SPACE */
2252 switch (*valpos) {
2253 case ' ':
2254 case '(':
2255 case ')':
2256 case '<':
2257 case '>':
2258 case '@':
2259 case ',':
2260 case ';':
2261 case ':':
2262 case '\\':
2263 case '"':
2264 case '/':
2265 case '[':
2266 case ']':
2267 case '?':
2268 case '=':
2269 encas = ENC_AS_QUOTED_STRING;
2270 continue;
2274 switch (encas) {
2275 case ENC_AS_TOKEN:
2276 g_string_append_printf(buf, "%s=%s", param, val);
2277 break;
2279 case ENC_AS_QUOTED_STRING:
2280 g_string_append_printf(buf, "%s=\"%s\"", param, val);
2281 break;
2283 #if 0 /* we don't use that for now */
2284 case ENC_AS_EXTENDED:
2285 if (!g_utf8_validate(val, -1, NULL))
2286 g_string_append_printf(buf, "%s*=%s''", param,
2287 conv_get_locale_charset_str());
2288 else
2289 g_string_append_printf(buf, "%s*=%s''", param,
2290 CS_INTERNAL);
2291 for (valpos = val; *valpos != '\0'; valpos++) {
2292 if (IS_ASCII(*valpos) && isalnum(*valpos)) {
2293 g_string_append_printf(buf, "%c", *valpos);
2294 } else {
2295 gchar hexstr[3] = "XX";
2296 get_hex_str(hexstr, *valpos);
2297 g_string_append_printf(buf, "%%%s", hexstr);
2300 break;
2301 #else
2302 case ENC_AS_EXTENDED:
2303 debug_print("Unhandled ENC_AS_EXTENDED.\n");
2304 break;
2305 #endif
2306 case ENC_AS_ENCWORD:
2307 len = MAX(strlen(val)*6, 512);
2308 tmp = g_malloc(len+1);
2309 codeconv_set_strict(TRUE);
2310 conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2311 prefs_common.outgoing_charset);
2312 codeconv_set_strict(FALSE);
2313 if (!tmp || !*tmp) {
2314 codeconv_set_strict(TRUE);
2315 conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2316 conv_get_outgoing_charset_str());
2317 codeconv_set_strict(FALSE);
2319 if (!tmp || !*tmp) {
2320 codeconv_set_strict(TRUE);
2321 conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2322 CS_UTF_8);
2323 codeconv_set_strict(FALSE);
2325 if (!tmp || !*tmp) {
2326 conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2327 CS_UTF_8);
2329 g_string_append_printf(buf, "%s=\"%s\"", param, tmp);
2330 g_free(tmp);
2331 break;
2335 if (buf->str && strlen(buf->str)) {
2336 tmp = strstr(buf->str, "\n");
2337 if (tmp)
2338 len = (tmp - buf->str);
2339 else
2340 len = strlen(buf->str);
2341 if (pdata->len + len > 76) {
2342 if (fprintf(pdata->fp, ";\n %s", buf->str) < 0)
2343 pdata->error = TRUE;
2344 pdata->len = strlen(buf->str) + 1;
2345 } else {
2346 if (fprintf(pdata->fp, "; %s", buf->str) < 0)
2347 pdata->error = TRUE;
2348 pdata->len += strlen(buf->str) + 2;
2351 g_string_free(buf, TRUE);
2354 #define TRY(func) { \
2355 if (!(func)) { \
2356 return -1; \
2360 int procmime_write_mime_header(MimeInfo *mimeinfo, FILE *fp)
2362 struct TypeTable *type_table;
2363 ParametersData *pdata = g_new0(ParametersData, 1);
2364 debug_print("procmime_write_mime_header\n");
2366 pdata->fp = fp;
2367 pdata->error = FALSE;
2368 for (type_table = mime_type_table; type_table->str != NULL; type_table++)
2369 if (mimeinfo->type == type_table->type) {
2370 gchar *buf = g_strdup_printf(
2371 "Content-Type: %s/%s", type_table->str, mimeinfo->subtype);
2372 if (fprintf(fp, "%s", buf) < 0) {
2373 g_free(buf);
2374 g_free(pdata);
2375 return -1;
2377 pdata->len = strlen(buf);
2378 g_free(buf);
2379 break;
2381 g_hash_table_foreach(mimeinfo->typeparameters, write_parameters, pdata);
2382 if (pdata->error == TRUE) {
2383 g_free(pdata);
2384 return -1;
2386 g_free(pdata);
2388 TRY(fprintf(fp, "\n") >= 0);
2390 if (mimeinfo->encoding_type != ENC_UNKNOWN)
2391 TRY(fprintf(fp, "Content-Transfer-Encoding: %s\n", procmime_get_encoding_str(mimeinfo->encoding_type)) >= 0);
2393 if (mimeinfo->description != NULL)
2394 TRY(fprintf(fp, "Content-Description: %s\n", mimeinfo->description) >= 0);
2396 if (mimeinfo->id != NULL)
2397 TRY(fprintf(fp, "Content-ID: %s\n", mimeinfo->id) >= 0);
2399 if (mimeinfo->location != NULL)
2400 TRY(fprintf(fp, "Content-Location: %s\n", mimeinfo->location) >= 0);
2402 if (mimeinfo->disposition != DISPOSITIONTYPE_UNKNOWN) {
2403 ParametersData *pdata = g_new0(ParametersData, 1);
2404 gchar *buf = NULL;
2405 if (mimeinfo->disposition == DISPOSITIONTYPE_INLINE)
2406 buf = g_strdup("Content-Disposition: inline");
2407 else if (mimeinfo->disposition == DISPOSITIONTYPE_ATTACHMENT)
2408 buf = g_strdup("Content-Disposition: attachment");
2409 else
2410 buf = g_strdup("Content-Disposition: unknown");
2412 if (fprintf(fp, "%s", buf) < 0) {
2413 g_free(buf);
2414 g_free(pdata);
2415 return -1;
2417 pdata->len = strlen(buf);
2418 g_free(buf);
2420 pdata->fp = fp;
2421 pdata->error = FALSE;
2422 g_hash_table_foreach(mimeinfo->dispositionparameters, write_parameters, pdata);
2423 if (pdata->error == TRUE) {
2424 g_free(pdata);
2425 return -1;
2427 g_free(pdata);
2428 TRY(fprintf(fp, "\n") >= 0);
2431 TRY(fprintf(fp, "\n") >= 0);
2433 return 0;
2436 static gint procmime_write_message_rfc822(MimeInfo *mimeinfo, FILE *fp)
2438 FILE *infp;
2439 GNode *childnode;
2440 MimeInfo *child;
2441 gchar buf[BUFFSIZE];
2442 gboolean skip = FALSE;;
2443 size_t len;
2445 debug_print("procmime_write_message_rfc822\n");
2447 /* write header */
2448 switch (mimeinfo->content) {
2449 case MIMECONTENT_FILE:
2450 if ((infp = claws_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2451 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
2452 return -1;
2454 if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
2455 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
2456 claws_fclose(infp);
2457 return -1;
2459 while (claws_fgets(buf, sizeof(buf), infp) == buf) {
2460 strcrchomp(buf);
2461 if (buf[0] == '\n' && buf[1] == '\0')
2462 break;
2463 if (skip && (buf[0] == ' ' || buf[0] == '\t'))
2464 continue;
2465 if (g_ascii_strncasecmp(buf, "MIME-Version:", 13) == 0 ||
2466 g_ascii_strncasecmp(buf, "Content-Type:", 13) == 0 ||
2467 g_ascii_strncasecmp(buf, "Content-Transfer-Encoding:", 26) == 0 ||
2468 g_ascii_strncasecmp(buf, "Content-Description:", 20) == 0 ||
2469 g_ascii_strncasecmp(buf, "Content-ID:", 11) == 0 ||
2470 g_ascii_strncasecmp(buf, "Content-Location:", 17) == 0 ||
2471 g_ascii_strncasecmp(buf, "Content-Disposition:", 20) == 0) {
2472 skip = TRUE;
2473 continue;
2475 len = strlen(buf);
2476 if (claws_fwrite(buf, sizeof(gchar), len, fp) < len) {
2477 g_warning("failed to dump %"G_GSIZE_FORMAT" bytes from file", len);
2478 claws_fclose(infp);
2479 return -1;
2481 skip = FALSE;
2483 claws_fclose(infp);
2484 break;
2486 case MIMECONTENT_MEM:
2487 len = strlen(mimeinfo->data.mem);
2488 if (claws_fwrite(mimeinfo->data.mem, sizeof(gchar), len, fp) < len) {
2489 g_warning("failed to dump %"G_GSIZE_FORMAT" bytes from mem", len);
2490 return -1;
2492 break;
2494 default:
2495 break;
2498 childnode = mimeinfo->node->children;
2499 if (childnode == NULL)
2500 return -1;
2502 child = (MimeInfo *) childnode->data;
2503 if (fprintf(fp, "MIME-Version: 1.0\n") < 0) {
2504 g_warning("failed to write mime version");
2505 return -1;
2507 if (procmime_write_mime_header(child, fp) < 0)
2508 return -1;
2509 return procmime_write_mimeinfo(child, fp);
2512 static gint procmime_write_multipart(MimeInfo *mimeinfo, FILE *fp)
2514 FILE *infp;
2515 GNode *childnode;
2516 gchar *boundary, *str, *str2;
2517 gchar buf[BUFFSIZE];
2518 gboolean firstboundary;
2519 size_t len;
2521 debug_print("procmime_write_multipart\n");
2523 boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
2525 switch (mimeinfo->content) {
2526 case MIMECONTENT_FILE:
2527 if ((infp = claws_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2528 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
2529 return -1;
2531 if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
2532 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
2533 claws_fclose(infp);
2534 return -1;
2536 while (claws_fgets(buf, sizeof(buf), infp) == buf) {
2537 if (IS_BOUNDARY(buf, boundary, strlen(boundary)))
2538 break;
2539 len = strlen(buf);
2540 if (claws_fwrite(buf, sizeof(gchar), len, fp) < len) {
2541 g_warning("failed to write %"G_GSIZE_FORMAT, len);
2542 claws_fclose(infp);
2543 return -1;
2546 claws_fclose(infp);
2547 break;
2549 case MIMECONTENT_MEM:
2550 str = g_strdup(mimeinfo->data.mem);
2551 if (((str2 = strstr(str, boundary)) != NULL) && ((str2 - str) >= 2) &&
2552 (*(str2 - 1) == '-') && (*(str2 - 2) == '-'))
2553 *(str2 - 2) = '\0';
2554 len = strlen(str);
2555 if (claws_fwrite(str, sizeof(gchar), len, fp) < len) {
2556 g_warning("failed to write %"G_GSIZE_FORMAT" from mem", len);
2557 g_free(str);
2558 return -1;
2560 g_free(str);
2561 break;
2563 default:
2564 break;
2567 childnode = mimeinfo->node->children;
2568 firstboundary = TRUE;
2569 while (childnode != NULL) {
2570 MimeInfo *child = childnode->data;
2572 if (firstboundary)
2573 firstboundary = FALSE;
2574 else
2575 TRY(fprintf(fp, "\n") >= 0);
2577 TRY(fprintf(fp, "--%s\n", boundary) >= 0);
2579 if (procmime_write_mime_header(child, fp) < 0)
2580 return -1;
2581 if (procmime_write_mimeinfo(child, fp) < 0)
2582 return -1;
2584 childnode = g_node_next_sibling(childnode);
2586 TRY(fprintf(fp, "\n--%s--\n", boundary) >= 0);
2588 return 0;
2591 gint procmime_write_mimeinfo(MimeInfo *mimeinfo, FILE *fp)
2593 FILE *infp;
2594 size_t len;
2595 debug_print("procmime_write_mimeinfo\n");
2597 if (G_NODE_IS_LEAF(mimeinfo->node)) {
2598 switch (mimeinfo->content) {
2599 case MIMECONTENT_FILE:
2600 if ((infp = claws_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2601 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
2602 return -1;
2604 copy_file_part_to_fp(infp, mimeinfo->offset, mimeinfo->length, fp);
2605 claws_fclose(infp);
2606 return 0;
2608 case MIMECONTENT_MEM:
2609 len = strlen(mimeinfo->data.mem);
2610 if (claws_fwrite(mimeinfo->data.mem, sizeof(gchar), len, fp) < len)
2611 return -1;
2612 return 0;
2614 default:
2615 return 0;
2617 } else {
2618 /* Call writer for mime type */
2619 switch (mimeinfo->type) {
2620 case MIMETYPE_MESSAGE:
2621 if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
2622 return procmime_write_message_rfc822(mimeinfo, fp);
2624 break;
2626 case MIMETYPE_MULTIPART:
2627 return procmime_write_multipart(mimeinfo, fp);
2629 default:
2630 break;
2633 return -1;
2636 return 0;
2639 gchar *procmime_get_part_file_name(MimeInfo *mimeinfo)
2641 gchar *base;
2643 if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
2644 base = g_strdup("mimetmp.html");
2645 else {
2646 const gchar *basetmp;
2647 gchar *basename;
2649 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
2650 if (basetmp == NULL)
2651 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
2652 if (basetmp == NULL)
2653 basetmp = "mimetmp";
2654 basename = g_path_get_basename(basetmp);
2655 if (*basename == '\0') {
2656 g_free(basename);
2657 basename = g_strdup("mimetmp");
2659 base = conv_filename_from_utf8(basename);
2660 g_free(basename);
2661 subst_for_shellsafe_filename(base);
2664 return base;
2667 void *procmime_get_part_as_string(MimeInfo *mimeinfo,
2668 gboolean null_terminate)
2670 FILE *infp;
2671 gchar *data;
2672 gint length, readlength;
2674 cm_return_val_if_fail(mimeinfo != NULL, NULL);
2676 if (mimeinfo->encoding_type != ENC_BINARY &&
2677 !procmime_decode_content(mimeinfo))
2678 return NULL;
2680 if (mimeinfo->content == MIMECONTENT_MEM)
2681 return g_strdup(mimeinfo->data.mem);
2683 if ((infp = claws_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2684 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
2685 return NULL;
2688 if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
2689 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
2690 claws_fclose(infp);
2691 return NULL;
2694 length = mimeinfo->length;
2696 data = g_malloc(null_terminate ? length + 1 : length);
2697 if (data == NULL) {
2698 g_warning("Could not allocate %d bytes for procmime_get_part_as_string.\n",
2699 (null_terminate ? length + 1 : length));
2700 claws_fclose(infp);
2701 return NULL;
2704 readlength = claws_fread(data, length, 1, infp);
2705 if (readlength <= 0) {
2706 FILE_OP_ERROR(mimeinfo->data.filename, "fread");
2707 g_free(data);
2708 claws_fclose(infp);
2709 return NULL;
2712 claws_fclose(infp);
2714 if (null_terminate)
2715 data[length] = '\0';
2717 return data;
2720 /* Returns an open GInputStream. The caller should just
2721 * read mimeinfo->length bytes from it and then release it. */
2722 GInputStream *procmime_get_part_as_inputstream(MimeInfo *mimeinfo)
2724 cm_return_val_if_fail(mimeinfo != NULL, NULL);
2726 if (mimeinfo->encoding_type != ENC_BINARY &&
2727 !procmime_decode_content(mimeinfo)) {
2728 g_warning("could not decode part");
2729 return NULL;
2731 if (mimeinfo->content == MIMECONTENT_MEM) {
2732 /* NULL for destroy func, since we're not copying
2733 * the data for the stream. */
2734 return g_memory_input_stream_new_from_data(
2735 mimeinfo->data.mem,
2736 mimeinfo->length, NULL);
2737 } else {
2738 return g_memory_input_stream_new_from_data(
2739 procmime_get_part_as_string(mimeinfo, FALSE),
2740 mimeinfo->length, g_free);
2744 GdkPixbuf *procmime_get_part_as_pixbuf(MimeInfo *mimeinfo, GError **error)
2746 GdkPixbuf *pixbuf;
2747 GInputStream *stream;
2749 if (error)
2750 *error = NULL;
2752 stream = procmime_get_part_as_inputstream(mimeinfo);
2753 if (stream == NULL) {
2754 if (error)
2755 *error = g_error_new_literal(G_FILE_ERROR, -1, _("Could not decode part"));
2756 return NULL;
2759 pixbuf = gdk_pixbuf_new_from_stream(stream, NULL, error);
2760 g_object_unref(stream);
2762 if (error && *error != NULL)
2763 return NULL;
2765 return pixbuf;