fix year reversal in last commit
[claws.git] / src / procmime.c
blob627b91f83e2b731e3917d575f59352a34bdaf36d
1 /*
2 * Claws Mail -- a GTK based, lightweight, and fast e-mail client
3 * Copyright (C) 1999-2024 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 claws_fclose(tmpfp);
447 } else if (encoding == ENC_X_UUENCODE) {
448 gchar outbuf[BUFFSIZE];
449 gint len;
450 gboolean flag = FALSE;
452 while ((ftell(infp) < readend) && (claws_fgets(buf, sizeof(buf), infp) != NULL)) {
453 if (!flag && strncmp(buf,"begin ", 6)) continue;
455 if (flag) {
456 len = fromuutobits(outbuf, buf);
457 if (len <= 0) {
458 if (len < 0)
459 g_warning("bad UUENCODE content (%d)", len);
460 break;
462 if (claws_fwrite(outbuf, sizeof(gchar), len, outfp) < len)
463 err = TRUE;
464 } else
465 flag = TRUE;
467 } else {
468 while ((ftell(infp) < readend) && (claws_fgets(buf, sizeof(buf), infp) != NULL)) {
469 if (!flowed) {
470 if (claws_fputs(buf, outfp) == EOF)
471 err = TRUE;
472 } else {
473 FLUSH_LASTLINE();
476 if (flowed)
477 FLUSH_LASTLINE();
478 if (err == TRUE)
479 g_warning("write error");
482 claws_fclose(outfp);
483 claws_fclose(infp);
485 account_sigsep_matchlist_delete();
487 if (err == TRUE) {
488 g_free(tmpfilename);
489 return FALSE;
492 if (g_stat(tmpfilename, &statbuf) < 0) {
493 FILE_OP_ERROR(tmpfilename, "stat");
494 g_free(tmpfilename);
495 return FALSE;
498 if (mimeinfo->tmp)
499 claws_unlink(mimeinfo->data.filename);
500 g_free(mimeinfo->data.filename);
501 mimeinfo->data.filename = tmpfilename;
502 mimeinfo->tmp = TRUE;
503 mimeinfo->offset = 0;
504 mimeinfo->length = statbuf.st_size;
505 mimeinfo->encoding_type = ENC_BINARY;
507 return TRUE;
510 gboolean procmime_encode_content(MimeInfo *mimeinfo, EncodingType encoding)
512 FILE *infp = NULL, *outfp;
513 gint len;
514 gchar *tmpfilename;
515 GStatBuf statbuf;
516 gboolean err = FALSE;
518 if (mimeinfo->content == MIMECONTENT_EMPTY)
519 return TRUE;
521 if (mimeinfo->encoding_type != ENC_UNKNOWN &&
522 mimeinfo->encoding_type != ENC_BINARY &&
523 mimeinfo->encoding_type != ENC_7BIT &&
524 mimeinfo->encoding_type != ENC_8BIT)
525 if(!procmime_decode_content(mimeinfo))
526 return FALSE;
528 outfp = get_tmpfile_in_dir(get_mime_tmp_dir(), &tmpfilename);
529 if (!outfp) {
530 perror("tmpfile");
531 g_free(tmpfilename);
532 return FALSE;
535 if (mimeinfo->content == MIMECONTENT_FILE && mimeinfo->data.filename) {
536 if ((infp = claws_fopen(mimeinfo->data.filename, "rb")) == NULL) {
537 g_warning("can't open file %s", mimeinfo->data.filename);
538 g_free(tmpfilename);
539 claws_fclose(outfp);
540 return FALSE;
542 } else if (mimeinfo->content == MIMECONTENT_MEM) {
543 infp = str_open_as_stream(mimeinfo->data.mem);
544 if (infp == NULL) {
545 g_free(tmpfilename);
546 claws_fclose(outfp);
547 return FALSE;
549 } else {
550 g_free(tmpfilename);
551 claws_fclose(outfp);
552 g_warning("unknown mimeinfo");
553 return FALSE;
556 if (encoding == ENC_BASE64) {
557 gchar inbuf[B64_LINE_SIZE], *out;
558 FILE *tmp_fp = infp;
559 gchar *tmp_file = NULL;
561 if (mimeinfo->type == MIMETYPE_TEXT ||
562 mimeinfo->type == MIMETYPE_MESSAGE) {
563 if (mimeinfo->content == MIMECONTENT_FILE) {
564 tmp_file = get_tmp_file();
565 if (canonicalize_file(mimeinfo->data.filename, tmp_file) < 0) {
566 g_free(tmp_file);
567 g_free(tmpfilename);
568 claws_fclose(infp);
569 claws_fclose(outfp);
570 return FALSE;
572 if ((tmp_fp = claws_fopen(tmp_file, "rb")) == NULL) {
573 FILE_OP_ERROR(tmp_file, "claws_fopen");
574 claws_unlink(tmp_file);
575 g_free(tmp_file);
576 g_free(tmpfilename);
577 claws_fclose(infp);
578 claws_fclose(outfp);
579 return FALSE;
581 } else {
582 gchar *out = canonicalize_str(mimeinfo->data.mem);
583 claws_fclose(infp);
584 infp = str_open_as_stream(out);
585 tmp_fp = infp;
586 g_free(out);
587 if (infp == NULL) {
588 g_free(tmpfilename);
589 claws_fclose(outfp);
590 return FALSE;
595 while ((len = claws_fread(inbuf, sizeof(gchar),
596 B64_LINE_SIZE, tmp_fp))
597 == B64_LINE_SIZE) {
598 out = g_base64_encode(inbuf, B64_LINE_SIZE);
599 if (claws_fputs(out, outfp) == EOF)
600 err = TRUE;
601 g_free(out);
602 if (claws_fputc('\n', outfp) == EOF)
603 err = TRUE;
605 if (len > 0 && claws_feof(tmp_fp)) {
606 out = g_base64_encode(inbuf, len);
607 if (claws_fputs(out, outfp) == EOF)
608 err = TRUE;
609 g_free(out);
610 if (claws_fputc('\n', outfp) == EOF)
611 err = TRUE;
614 if (tmp_file) {
615 claws_fclose(tmp_fp);
616 claws_unlink(tmp_file);
617 g_free(tmp_file);
619 } else if (encoding == ENC_QUOTED_PRINTABLE) {
620 gchar inbuf[BUFFSIZE], outbuf[BUFFSIZE * 4];
622 while (claws_fgets(inbuf, sizeof(inbuf), infp) != NULL) {
623 qp_encode_line(outbuf, inbuf);
625 if (!strncmp("From ", outbuf, sizeof("From ")-1)) {
626 gchar *tmpbuf = outbuf;
628 tmpbuf += sizeof("From ")-1;
630 if (claws_fputs("=46rom ", outfp) == EOF)
631 err = TRUE;
632 if (claws_fputs(tmpbuf, outfp) == EOF)
633 err = TRUE;
634 } else {
635 if (claws_fputs(outbuf, outfp) == EOF)
636 err = TRUE;
639 } else {
640 gchar buf[BUFFSIZE];
642 while (claws_fgets(buf, sizeof(buf), infp) != NULL) {
643 strcrchomp(buf);
644 if (claws_fputs(buf, outfp) == EOF)
645 err = TRUE;
649 claws_fclose(outfp);
650 claws_fclose(infp);
652 if (err == TRUE) {
653 g_free(tmpfilename);
654 return FALSE;
657 if (mimeinfo->content == MIMECONTENT_FILE) {
658 if (mimeinfo->tmp && (mimeinfo->data.filename != NULL))
659 claws_unlink(mimeinfo->data.filename);
660 g_free(mimeinfo->data.filename);
661 } else if (mimeinfo->content == MIMECONTENT_MEM) {
662 if (mimeinfo->tmp && (mimeinfo->data.mem != NULL))
663 g_free(mimeinfo->data.mem);
666 if (g_stat(tmpfilename, &statbuf) < 0) {
667 FILE_OP_ERROR(tmpfilename, "stat");
668 g_free(tmpfilename);
669 return FALSE;
671 mimeinfo->content = MIMECONTENT_FILE;
672 mimeinfo->data.filename = tmpfilename;
673 mimeinfo->tmp = TRUE;
674 mimeinfo->offset = 0;
675 mimeinfo->length = statbuf.st_size;
676 mimeinfo->encoding_type = encoding;
678 return TRUE;
681 static gint procmime_get_part_to_stream(FILE *outfp, MimeInfo *mimeinfo)
683 FILE *infp;
684 gchar buf[BUFFSIZE];
685 gint restlength, readlength;
686 gint saved_errno = 0;
688 cm_return_val_if_fail(outfp != NULL, -1);
689 cm_return_val_if_fail(mimeinfo != NULL, -1);
691 if (mimeinfo->encoding_type != ENC_BINARY && !procmime_decode_content(mimeinfo))
692 return -EINVAL;
694 if ((infp = claws_fopen(mimeinfo->data.filename, "rb")) == NULL) {
695 saved_errno = errno;
696 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
697 return -(saved_errno);
699 if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
700 saved_errno = errno;
701 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
702 claws_fclose(infp);
703 return -(saved_errno);
706 restlength = mimeinfo->length;
708 while ((restlength > 0) && ((readlength = claws_fread(buf, 1, restlength > BUFFSIZE ? BUFFSIZE : restlength, infp)) > 0)) {
709 if (claws_fwrite(buf, 1, readlength, outfp) != readlength) {
710 saved_errno = errno;
711 claws_fclose(infp);
712 return -(saved_errno);
714 restlength -= readlength;
717 claws_fclose(infp);
718 rewind(outfp);
720 return 0;
723 gint procmime_get_part(const gchar *outfile, MimeInfo *mimeinfo)
725 FILE *outfp;
726 gint result;
727 gint saved_errno = 0;
729 cm_return_val_if_fail(outfile != NULL, -1);
731 if ((outfp = claws_fopen(outfile, "wb")) == NULL) {
732 saved_errno = errno;
733 FILE_OP_ERROR(outfile, "claws_fopen");
734 return -(saved_errno);
737 if (change_file_mode_rw(outfp, outfile) < 0) {
738 FILE_OP_ERROR(outfile, "chmod");
739 g_warning("can't change file mode: %s", outfile);
742 result = procmime_get_part_to_stream(outfp, mimeinfo);
744 if (claws_fclose(outfp) == EOF) {
745 saved_errno = errno;
746 FILE_OP_ERROR(outfile, "claws_fclose");
747 if (claws_unlink(outfile) < 0)
748 FILE_OP_ERROR(outfile, "claws_unlink");
749 return -(saved_errno);
752 return result;
755 gboolean procmime_scan_text_content(MimeInfo *mimeinfo,
756 gboolean (*scan_callback)(const gchar *str, gpointer cb_data),
757 gpointer cb_data)
759 FILE *tmpfp;
760 const gchar *src_codeset;
761 gboolean conv_fail = FALSE;
762 gchar buf[BUFFSIZE];
763 gchar *str;
764 gboolean scan_ret = FALSE;
765 int r;
767 cm_return_val_if_fail(mimeinfo != NULL, TRUE);
768 cm_return_val_if_fail(scan_callback != NULL, TRUE);
770 if (!procmime_decode_content(mimeinfo))
771 return TRUE;
773 tmpfp = my_tmpfile();
775 if (tmpfp == NULL) {
776 FILE_OP_ERROR("tmpfile", "open");
777 return TRUE;
780 if ((r = procmime_get_part_to_stream(tmpfp, mimeinfo)) < 0) {
781 g_warning("procmime_get_part_to_stream error %d", r);
782 return TRUE;
785 src_codeset = forced_charset
786 ? forced_charset :
787 procmime_mimeinfo_get_parameter(mimeinfo, "charset");
789 /* use supersets transparently when possible */
790 if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_ISO_8859_1))
791 src_codeset = CS_WINDOWS_1252;
792 else if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_X_GBK))
793 src_codeset = CS_GB18030;
794 else if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_GBK))
795 src_codeset = CS_GB18030;
796 else if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_GB2312))
797 src_codeset = CS_GB18030;
798 else if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_X_VIET_VPS))
799 src_codeset = CS_WINDOWS_874;
801 if (mimeinfo->type == MIMETYPE_TEXT && !g_ascii_strcasecmp(mimeinfo->subtype, "html")) {
802 SC_HTMLParser *parser;
803 CodeConverter *conv;
805 conv = conv_code_converter_new(src_codeset);
806 parser = sc_html_parser_new(tmpfp, conv);
807 while ((str = sc_html_parse(parser)) != NULL) {
808 if ((scan_ret = scan_callback(str, cb_data)) == TRUE)
809 break;
811 sc_html_parser_destroy(parser);
812 conv_code_converter_destroy(conv);
813 } else if (mimeinfo->type == MIMETYPE_TEXT && !g_ascii_strcasecmp(mimeinfo->subtype, "enriched")) {
814 ERTFParser *parser;
815 CodeConverter *conv;
817 conv = conv_code_converter_new(src_codeset);
818 parser = ertf_parser_new(tmpfp, conv);
819 while ((str = ertf_parse(parser)) != NULL) {
820 if ((scan_ret = scan_callback(str, cb_data)) == TRUE)
821 break;
823 ertf_parser_destroy(parser);
824 conv_code_converter_destroy(conv);
825 } else if (mimeinfo->type == MIMETYPE_TEXT && mimeinfo->disposition != DISPOSITIONTYPE_ATTACHMENT) {
826 while (claws_fgets(buf, sizeof(buf), tmpfp) != NULL) {
827 str = conv_codeset_strdup(buf, src_codeset, CS_UTF_8);
828 if (str) {
829 if ((scan_ret = scan_callback(str, cb_data)) == TRUE) {
830 g_free(str);
831 break;
833 g_free(str);
834 } else {
835 conv_fail = TRUE;
836 if ((scan_ret = scan_callback(buf, cb_data)) == TRUE)
837 break;
842 if (conv_fail)
843 g_warning("procmime_get_text_content(): code conversion failed");
845 claws_fclose(tmpfp);
847 return scan_ret;
850 static gboolean scan_fputs_cb(const gchar *str, gpointer fp)
852 if (claws_fputs(str, (FILE *)fp) == EOF)
853 return TRUE;
855 return FALSE;
858 FILE *procmime_get_text_content(MimeInfo *mimeinfo)
860 FILE *outfp;
861 gboolean err;
863 if ((outfp = my_tmpfile()) == NULL) {
864 perror("my_tmpfile");
865 return NULL;
868 err = procmime_scan_text_content(mimeinfo, scan_fputs_cb, outfp);
870 rewind(outfp);
871 if (err == TRUE) {
872 claws_fclose(outfp);
873 return NULL;
875 return outfp;
879 FILE *procmime_get_binary_content(MimeInfo *mimeinfo)
881 FILE *outfp;
883 cm_return_val_if_fail(mimeinfo != NULL, NULL);
885 if (!procmime_decode_content(mimeinfo))
886 return NULL;
888 outfp = my_tmpfile();
890 if (procmime_get_part_to_stream(outfp, mimeinfo) < 0) {
891 return NULL;
894 return outfp;
897 /* search the first text part of (multipart) MIME message,
898 decode, convert it and output to outfp. */
899 FILE *procmime_get_first_text_content(MsgInfo *msginfo)
901 FILE *outfp = NULL;
902 MimeInfo *mimeinfo, *partinfo;
903 gboolean empty_ok = FALSE, short_scan = TRUE;
905 cm_return_val_if_fail(msginfo != NULL, NULL);
907 /* first we try to short-scan (for speed), refusing empty parts */
908 scan_again:
909 if (short_scan)
910 mimeinfo = procmime_scan_message_short(msginfo);
911 else
912 mimeinfo = procmime_scan_message(msginfo);
913 if (!mimeinfo) return NULL;
915 partinfo = mimeinfo;
916 while (partinfo && (partinfo->type != MIMETYPE_TEXT ||
917 (partinfo->length == 0 && !empty_ok))) {
918 partinfo = procmime_mimeinfo_next(partinfo);
920 if (partinfo)
921 outfp = procmime_get_text_content(partinfo);
922 else if (!empty_ok && short_scan) {
923 /* if short scan didn't find a non-empty part, rescan
924 * fully for non-empty parts
926 short_scan = FALSE;
927 procmime_mimeinfo_free_all(&mimeinfo);
928 goto scan_again;
929 } else if (!empty_ok && !short_scan) {
930 /* if full scan didn't find a non-empty part, rescan
931 * accepting empty parts
933 empty_ok = TRUE;
934 procmime_mimeinfo_free_all(&mimeinfo);
935 goto scan_again;
937 procmime_mimeinfo_free_all(&mimeinfo);
939 return outfp;
943 static gboolean find_encrypted_func(GNode *node, gpointer data)
945 MimeInfo *mimeinfo = (MimeInfo *) node->data;
946 MimeInfo **encinfo = (MimeInfo **) data;
948 if (privacy_mimeinfo_is_encrypted(mimeinfo)) {
949 *encinfo = mimeinfo;
950 return TRUE;
953 return FALSE;
956 static MimeInfo *find_encrypted_part(MimeInfo *rootinfo)
958 MimeInfo *encinfo = NULL;
960 g_node_traverse(rootinfo->node, G_IN_ORDER, G_TRAVERSE_ALL, -1,
961 find_encrypted_func, &encinfo);
963 return encinfo;
966 /* search the first encrypted text part of (multipart) MIME message,
967 decode, convert it and output to outfp. */
968 FILE *procmime_get_first_encrypted_text_content(MsgInfo *msginfo)
970 FILE *outfp = NULL;
971 MimeInfo *mimeinfo, *partinfo, *encinfo;
973 cm_return_val_if_fail(msginfo != NULL, NULL);
975 mimeinfo = procmime_scan_message(msginfo);
976 if (!mimeinfo) {
977 return NULL;
980 partinfo = mimeinfo;
981 if ((encinfo = find_encrypted_part(partinfo)) != NULL) {
982 debug_print("decrypting message part\n");
983 if (privacy_mimeinfo_decrypt(encinfo) < 0) {
984 alertpanel_error(_("Couldn't decrypt: %s"),
985 privacy_get_error());
986 return NULL;
989 partinfo = mimeinfo;
990 while (partinfo && partinfo->type != MIMETYPE_TEXT) {
991 partinfo = procmime_mimeinfo_next(partinfo);
992 if (privacy_mimeinfo_is_signed(partinfo))
993 procmsg_msginfo_set_flags(msginfo, 0, MSG_SIGNED);
996 if (partinfo)
997 outfp = procmime_get_text_content(partinfo);
999 procmime_mimeinfo_free_all(&mimeinfo);
1001 return outfp;
1004 gboolean procmime_msginfo_is_encrypted(MsgInfo *msginfo)
1006 MimeInfo *mimeinfo, *partinfo;
1007 gboolean result = FALSE;
1009 cm_return_val_if_fail(msginfo != NULL, FALSE);
1011 mimeinfo = procmime_scan_message(msginfo);
1012 if (!mimeinfo) {
1013 return FALSE;
1016 partinfo = mimeinfo;
1017 result = (find_encrypted_part(partinfo) != NULL);
1018 procmime_mimeinfo_free_all(&mimeinfo);
1020 return result;
1023 gchar *procmime_get_tmp_file_name(MimeInfo *mimeinfo)
1025 static guint32 id = 0;
1026 gchar *base;
1027 gchar *filename;
1028 gchar f_prefix[10];
1030 cm_return_val_if_fail(mimeinfo != NULL, NULL);
1032 g_snprintf(f_prefix, sizeof(f_prefix), "%08x.", id++);
1034 if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
1035 base = g_strdup("mimetmp.html");
1036 else {
1037 const gchar *basetmp1;
1038 gchar *basetmp2;
1040 basetmp1 = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
1041 if (basetmp1 == NULL)
1042 basetmp1 = procmime_mimeinfo_get_parameter(mimeinfo, "name");
1043 if (basetmp1 == NULL)
1044 basetmp1 = "mimetmp";
1045 basetmp2 = g_path_get_basename(basetmp1);
1046 if (*basetmp2 == '\0') {
1047 g_free(basetmp2);
1048 basetmp2 = g_strdup("mimetmp");
1050 base = conv_filename_from_utf8(basetmp2);
1051 g_free(basetmp2);
1052 subst_for_shellsafe_filename(base);
1055 filename = g_strconcat(get_mime_tmp_dir(), G_DIR_SEPARATOR_S,
1056 f_prefix, base, NULL);
1058 g_free(base);
1060 return filename;
1063 static GList *mime_type_list = NULL;
1065 gchar *procmime_get_mime_type(const gchar *filename)
1067 const gchar *p;
1068 gchar *ext = NULL;
1069 gchar *base;
1070 gchar *str;
1071 #ifndef G_OS_WIN32
1072 static GHashTable *mime_type_table = NULL;
1073 MimeType *mime_type;
1075 if (!mime_type_table) {
1076 mime_type_table = procmime_get_mime_type_table();
1077 if (!mime_type_table) return NULL;
1079 #endif
1081 if (filename == NULL)
1082 return NULL;
1084 base = g_path_get_basename(filename);
1085 if ((p = strrchr(base, '.')) != NULL)
1086 #ifndef G_OS_WIN32
1087 ext = g_utf8_strdown(p + 1, -1);
1088 #else
1089 ext = g_utf8_strdown(p, -1);
1090 #endif
1091 else
1092 ext = g_utf8_strdown(base, -1);
1093 g_free(base);
1095 #ifndef G_OS_WIN32
1096 mime_type = g_hash_table_lookup(mime_type_table, ext);
1098 if (mime_type) {
1099 str = g_strconcat(mime_type->type, "/", mime_type->sub_type,
1100 NULL);
1101 debug_print("got type %s for %s\n", str, ext);
1102 g_free(ext);
1103 return str;
1105 g_free(ext);
1106 return NULL;
1107 #else
1108 str = read_w32_registry_string(HKEY_CLASSES_ROOT, ext, REG_MIME_TYPE_VALUE);
1109 debug_print("got type %s for %s\n", str, ext);
1110 g_free(ext);
1111 return str;
1112 #endif
1115 #ifndef G_OS_WIN32
1116 static guint procmime_str_hash(gconstpointer gptr)
1118 guint hash_result = 0;
1119 const char *str;
1121 for (str = gptr; str && *str; str++) {
1122 if (isupper(*str)) hash_result += (*str + ' ');
1123 else hash_result += *str;
1126 return hash_result;
1129 static gint procmime_str_equal(gconstpointer gptr1, gconstpointer gptr2)
1131 const char *str1 = gptr1;
1132 const char *str2 = gptr2;
1134 return !g_utf8_collate(str1, str2);
1137 static GHashTable *procmime_get_mime_type_table(void)
1139 GHashTable *table = NULL;
1140 GList *cur;
1141 MimeType *mime_type;
1142 gchar **exts;
1144 if (!mime_type_list) {
1145 mime_type_list = procmime_get_mime_type_list();
1146 if (!mime_type_list) return NULL;
1149 table = g_hash_table_new(procmime_str_hash, procmime_str_equal);
1151 for (cur = mime_type_list; cur != NULL; cur = cur->next) {
1152 gint i;
1153 gchar *key;
1155 mime_type = (MimeType *)cur->data;
1157 if (!mime_type->extension) continue;
1159 exts = g_strsplit(mime_type->extension, " ", 16);
1160 for (i = 0; exts[i] != NULL; i++) {
1161 /* Don't overwrite previously inserted extension */
1162 if (!g_hash_table_lookup(table, exts[i])) {
1163 key = g_strdup(exts[i]);
1164 g_hash_table_insert(table, key, mime_type);
1167 g_strfreev(exts);
1170 return table;
1172 #endif
1174 GList *procmime_get_mime_type_list(void)
1176 GList *list = NULL;
1177 FILE *fp;
1178 gchar buf[BUFFSIZE];
1179 gchar *p;
1180 gchar *delim;
1181 MimeType *mime_type;
1182 gboolean fp_is_glob_file = TRUE;
1184 if (mime_type_list)
1185 return mime_type_list;
1187 #if defined(__NetBSD__) || defined(__OpenBSD__) || defined(__FreeBSD__)
1188 if ((fp = claws_fopen(DATAROOTDIR "/mime/globs", "rb")) == NULL)
1189 #else
1190 if ((fp = claws_fopen("/usr/share/mime/globs", "rb")) == NULL)
1191 #endif
1193 fp_is_glob_file = FALSE;
1194 if ((fp = claws_fopen("/etc/mime.types", "rb")) == NULL) {
1195 if ((fp = claws_fopen(SYSCONFDIR "/mime.types", "rb"))
1196 == NULL) {
1197 FILE_OP_ERROR(SYSCONFDIR "/mime.types",
1198 "claws_fopen");
1199 return NULL;
1204 while (claws_fgets(buf, sizeof(buf), fp) != NULL) {
1205 p = strchr(buf, '#');
1206 if (p) *p = '\0';
1207 g_strstrip(buf);
1209 p = buf;
1211 if (fp_is_glob_file) {
1212 while (*p && !g_ascii_isspace(*p) && (*p!=':')) p++;
1213 } else {
1214 while (*p && !g_ascii_isspace(*p)) p++;
1217 if (*p) {
1218 *p = '\0';
1219 p++;
1221 delim = strchr(buf, '/');
1222 if (delim == NULL) continue;
1223 *delim = '\0';
1225 mime_type = g_new(MimeType, 1);
1226 mime_type->type = g_strdup(buf);
1227 mime_type->sub_type = g_strdup(delim + 1);
1229 if (fp_is_glob_file) {
1230 while (*p && (g_ascii_isspace(*p)||(*p=='*')||(*p=='.'))) p++;
1231 } else {
1232 while (*p && g_ascii_isspace(*p)) p++;
1235 if (*p)
1236 mime_type->extension = g_utf8_strdown(p, -1);
1237 else
1238 mime_type->extension = NULL;
1240 list = g_list_append(list, mime_type);
1243 claws_fclose(fp);
1245 if (!list)
1246 g_warning("can't read mime.types");
1248 return list;
1251 EncodingType procmime_get_encoding_for_charset(const gchar *charset)
1253 if (!charset)
1254 return ENC_8BIT;
1255 else if (!g_ascii_strncasecmp(charset, "ISO-2022-", 9) ||
1256 !g_ascii_strcasecmp(charset, "US-ASCII"))
1257 return ENC_7BIT;
1258 else if (!g_ascii_strcasecmp(charset, "ISO-8859-5") ||
1259 !g_ascii_strncasecmp(charset, "KOI8-", 5) ||
1260 !g_ascii_strcasecmp(charset, "X-MAC-CYRILLIC") ||
1261 !g_ascii_strcasecmp(charset, "MAC-CYRILLIC") ||
1262 !g_ascii_strcasecmp(charset, "Windows-1251"))
1263 return ENC_8BIT;
1264 else if (!g_ascii_strncasecmp(charset, "ISO-8859-", 9))
1265 return ENC_QUOTED_PRINTABLE;
1266 else if (!g_ascii_strncasecmp(charset, "UTF-8", 5))
1267 return ENC_QUOTED_PRINTABLE;
1268 else
1269 return ENC_8BIT;
1272 EncodingType procmime_get_encoding_for_text_file(const gchar *file, gboolean *has_binary)
1274 FILE *fp;
1275 guchar buf[BUFFSIZE];
1276 size_t len;
1277 size_t octet_chars = 0;
1278 size_t total_len = 0;
1279 gfloat octet_percentage;
1280 gboolean force_b64 = FALSE;
1282 if ((fp = claws_fopen(file, "rb")) == NULL) {
1283 FILE_OP_ERROR(file, "claws_fopen");
1284 return ENC_UNKNOWN;
1287 while ((len = claws_fread(buf, sizeof(guchar), sizeof(buf), fp)) > 0) {
1288 guchar *p;
1289 gint i;
1291 for (p = buf, i = 0; i < len; ++p, ++i) {
1292 if (*p & 0x80)
1293 ++octet_chars;
1294 if (*p == '\0') {
1295 force_b64 = TRUE;
1296 *has_binary = TRUE;
1299 total_len += len;
1302 claws_fclose(fp);
1304 if (total_len > 0)
1305 octet_percentage = (gfloat)octet_chars / (gfloat)total_len;
1306 else
1307 octet_percentage = 0.0;
1309 debug_print("procmime_get_encoding_for_text_file(): "
1310 "8bit chars: %"G_GSIZE_FORMAT" / %"G_GSIZE_FORMAT" (%f%%)\n", octet_chars, total_len,
1311 100.0 * octet_percentage);
1313 if (octet_percentage > 0.20 || force_b64) {
1314 debug_print("using BASE64\n");
1315 return ENC_BASE64;
1316 } else if (octet_chars > 0) {
1317 debug_print("using quoted-printable\n");
1318 return ENC_QUOTED_PRINTABLE;
1319 } else {
1320 debug_print("using 7bit\n");
1321 return ENC_7BIT;
1325 struct EncodingTable
1327 gchar *str;
1328 EncodingType enc_type;
1331 struct EncodingTable encoding_table[] = {
1332 {"7bit", ENC_7BIT},
1333 {"8bit", ENC_8BIT},
1334 {"binary", ENC_BINARY},
1335 {"quoted-printable", ENC_QUOTED_PRINTABLE},
1336 {"base64", ENC_BASE64},
1337 {"x-uuencode", ENC_UNKNOWN},
1338 {NULL, ENC_UNKNOWN},
1341 const gchar *procmime_get_encoding_str(EncodingType encoding)
1343 struct EncodingTable *enc_table;
1345 for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1346 if (enc_table->enc_type == encoding)
1347 return enc_table->str;
1349 return NULL;
1352 /* --- NEW MIME STUFF --- */
1353 struct TypeTable
1355 gchar *str;
1356 MimeMediaType type;
1359 static struct TypeTable mime_type_table[] = {
1360 {"text", MIMETYPE_TEXT},
1361 {"image", MIMETYPE_IMAGE},
1362 {"audio", MIMETYPE_AUDIO},
1363 {"video", MIMETYPE_VIDEO},
1364 {"font", MIMETYPE_FONT},
1365 {"model", MIMETYPE_MODEL},
1366 {"chemical", MIMETYPE_CHEMICAL},
1367 {"application", MIMETYPE_APPLICATION},
1368 {"message", MIMETYPE_MESSAGE},
1369 {"multipart", MIMETYPE_MULTIPART},
1370 {NULL, 0},
1373 const gchar *procmime_get_media_type_str(MimeMediaType type)
1375 struct TypeTable *type_table;
1377 for (type_table = mime_type_table; type_table->str != NULL; type_table++) {
1378 if (type_table->type == type)
1379 return type_table->str;
1381 return NULL;
1384 MimeMediaType procmime_get_media_type(const gchar *str)
1386 struct TypeTable *typetablearray;
1388 for (typetablearray = mime_type_table; typetablearray->str != NULL; typetablearray++)
1389 if (g_ascii_strncasecmp(str, typetablearray->str, strlen(typetablearray->str)) == 0)
1390 return typetablearray->type;
1392 return MIMETYPE_UNKNOWN;
1396 *\brief Safe wrapper for content type string.
1398 *\return const gchar * Pointer to content type string.
1400 gchar *procmime_get_content_type_str(MimeMediaType type,
1401 const char *subtype)
1403 const gchar *type_str = NULL;
1405 if (subtype == NULL || !(type_str = procmime_get_media_type_str(type)))
1406 return g_strdup("unknown");
1407 return g_strdup_printf("%s/%s", type_str, subtype);
1410 static int procmime_parse_mimepart(MimeInfo *parent,
1411 gchar *content_type,
1412 gchar *content_encoding,
1413 gchar *content_description,
1414 gchar *content_id,
1415 gchar *content_disposition,
1416 gchar *content_location,
1417 const gchar *original_msgid,
1418 const gchar *disposition_notification_hdr,
1419 const gchar *filename,
1420 guint offset,
1421 guint length,
1422 gboolean short_scan);
1424 static void procmime_parse_message_rfc822(MimeInfo *mimeinfo, gboolean short_scan)
1426 HeaderEntry hentry[] = {{"Content-Type:", NULL, TRUE},
1427 {"Content-Transfer-Encoding:",
1428 NULL, FALSE},
1429 {"Content-Description:",
1430 NULL, TRUE},
1431 {"Content-ID:",
1432 NULL, TRUE},
1433 {"Content-Disposition:",
1434 NULL, TRUE},
1435 {"Content-Location:",
1436 NULL, TRUE},
1437 {"MIME-Version:",
1438 NULL, TRUE},
1439 {"Original-Message-ID:",
1440 NULL, TRUE},
1441 {"Disposition:",
1442 NULL, TRUE},
1443 {NULL, NULL, FALSE}};
1444 guint content_start, i;
1445 FILE *fp;
1446 gchar *tmp;
1447 gint len = 0;
1449 procmime_decode_content(mimeinfo);
1451 fp = claws_fopen(mimeinfo->data.filename, "rb");
1452 if (fp == NULL) {
1453 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
1454 return;
1456 if (fseek(fp, mimeinfo->offset, SEEK_SET) < 0) {
1457 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
1458 claws_fclose(fp);
1459 return;
1461 procheader_get_header_fields(fp, hentry);
1462 if (hentry[0].body != NULL) {
1463 tmp = conv_unmime_header(hentry[0].body, NULL, FALSE);
1464 g_free(hentry[0].body);
1465 hentry[0].body = tmp;
1467 if (hentry[2].body != NULL) {
1468 tmp = conv_unmime_header(hentry[2].body, NULL, FALSE);
1469 g_free(hentry[2].body);
1470 hentry[2].body = tmp;
1472 if (hentry[4].body != NULL) {
1473 tmp = conv_unmime_header(hentry[4].body, NULL, FALSE);
1474 g_free(hentry[4].body);
1475 hentry[4].body = tmp;
1477 if (hentry[5].body != NULL) {
1478 tmp = conv_unmime_header(hentry[5].body, NULL, FALSE);
1479 g_free(hentry[5].body);
1480 hentry[5].body = tmp;
1482 if (hentry[7].body != NULL) {
1483 tmp = conv_unmime_header(hentry[7].body, NULL, FALSE);
1484 g_free(hentry[7].body);
1485 hentry[7].body = tmp;
1487 if (hentry[8].body != NULL) {
1488 tmp = conv_unmime_header(hentry[8].body, NULL, FALSE);
1489 g_free(hentry[8].body);
1490 hentry[8].body = tmp;
1493 content_start = ftell(fp);
1494 claws_fclose(fp);
1496 len = mimeinfo->length - (content_start - mimeinfo->offset);
1497 if (len < 0)
1498 len = 0;
1499 procmime_parse_mimepart(mimeinfo,
1500 hentry[0].body, hentry[1].body,
1501 hentry[2].body, hentry[3].body,
1502 hentry[4].body, hentry[5].body,
1503 hentry[7].body, hentry[8].body,
1504 mimeinfo->data.filename, content_start,
1505 len, short_scan);
1507 for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1508 g_free(hentry[i].body);
1509 hentry[i].body = NULL;
1513 static void procmime_parse_disposition_notification(MimeInfo *mimeinfo,
1514 const gchar *original_msgid, const gchar *disposition_notification_hdr,
1515 gboolean short_scan)
1517 HeaderEntry hentry[] = {{"Original-Message-ID:", NULL, TRUE},
1518 {"Disposition:", NULL, TRUE},
1519 {NULL, NULL, FALSE}};
1520 guint i;
1521 FILE *fp;
1522 gchar *orig_msg_id = NULL;
1523 gchar *disp = NULL;
1525 procmime_decode_content(mimeinfo);
1527 debug_print("parse disposition notification\n");
1528 fp = claws_fopen(mimeinfo->data.filename, "rb");
1529 if (fp == NULL) {
1530 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
1531 return;
1533 if (fseek(fp, mimeinfo->offset, SEEK_SET) < 0) {
1534 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
1535 claws_fclose(fp);
1536 return;
1539 if (original_msgid && disposition_notification_hdr) {
1540 hentry[0].body = g_strdup(original_msgid);
1541 hentry[1].body = g_strdup(disposition_notification_hdr);
1542 } else {
1543 procheader_get_header_fields(fp, hentry);
1546 claws_fclose(fp);
1548 if (!hentry[0].body || !hentry[1].body) {
1549 debug_print("MsgId %s, Disp %s\n",
1550 hentry[0].body ? hentry[0].body:"(nil)",
1551 hentry[1].body ? hentry[1].body:"(nil)");
1552 goto bail;
1555 orig_msg_id = g_strdup(hentry[0].body);
1556 disp = g_strdup(hentry[1].body);
1558 extract_parenthesis(orig_msg_id, '<', '>');
1559 remove_space(orig_msg_id);
1561 if (strstr(disp, "displayed")) {
1562 /* find sent message, if possible */
1563 MsgInfo *info = NULL;
1564 GList *flist;
1565 debug_print("%s has been displayed.\n", orig_msg_id);
1566 for (flist = folder_get_list(); flist != NULL; flist = g_list_next(flist)) {
1567 FolderItem *outbox = ((Folder *)(flist->data))->outbox;
1568 if (!outbox) {
1569 debug_print("skipping folder with no outbox...\n");
1570 continue;
1572 info = folder_item_get_msginfo_by_msgid(outbox, orig_msg_id);
1573 debug_print("%s %s in %s\n", info?"found":"didn't find", orig_msg_id, outbox->path);
1574 if (info) {
1575 procmsg_msginfo_set_flags(info, MSG_RETRCPT_GOT, 0);
1576 procmsg_msginfo_free(&info);
1580 g_free(orig_msg_id);
1581 g_free(disp);
1582 bail:
1583 for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1584 g_free(hentry[i].body);
1585 hentry[i].body = NULL;
1589 #define GET_HEADERS() { \
1590 procheader_get_header_fields(fp, hentry); \
1591 if (hentry[0].body != NULL) { \
1592 tmp = conv_unmime_header(hentry[0].body, NULL, FALSE); \
1593 g_free(hentry[0].body); \
1594 hentry[0].body = tmp; \
1596 if (hentry[2].body != NULL) { \
1597 tmp = conv_unmime_header(hentry[2].body, NULL, FALSE); \
1598 g_free(hentry[2].body); \
1599 hentry[2].body = tmp; \
1601 if (hentry[4].body != NULL) { \
1602 tmp = conv_unmime_header(hentry[4].body, NULL, FALSE); \
1603 g_free(hentry[4].body); \
1604 hentry[4].body = tmp; \
1606 if (hentry[5].body != NULL) { \
1607 tmp = conv_unmime_header(hentry[5].body, NULL, FALSE); \
1608 g_free(hentry[5].body); \
1609 hentry[5].body = tmp; \
1611 if (hentry[6].body != NULL) { \
1612 tmp = conv_unmime_header(hentry[6].body, NULL, FALSE); \
1613 g_free(hentry[6].body); \
1614 hentry[6].body = tmp; \
1616 if (hentry[7].body != NULL) { \
1617 tmp = conv_unmime_header(hentry[7].body, NULL, FALSE); \
1618 g_free(hentry[7].body); \
1619 hentry[7].body = tmp; \
1623 static void procmime_parse_multipart(MimeInfo *mimeinfo, gboolean short_scan)
1625 HeaderEntry hentry[] = {{"Content-Type:", NULL, TRUE},
1626 {"Content-Transfer-Encoding:",
1627 NULL, FALSE},
1628 {"Content-Description:",
1629 NULL, TRUE},
1630 {"Content-ID:",
1631 NULL, TRUE},
1632 {"Content-Disposition:",
1633 NULL, TRUE},
1634 {"Content-Location:",
1635 NULL, TRUE},
1636 {"Original-Message-ID:",
1637 NULL, TRUE},
1638 {"Disposition:",
1639 NULL, TRUE},
1640 {NULL, NULL, FALSE}};
1641 gchar *tmp;
1642 gchar *boundary;
1643 gint boundary_len = 0, lastoffset = -1, i;
1644 gchar buf[BUFFSIZE];
1645 FILE *fp;
1646 int result = 0;
1647 gboolean start_found = FALSE;
1648 gboolean end_found = FALSE;
1650 boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
1651 if (!boundary)
1652 return;
1653 boundary_len = strlen(boundary);
1655 procmime_decode_content(mimeinfo);
1657 fp = claws_fopen(mimeinfo->data.filename, "rb");
1658 if (fp == NULL) {
1659 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
1660 return;
1663 if (fseek(fp, mimeinfo->offset, SEEK_SET) < 0) {
1664 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
1665 claws_fclose(fp);
1666 return;
1669 while (claws_fgets(buf, sizeof(buf), fp) != NULL && result == 0) {
1670 if (ftell(fp) - 1 > (mimeinfo->offset + mimeinfo->length))
1671 break;
1673 if (IS_BOUNDARY(buf, boundary, boundary_len)) {
1674 start_found = TRUE;
1676 if (lastoffset != -1) {
1677 gint len = (ftell(fp) - strlen(buf)) - lastoffset - 1;
1678 if (len < 0)
1679 len = 0;
1680 result = procmime_parse_mimepart(mimeinfo,
1681 hentry[0].body, hentry[1].body,
1682 hentry[2].body, hentry[3].body,
1683 hentry[4].body, hentry[5].body,
1684 hentry[6].body, hentry[7].body,
1685 mimeinfo->data.filename, lastoffset,
1686 len, short_scan);
1687 if (result == 1 && short_scan)
1688 break;
1692 if (buf[2 + boundary_len] == '-' &&
1693 buf[2 + boundary_len + 1] == '-') {
1694 end_found = TRUE;
1695 break;
1697 for (i = 0; i < (sizeof hentry / sizeof hentry[0]) ; i++) {
1698 g_free(hentry[i].body);
1699 hentry[i].body = NULL;
1701 GET_HEADERS();
1702 lastoffset = ftell(fp);
1706 if (start_found && !end_found && lastoffset != -1) {
1707 gint len = (ftell(fp) - strlen(buf)) - lastoffset - 1;
1709 if (len >= 0) {
1710 result = procmime_parse_mimepart(mimeinfo,
1711 hentry[0].body, hentry[1].body,
1712 hentry[2].body, hentry[3].body,
1713 hentry[4].body, hentry[5].body,
1714 hentry[6].body, hentry[7].body,
1715 mimeinfo->data.filename, lastoffset,
1716 len, short_scan);
1718 mimeinfo->broken = TRUE;
1721 for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1722 g_free(hentry[i].body);
1723 hentry[i].body = NULL;
1725 claws_fclose(fp);
1728 static void parse_parameters(const gchar *parameters, GHashTable *table)
1730 gchar *params, *param, *next;
1731 GSList *convlist = NULL, *concatlist = NULL, *cur;
1733 params = g_strdup(parameters);
1734 param = params;
1735 next = params;
1736 for (; next != NULL; param = next) {
1737 gchar *attribute, *value, *tmp, *down_attr, *orig_down_attr;
1738 gint len;
1739 gboolean convert = FALSE;
1741 next = strchr_with_skip_quote(param, '"', ';');
1742 if (next != NULL) {
1743 next[0] = '\0';
1744 next++;
1747 g_strstrip(param);
1749 attribute = param;
1750 value = strchr(attribute, '=');
1751 if (value == NULL)
1752 continue;
1754 value[0] = '\0';
1755 value++;
1756 while (value[0] != '\0' && value[0] == ' ')
1757 value++;
1759 down_attr = g_utf8_strdown(attribute, -1);
1760 orig_down_attr = down_attr;
1762 len = down_attr ? strlen(down_attr):0;
1763 if (len > 0 && down_attr[len - 1] == '*') {
1764 gchar *srcpos, *dstpos, *endpos;
1766 convert = TRUE;
1767 down_attr[len - 1] = '\0';
1769 srcpos = value;
1770 dstpos = value;
1771 endpos = value + strlen(value);
1772 while (srcpos < endpos) {
1773 if (*srcpos != '%')
1774 *dstpos = *srcpos;
1775 else {
1776 guchar dstvalue;
1778 if (!get_hex_value(&dstvalue, srcpos[1], srcpos[2]))
1779 *dstpos = '?';
1780 else
1781 *dstpos = dstvalue;
1782 srcpos += 2;
1784 srcpos++;
1785 dstpos++;
1787 *dstpos = '\0';
1788 if (value[0] == '"')
1789 extract_quote(value, '"');
1790 } else {
1791 if (value[0] == '"')
1792 extract_quote(value, '"');
1793 else if ((tmp = strchr(value, ' ')) != NULL)
1794 *tmp = '\0';
1797 if (down_attr) {
1798 while (down_attr[0] == ' ')
1799 down_attr++;
1800 while (down_attr[strlen(down_attr)-1] == ' ')
1801 down_attr[strlen(down_attr)-1] = '\0';
1804 while (value[0] != '\0' && value[0] == ' ')
1805 value++;
1806 while (value[strlen(value)-1] == ' ')
1807 value[strlen(value)-1] = '\0';
1809 if (down_attr && strrchr(down_attr, '*') != NULL) {
1810 gchar *tmpattr;
1812 tmpattr = g_strdup(down_attr);
1813 tmp = strrchr(tmpattr, '*');
1814 tmp[0] = '\0';
1816 if ((tmp[1] == '0') && (tmp[2] == '\0') &&
1817 (g_slist_find_custom(concatlist, down_attr, (GCompareFunc)g_strcmp0) == NULL))
1818 concatlist = g_slist_prepend(concatlist, g_strdup(tmpattr));
1820 if (convert && (g_slist_find_custom(convlist, tmpattr, (GCompareFunc)g_strcmp0) == NULL))
1821 convlist = g_slist_prepend(convlist, g_strdup(tmpattr));
1823 g_free(tmpattr);
1824 } else if (convert) {
1825 if (g_slist_find_custom(convlist, down_attr, (GCompareFunc)g_strcmp0) == NULL)
1826 convlist = g_slist_prepend(convlist, g_strdup(down_attr));
1829 if (g_hash_table_lookup(table, down_attr) == NULL)
1830 g_hash_table_insert(table, g_strdup(down_attr), g_strdup(value));
1831 g_free(orig_down_attr);
1834 for (cur = concatlist; cur != NULL; cur = g_slist_next(cur)) {
1835 gchar *attribute, *attrwnum, *partvalue;
1836 gint n = 0;
1837 GString *value;
1839 attribute = (gchar *) cur->data;
1840 value = g_string_sized_new(64);
1842 attrwnum = g_strdup_printf("%s*%d", attribute, n);
1843 while ((partvalue = g_hash_table_lookup(table, attrwnum)) != NULL) {
1844 g_string_append(value, partvalue);
1846 g_hash_table_remove(table, attrwnum);
1847 g_free(attrwnum);
1848 n++;
1849 attrwnum = g_strdup_printf("%s*%d", attribute, n);
1851 g_free(attrwnum);
1853 g_hash_table_insert(table, g_strdup(attribute), g_strdup(value->str));
1854 g_string_free(value, TRUE);
1856 slist_free_strings_full(concatlist);
1858 for (cur = convlist; cur != NULL; cur = g_slist_next(cur)) {
1859 gchar *attribute, *key, *value;
1860 gchar *charset, *lang, *oldvalue, *newvalue;
1862 attribute = (gchar *) cur->data;
1863 if (!g_hash_table_lookup_extended(
1864 table, attribute, (gpointer *)(gchar *) &key, (gpointer *)(gchar *) &value))
1865 continue;
1867 charset = value;
1868 if (charset == NULL)
1869 continue;
1870 lang = strchr(charset, '\'');
1871 if (lang == NULL)
1872 continue;
1873 lang[0] = '\0';
1874 lang++;
1875 oldvalue = strchr(lang, '\'');
1876 if (oldvalue == NULL)
1877 continue;
1878 oldvalue[0] = '\0';
1879 oldvalue++;
1881 newvalue = conv_codeset_strdup(oldvalue, charset, CS_UTF_8);
1883 g_hash_table_remove(table, attribute);
1884 g_free(key);
1885 g_free(value);
1887 g_hash_table_insert(table, g_strdup(attribute), newvalue);
1889 slist_free_strings_full(convlist);
1891 g_free(params);
1894 static void procmime_parse_content_type(const gchar *content_type, MimeInfo *mimeinfo)
1896 cm_return_if_fail(content_type != NULL);
1897 cm_return_if_fail(mimeinfo != NULL);
1899 /* RFC 2045, page 13 says that the mime subtype is MANDATORY;
1900 * if it's not available we use the default Content-Type */
1901 if ((content_type[0] == '\0') || (strchr(content_type, '/') == NULL)) {
1902 mimeinfo->type = MIMETYPE_TEXT;
1903 mimeinfo->subtype = g_strdup("plain");
1904 if (g_hash_table_lookup(mimeinfo->typeparameters,
1905 "charset") == NULL) {
1906 g_hash_table_insert(mimeinfo->typeparameters,
1907 g_strdup("charset"),
1908 g_strdup(
1909 conv_get_locale_charset_str_no_utf8()));
1911 } else {
1912 gchar *type, *subtype, *params;
1914 type = g_strdup(content_type);
1915 subtype = strchr(type, '/') + 1;
1916 *(subtype - 1) = '\0';
1917 if ((params = strchr(subtype, ';')) != NULL) {
1918 params[0] = '\0';
1919 params++;
1922 mimeinfo->type = procmime_get_media_type(type);
1923 mimeinfo->subtype = g_strstrip(g_strdup(subtype));
1925 /* Get mimeinfo->typeparameters */
1926 if (params != NULL)
1927 parse_parameters(params, mimeinfo->typeparameters);
1929 g_free(type);
1933 static void procmime_parse_content_disposition(const gchar *content_disposition, MimeInfo *mimeinfo)
1935 gchar *tmp, *params;
1937 cm_return_if_fail(content_disposition != NULL);
1938 cm_return_if_fail(mimeinfo != NULL);
1940 tmp = g_strdup(content_disposition);
1941 if ((params = strchr(tmp, ';')) != NULL) {
1942 params[0] = '\0';
1943 params++;
1945 g_strstrip(tmp);
1947 if (!g_ascii_strcasecmp(tmp, "inline"))
1948 mimeinfo->disposition = DISPOSITIONTYPE_INLINE;
1949 else if (!g_ascii_strcasecmp(tmp, "attachment"))
1950 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1951 else
1952 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1954 if (params != NULL)
1955 parse_parameters(params, mimeinfo->dispositionparameters);
1957 g_free(tmp);
1961 static void procmime_parse_content_encoding(const gchar *content_encoding, MimeInfo *mimeinfo)
1963 struct EncodingTable *enc_table;
1965 for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1966 if (g_ascii_strcasecmp(enc_table->str, content_encoding) == 0) {
1967 mimeinfo->encoding_type = enc_table->enc_type;
1968 return;
1971 mimeinfo->encoding_type = ENC_UNKNOWN;
1972 return;
1975 static GSList *registered_parsers = NULL;
1977 static MimeParser *procmime_get_mimeparser_for_type(MimeMediaType type, const gchar *sub_type)
1979 GSList *cur;
1980 for (cur = registered_parsers; cur; cur = cur->next) {
1981 MimeParser *parser = (MimeParser *)cur->data;
1982 if (parser->type == type && !g_strcmp0(parser->sub_type, sub_type))
1983 return parser;
1985 return NULL;
1988 void procmime_mimeparser_register(MimeParser *parser)
1990 if (!procmime_get_mimeparser_for_type(parser->type, parser->sub_type))
1991 registered_parsers = g_slist_append(registered_parsers, parser);
1995 void procmime_mimeparser_unregister(MimeParser *parser)
1997 registered_parsers = g_slist_remove(registered_parsers, parser);
2000 static gboolean procmime_mimeparser_parse(MimeParser *parser, MimeInfo *mimeinfo)
2002 cm_return_val_if_fail(parser->parse != NULL, FALSE);
2003 return parser->parse(parser, mimeinfo);
2006 static int procmime_parse_mimepart(MimeInfo *parent,
2007 gchar *content_type,
2008 gchar *content_encoding,
2009 gchar *content_description,
2010 gchar *content_id,
2011 gchar *content_disposition,
2012 gchar *content_location,
2013 const gchar *original_msgid,
2014 const gchar *disposition_notification_hdr,
2015 const gchar *filename,
2016 guint offset,
2017 guint length,
2018 gboolean short_scan)
2020 MimeInfo *mimeinfo;
2021 MimeParser *parser = NULL;
2022 gboolean parsed = FALSE;
2023 int result = 0;
2025 /* Create MimeInfo */
2026 mimeinfo = procmime_mimeinfo_new();
2027 mimeinfo->content = MIMECONTENT_FILE;
2029 if (parent != NULL) {
2030 if (g_node_depth(parent->node) > 32) {
2031 /* 32 is an arbitrary value
2032 * this avoids DOSsing ourselves
2033 * with enormous messages
2035 procmime_mimeinfo_free_all(&mimeinfo);
2036 return -1;
2038 g_node_append(parent->node, mimeinfo->node);
2040 mimeinfo->data.filename = g_strdup(filename);
2041 mimeinfo->offset = offset;
2042 mimeinfo->length = length;
2044 if (content_type != NULL) {
2045 g_strchomp(content_type);
2046 procmime_parse_content_type(content_type, mimeinfo);
2047 } else {
2048 mimeinfo->type = MIMETYPE_TEXT;
2049 mimeinfo->subtype = g_strdup("plain");
2050 if (g_hash_table_lookup(mimeinfo->typeparameters,
2051 "charset") == NULL) {
2052 g_hash_table_insert(mimeinfo->typeparameters,
2053 g_strdup("charset"),
2054 g_strdup(
2055 conv_get_locale_charset_str_no_utf8()));
2059 if (content_encoding != NULL) {
2060 g_strchomp(content_encoding);
2061 procmime_parse_content_encoding(content_encoding, mimeinfo);
2062 } else {
2063 mimeinfo->encoding_type = ENC_UNKNOWN;
2066 if (content_description != NULL)
2067 mimeinfo->description = g_strdup(content_description);
2068 else
2069 mimeinfo->description = NULL;
2071 if (content_id != NULL)
2072 mimeinfo->id = g_strdup(content_id);
2073 else
2074 mimeinfo->id = NULL;
2076 if (content_location != NULL)
2077 mimeinfo->location = g_strdup(content_location);
2078 else
2079 mimeinfo->location = NULL;
2081 if (content_disposition != NULL) {
2082 g_strchomp(content_disposition);
2083 procmime_parse_content_disposition(content_disposition, mimeinfo);
2084 } else
2085 mimeinfo->disposition = DISPOSITIONTYPE_UNKNOWN;
2087 /* Call parser for mime type */
2088 if ((parser = procmime_get_mimeparser_for_type(mimeinfo->type, mimeinfo->subtype)) != NULL) {
2089 parsed = procmime_mimeparser_parse(parser, mimeinfo);
2091 if (!parsed) {
2092 switch (mimeinfo->type) {
2093 case MIMETYPE_TEXT:
2094 if (g_ascii_strcasecmp(mimeinfo->subtype, "plain") == 0 && short_scan) {
2095 return 1;
2097 break;
2099 case MIMETYPE_MESSAGE:
2100 if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
2101 procmime_parse_message_rfc822(mimeinfo, short_scan);
2103 if (g_ascii_strcasecmp(mimeinfo->subtype, "disposition-notification") == 0) {
2104 procmime_parse_disposition_notification(mimeinfo,
2105 original_msgid, disposition_notification_hdr, short_scan);
2107 break;
2109 case MIMETYPE_MULTIPART:
2110 procmime_parse_multipart(mimeinfo, short_scan);
2111 break;
2113 case MIMETYPE_APPLICATION:
2114 if (g_ascii_strcasecmp(mimeinfo->subtype, "octet-stream") == 0
2115 && original_msgid && *original_msgid
2116 && disposition_notification_hdr && *disposition_notification_hdr) {
2117 procmime_parse_disposition_notification(mimeinfo,
2118 original_msgid, disposition_notification_hdr, short_scan);
2120 break;
2121 default:
2122 break;
2126 return result;
2129 static gchar *typenames[] = {
2130 "text",
2131 "image",
2132 "audio",
2133 "video",
2134 "application",
2135 "message",
2136 "multipart",
2137 "font",
2138 "model",
2139 "chemical",
2140 "unknown",
2143 static gboolean output_func(GNode *node, gpointer data)
2145 guint i, depth;
2146 MimeInfo *mimeinfo = (MimeInfo *) node->data;
2148 depth = g_node_depth(node);
2149 for (i = 0; i < depth; i++)
2150 g_print(" ");
2151 g_print("%s/%s (offset:%d length:%d encoding: %d)\n",
2152 (mimeinfo->type <= MIMETYPE_UNKNOWN)? typenames[mimeinfo->type] : "unknown",
2153 mimeinfo->subtype, mimeinfo->offset, mimeinfo->length, mimeinfo->encoding_type);
2155 return FALSE;
2158 static void output_mime_structure(MimeInfo *mimeinfo, int indent)
2160 g_node_traverse(mimeinfo->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1, output_func, NULL);
2163 static MimeInfo *procmime_scan_file_with_offset(const gchar *filename, int offset, gboolean short_scan)
2165 MimeInfo *mimeinfo;
2166 GStatBuf buf;
2168 if (g_stat(filename, &buf) < 0) {
2169 FILE_OP_ERROR(filename, "stat");
2170 return NULL;
2173 mimeinfo = procmime_mimeinfo_new();
2174 mimeinfo->content = MIMECONTENT_FILE;
2175 mimeinfo->encoding_type = ENC_UNKNOWN;
2176 mimeinfo->type = MIMETYPE_MESSAGE;
2177 mimeinfo->subtype = g_strdup("rfc822");
2178 mimeinfo->data.filename = g_strdup(filename);
2179 mimeinfo->offset = offset;
2180 mimeinfo->length = buf.st_size - offset;
2182 procmime_parse_message_rfc822(mimeinfo, short_scan);
2183 if (debug_get_mode())
2184 output_mime_structure(mimeinfo, 0);
2186 return mimeinfo;
2189 static MimeInfo *procmime_scan_file_full(const gchar *filename, gboolean short_scan)
2191 MimeInfo *mimeinfo;
2193 cm_return_val_if_fail(filename != NULL, NULL);
2195 mimeinfo = procmime_scan_file_with_offset(filename, 0, short_scan);
2197 return mimeinfo;
2200 MimeInfo *procmime_scan_file(const gchar *filename)
2202 return procmime_scan_file_full(filename, FALSE);
2205 static MimeInfo *procmime_scan_file_short(const gchar *filename)
2207 return procmime_scan_file_full(filename, TRUE);
2210 static MimeInfo *procmime_scan_queue_file_full(const gchar *filename, gboolean short_scan)
2212 FILE *fp;
2213 MimeInfo *mimeinfo;
2214 gchar buf[BUFFSIZE];
2215 gint offset = 0;
2217 cm_return_val_if_fail(filename != NULL, NULL);
2219 /* Open file */
2220 if ((fp = claws_fopen(filename, "rb")) == NULL)
2221 return NULL;
2222 /* Skip queue header */
2223 while (claws_fgets(buf, sizeof(buf), fp) != NULL) {
2224 /* new way */
2225 if ((!strncmp(buf, "X-Claws-End-Special-Headers: 1",
2226 strlen("X-Claws-End-Special-Headers:"))) ||
2227 (!strncmp(buf, "X-Sylpheed-End-Special-Headers: 1",
2228 strlen("X-Sylpheed-End-Special-Headers:"))))
2229 break;
2230 /* old way */
2231 if (buf[0] == '\r' || buf[0] == '\n') break;
2232 /* from other mailers */
2233 if (!strncmp(buf, "Date: ", 6)
2234 || !strncmp(buf, "To: ", 4)
2235 || !strncmp(buf, "From: ", 6)
2236 || !strncmp(buf, "Subject: ", 9)) {
2237 rewind(fp);
2238 break;
2241 offset = ftell(fp);
2242 claws_fclose(fp);
2244 mimeinfo = procmime_scan_file_with_offset(filename, offset, short_scan);
2246 return mimeinfo;
2249 MimeInfo *procmime_scan_queue_file(const gchar *filename)
2251 return procmime_scan_queue_file_full(filename, FALSE);
2254 static MimeInfo *procmime_scan_queue_file_short(const gchar *filename)
2256 return procmime_scan_queue_file_full(filename, TRUE);
2259 typedef enum {
2260 ENC_AS_TOKEN,
2261 ENC_AS_QUOTED_STRING,
2262 ENC_AS_EXTENDED,
2263 ENC_AS_ENCWORD
2264 } EncodeAs;
2266 typedef struct _ParametersData {
2267 FILE *fp;
2268 guint len;
2269 gint error;
2270 } ParametersData;
2272 static void write_parameters(gpointer key, gpointer value, gpointer user_data)
2274 gchar *param = key;
2275 gchar *val = value, *valpos, *tmp;
2276 ParametersData *pdata = (ParametersData *)user_data;
2277 GString *buf = g_string_new("");
2278 gint len;
2280 EncodeAs encas = ENC_AS_TOKEN;
2282 for (valpos = val; *valpos != 0; valpos++) {
2283 if (!IS_ASCII(*valpos)) {
2284 encas = ENC_AS_ENCWORD;
2285 break;
2288 /* CTLs */
2289 if (((*valpos >= 0) && (*valpos < 037)) || (*valpos == 0177)) {
2290 encas = ENC_AS_QUOTED_STRING;
2291 continue;
2294 /* tspecials + SPACE */
2295 switch (*valpos) {
2296 case ' ':
2297 case '(':
2298 case ')':
2299 case '<':
2300 case '>':
2301 case '@':
2302 case ',':
2303 case ';':
2304 case ':':
2305 case '\\':
2306 case '"':
2307 case '/':
2308 case '[':
2309 case ']':
2310 case '?':
2311 case '=':
2312 encas = ENC_AS_QUOTED_STRING;
2313 continue;
2317 switch (encas) {
2318 case ENC_AS_TOKEN:
2319 g_string_append_printf(buf, "%s=%s", param, val);
2320 break;
2322 case ENC_AS_QUOTED_STRING:
2323 g_string_append_printf(buf, "%s=\"%s\"", param, val);
2324 break;
2326 #if 0 /* we don't use that for now */
2327 case ENC_AS_EXTENDED:
2328 if (!g_utf8_validate(val, -1, NULL))
2329 g_string_append_printf(buf, "%s*=%s''", param,
2330 conv_get_locale_charset_str());
2331 else
2332 g_string_append_printf(buf, "%s*=%s''", param,
2333 CS_INTERNAL);
2334 for (valpos = val; *valpos != '\0'; valpos++) {
2335 if (IS_ASCII(*valpos) && isalnum(*valpos)) {
2336 g_string_append_printf(buf, "%c", *valpos);
2337 } else {
2338 gchar hexstr[3] = "XX";
2339 get_hex_str(hexstr, *valpos);
2340 g_string_append_printf(buf, "%%%s", hexstr);
2343 break;
2344 #else
2345 case ENC_AS_EXTENDED:
2346 debug_print("Unhandled ENC_AS_EXTENDED.\n");
2347 break;
2348 #endif
2349 case ENC_AS_ENCWORD:
2350 len = MAX(strlen(val)*6, 512);
2351 tmp = g_malloc(len+1);
2352 codeconv_set_strict(TRUE);
2353 conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2354 prefs_common.outgoing_charset);
2355 codeconv_set_strict(FALSE);
2356 if (!tmp || !*tmp) {
2357 codeconv_set_strict(TRUE);
2358 conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2359 conv_get_outgoing_charset_str());
2360 codeconv_set_strict(FALSE);
2362 if (!tmp || !*tmp) {
2363 codeconv_set_strict(TRUE);
2364 conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2365 CS_UTF_8);
2366 codeconv_set_strict(FALSE);
2368 if (!tmp || !*tmp) {
2369 conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2370 CS_UTF_8);
2372 g_string_append_printf(buf, "%s=\"%s\"", param, tmp);
2373 g_free(tmp);
2374 break;
2378 if (buf->str && strlen(buf->str)) {
2379 tmp = strstr(buf->str, "\n");
2380 if (tmp)
2381 len = (tmp - buf->str);
2382 else
2383 len = strlen(buf->str);
2384 if (pdata->len + len > 76) {
2385 if (fprintf(pdata->fp, ";\n %s", buf->str) < 0)
2386 pdata->error = TRUE;
2387 pdata->len = strlen(buf->str) + 1;
2388 } else {
2389 if (fprintf(pdata->fp, "; %s", buf->str) < 0)
2390 pdata->error = TRUE;
2391 pdata->len += strlen(buf->str) + 2;
2394 g_string_free(buf, TRUE);
2397 #define TRY(func) { \
2398 if (!(func)) { \
2399 return -1; \
2403 int procmime_write_mime_header(MimeInfo *mimeinfo, FILE *fp)
2405 struct TypeTable *type_table;
2406 ParametersData *pdata = g_new0(ParametersData, 1);
2407 debug_print("procmime_write_mime_header\n");
2409 pdata->fp = fp;
2410 pdata->error = FALSE;
2411 for (type_table = mime_type_table; type_table->str != NULL; type_table++)
2412 if (mimeinfo->type == type_table->type) {
2413 gchar *buf = g_strdup_printf(
2414 "Content-Type: %s/%s", type_table->str, mimeinfo->subtype);
2415 if (fprintf(fp, "%s", buf) < 0) {
2416 g_free(buf);
2417 g_free(pdata);
2418 return -1;
2420 pdata->len = strlen(buf);
2421 g_free(buf);
2422 break;
2424 g_hash_table_foreach(mimeinfo->typeparameters, write_parameters, pdata);
2425 if (pdata->error == TRUE) {
2426 g_free(pdata);
2427 return -1;
2429 g_free(pdata);
2431 TRY(fprintf(fp, "\n") >= 0);
2433 if (mimeinfo->encoding_type != ENC_UNKNOWN)
2434 TRY(fprintf(fp, "Content-Transfer-Encoding: %s\n", procmime_get_encoding_str(mimeinfo->encoding_type)) >= 0);
2436 if (mimeinfo->description != NULL)
2437 TRY(fprintf(fp, "Content-Description: %s\n", mimeinfo->description) >= 0);
2439 if (mimeinfo->id != NULL)
2440 TRY(fprintf(fp, "Content-ID: %s\n", mimeinfo->id) >= 0);
2442 if (mimeinfo->location != NULL)
2443 TRY(fprintf(fp, "Content-Location: %s\n", mimeinfo->location) >= 0);
2445 if (mimeinfo->disposition != DISPOSITIONTYPE_UNKNOWN) {
2446 ParametersData *pdata = g_new0(ParametersData, 1);
2447 gchar *buf = NULL;
2448 if (mimeinfo->disposition == DISPOSITIONTYPE_INLINE)
2449 buf = g_strdup("Content-Disposition: inline");
2450 else if (mimeinfo->disposition == DISPOSITIONTYPE_ATTACHMENT)
2451 buf = g_strdup("Content-Disposition: attachment");
2452 else
2453 buf = g_strdup("Content-Disposition: unknown");
2455 if (fprintf(fp, "%s", buf) < 0) {
2456 g_free(buf);
2457 g_free(pdata);
2458 return -1;
2460 pdata->len = strlen(buf);
2461 g_free(buf);
2463 pdata->fp = fp;
2464 pdata->error = FALSE;
2465 g_hash_table_foreach(mimeinfo->dispositionparameters, write_parameters, pdata);
2466 if (pdata->error == TRUE) {
2467 g_free(pdata);
2468 return -1;
2470 g_free(pdata);
2471 TRY(fprintf(fp, "\n") >= 0);
2474 TRY(fprintf(fp, "\n") >= 0);
2476 return 0;
2479 static gint procmime_write_message_rfc822(MimeInfo *mimeinfo, FILE *fp)
2481 FILE *infp;
2482 GNode *childnode;
2483 MimeInfo *child;
2484 gchar buf[BUFFSIZE];
2485 gboolean skip = FALSE;
2486 size_t len;
2488 debug_print("procmime_write_message_rfc822\n");
2490 /* write header */
2491 switch (mimeinfo->content) {
2492 case MIMECONTENT_FILE:
2493 if ((infp = claws_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2494 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
2495 return -1;
2497 if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
2498 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
2499 claws_fclose(infp);
2500 return -1;
2502 while (claws_fgets(buf, sizeof(buf), infp) == buf) {
2503 strcrchomp(buf);
2504 if (buf[0] == '\n' && buf[1] == '\0')
2505 break;
2506 if (skip && (buf[0] == ' ' || buf[0] == '\t'))
2507 continue;
2508 if (g_ascii_strncasecmp(buf, "MIME-Version:", 13) == 0 ||
2509 g_ascii_strncasecmp(buf, "Content-Type:", 13) == 0 ||
2510 g_ascii_strncasecmp(buf, "Content-Transfer-Encoding:", 26) == 0 ||
2511 g_ascii_strncasecmp(buf, "Content-Description:", 20) == 0 ||
2512 g_ascii_strncasecmp(buf, "Content-ID:", 11) == 0 ||
2513 g_ascii_strncasecmp(buf, "Content-Location:", 17) == 0 ||
2514 g_ascii_strncasecmp(buf, "Content-Disposition:", 20) == 0) {
2515 skip = TRUE;
2516 continue;
2518 len = strlen(buf);
2519 if (claws_fwrite(buf, sizeof(gchar), len, fp) < len) {
2520 g_warning("failed to dump %"G_GSIZE_FORMAT" bytes from file", len);
2521 claws_fclose(infp);
2522 return -1;
2524 skip = FALSE;
2526 claws_fclose(infp);
2527 break;
2529 case MIMECONTENT_MEM:
2530 len = strlen(mimeinfo->data.mem);
2531 if (claws_fwrite(mimeinfo->data.mem, sizeof(gchar), len, fp) < len) {
2532 g_warning("failed to dump %"G_GSIZE_FORMAT" bytes from mem", len);
2533 return -1;
2535 break;
2537 default:
2538 break;
2541 childnode = mimeinfo->node->children;
2542 if (childnode == NULL)
2543 return -1;
2545 child = (MimeInfo *) childnode->data;
2546 if (fprintf(fp, "MIME-Version: 1.0\n") < 0) {
2547 g_warning("failed to write mime version");
2548 return -1;
2550 if (procmime_write_mime_header(child, fp) < 0)
2551 return -1;
2552 return procmime_write_mimeinfo(child, fp);
2555 static gint procmime_write_multipart(MimeInfo *mimeinfo, FILE *fp)
2557 FILE *infp;
2558 GNode *childnode;
2559 gchar *boundary, *str, *str2;
2560 gchar buf[BUFFSIZE];
2561 gboolean firstboundary;
2562 size_t len;
2564 debug_print("procmime_write_multipart\n");
2566 boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
2568 switch (mimeinfo->content) {
2569 case MIMECONTENT_FILE:
2570 if ((infp = claws_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2571 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
2572 return -1;
2574 if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
2575 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
2576 claws_fclose(infp);
2577 return -1;
2579 while (claws_fgets(buf, sizeof(buf), infp) == buf) {
2580 if (IS_BOUNDARY(buf, boundary, strlen(boundary)))
2581 break;
2582 len = strlen(buf);
2583 if (claws_fwrite(buf, sizeof(gchar), len, fp) < len) {
2584 g_warning("failed to write %"G_GSIZE_FORMAT, len);
2585 claws_fclose(infp);
2586 return -1;
2589 claws_fclose(infp);
2590 break;
2592 case MIMECONTENT_MEM:
2593 str = g_strdup(mimeinfo->data.mem);
2594 if (((str2 = strstr(str, boundary)) != NULL) && ((str2 - str) >= 2) &&
2595 (*(str2 - 1) == '-') && (*(str2 - 2) == '-'))
2596 *(str2 - 2) = '\0';
2597 len = strlen(str);
2598 if (claws_fwrite(str, sizeof(gchar), len, fp) < len) {
2599 g_warning("failed to write %"G_GSIZE_FORMAT" from mem", len);
2600 g_free(str);
2601 return -1;
2603 g_free(str);
2604 break;
2606 default:
2607 break;
2610 childnode = mimeinfo->node->children;
2611 firstboundary = TRUE;
2612 while (childnode != NULL) {
2613 MimeInfo *child = childnode->data;
2615 if (firstboundary)
2616 firstboundary = FALSE;
2617 else
2618 TRY(fprintf(fp, "\n") >= 0);
2620 TRY(fprintf(fp, "--%s\n", boundary) >= 0);
2622 if (procmime_write_mime_header(child, fp) < 0)
2623 return -1;
2624 if (procmime_write_mimeinfo(child, fp) < 0)
2625 return -1;
2627 childnode = g_node_next_sibling(childnode);
2629 TRY(fprintf(fp, "\n--%s--\n", boundary) >= 0);
2631 return 0;
2634 gint procmime_write_mimeinfo(MimeInfo *mimeinfo, FILE *fp)
2636 FILE *infp;
2637 size_t len;
2638 debug_print("procmime_write_mimeinfo\n");
2640 if (G_NODE_IS_LEAF(mimeinfo->node)) {
2641 switch (mimeinfo->content) {
2642 case MIMECONTENT_FILE:
2643 if ((infp = claws_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2644 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
2645 return -1;
2647 copy_file_part_to_fp(infp, mimeinfo->offset, mimeinfo->length, fp);
2648 claws_fclose(infp);
2649 return 0;
2651 case MIMECONTENT_MEM:
2652 len = strlen(mimeinfo->data.mem);
2653 if (claws_fwrite(mimeinfo->data.mem, sizeof(gchar), len, fp) < len)
2654 return -1;
2655 return 0;
2657 default:
2658 return 0;
2660 } else {
2661 /* Call writer for mime type */
2662 switch (mimeinfo->type) {
2663 case MIMETYPE_MESSAGE:
2664 if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
2665 return procmime_write_message_rfc822(mimeinfo, fp);
2667 break;
2669 case MIMETYPE_MULTIPART:
2670 return procmime_write_multipart(mimeinfo, fp);
2672 default:
2673 break;
2676 return -1;
2679 return 0;
2682 gchar *procmime_get_part_file_name(MimeInfo *mimeinfo)
2684 gchar *base;
2686 if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
2687 base = g_strdup("mimetmp.html");
2688 else {
2689 const gchar *basetmp;
2690 gchar *basename;
2692 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
2693 if (basetmp == NULL)
2694 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
2695 if (basetmp == NULL)
2696 basetmp = "mimetmp";
2697 basename = g_path_get_basename(basetmp);
2698 if (*basename == '\0') {
2699 g_free(basename);
2700 basename = g_strdup("mimetmp");
2702 base = conv_filename_from_utf8(basename);
2703 g_free(basename);
2704 subst_for_shellsafe_filename(base);
2707 return base;
2710 void *procmime_get_part_as_string(MimeInfo *mimeinfo,
2711 gboolean null_terminate)
2713 FILE *infp;
2714 gchar *data;
2715 gint length, readlength;
2717 cm_return_val_if_fail(mimeinfo != NULL, NULL);
2719 if (mimeinfo->encoding_type != ENC_BINARY &&
2720 !procmime_decode_content(mimeinfo))
2721 return NULL;
2723 if (mimeinfo->content == MIMECONTENT_MEM)
2724 return g_strdup(mimeinfo->data.mem);
2726 if ((infp = claws_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2727 FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
2728 return NULL;
2731 if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
2732 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
2733 claws_fclose(infp);
2734 return NULL;
2737 length = mimeinfo->length;
2739 data = g_malloc(null_terminate ? length + 1 : length);
2740 if (data == NULL) {
2741 g_warning("could not allocate %d bytes for procmime_get_part_as_string",
2742 (null_terminate ? length + 1 : length));
2743 claws_fclose(infp);
2744 return NULL;
2747 readlength = claws_fread(data, length, 1, infp);
2748 if (readlength <= 0) {
2749 FILE_OP_ERROR(mimeinfo->data.filename, "fread");
2750 g_free(data);
2751 claws_fclose(infp);
2752 return NULL;
2755 claws_fclose(infp);
2757 if (null_terminate)
2758 data[length] = '\0';
2760 return data;
2763 /* Returns an open GInputStream. The caller should just
2764 * read mimeinfo->length bytes from it and then release it. */
2765 GInputStream *procmime_get_part_as_inputstream(MimeInfo *mimeinfo)
2767 cm_return_val_if_fail(mimeinfo != NULL, NULL);
2769 if (mimeinfo->encoding_type != ENC_BINARY &&
2770 !procmime_decode_content(mimeinfo)) {
2771 g_warning("could not decode part");
2772 return NULL;
2774 if (mimeinfo->content == MIMECONTENT_MEM) {
2775 /* NULL for destroy func, since we're not copying
2776 * the data for the stream. */
2777 return g_memory_input_stream_new_from_data(
2778 mimeinfo->data.mem,
2779 mimeinfo->length, NULL);
2780 } else {
2781 return g_memory_input_stream_new_from_data(
2782 procmime_get_part_as_string(mimeinfo, FALSE),
2783 mimeinfo->length, g_free);
2787 GdkPixbuf *procmime_get_part_as_pixbuf(MimeInfo *mimeinfo, GError **error)
2789 GdkPixbuf *pixbuf;
2790 GInputStream *stream;
2792 if (error)
2793 *error = NULL;
2795 stream = procmime_get_part_as_inputstream(mimeinfo);
2796 if (stream == NULL) {
2797 if (error)
2798 *error = g_error_new_literal(G_FILE_ERROR, -1, _("Could not decode part"));
2799 return NULL;
2802 pixbuf = gdk_pixbuf_new_from_stream(stream, NULL, error);
2803 g_object_unref(stream);
2805 if (error && *error != NULL)
2806 return NULL;
2808 return pixbuf;