Refactor colors handling with more arrays
[claws.git] / src / procmime.c
blob44e546c3a930f3e2fef8b5552fdd933041a5030d
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 #define _GNU_SOURCE
25 #include <stdio.h>
27 #include "defs.h"
29 #include <glib.h>
30 #include <glib/gi18n.h>
31 #include <string.h>
32 #if HAVE_LOCALE_H
33 # include <locale.h>
34 #endif
35 #include <ctype.h>
36 #include <sys/types.h>
37 #include <sys/stat.h>
38 #include <unistd.h>
39 #include <errno.h>
41 #include "procmime.h"
42 #include "procheader.h"
43 #include "quoted-printable.h"
44 #include "uuencode.h"
45 #include "unmime.h"
46 #include "html.h"
47 #include "enriched.h"
48 #include "codeconv.h"
49 #include "utils.h"
50 #include "prefs_common.h"
51 #include "prefs_gtk.h"
52 #include "alertpanel.h"
53 #include "timing.h"
54 #include "privacy.h"
56 static GHashTable *procmime_get_mime_type_table (void);
57 static MimeInfo *procmime_scan_file_short(const gchar *filename);
58 static MimeInfo *procmime_scan_queue_file_short(const gchar *filename);
59 static MimeInfo *procmime_scan_queue_file_full(const gchar *filename, gboolean short_scan);
61 MimeInfo *procmime_mimeinfo_new(void)
63 MimeInfo *mimeinfo;
65 mimeinfo = g_new0(MimeInfo, 1);
66 mimeinfo->content = MIMECONTENT_EMPTY;
67 mimeinfo->data.filename = NULL;
69 mimeinfo->type = MIMETYPE_UNKNOWN;
70 mimeinfo->encoding_type = ENC_UNKNOWN;
71 mimeinfo->typeparameters = g_hash_table_new(g_str_hash, g_str_equal);
73 mimeinfo->disposition = DISPOSITIONTYPE_UNKNOWN;
74 mimeinfo->dispositionparameters
75 = g_hash_table_new(g_str_hash, g_str_equal);
77 mimeinfo->node = g_node_new(mimeinfo);
79 return mimeinfo;
82 static gboolean procmime_mimeinfo_parameters_destroy(gpointer key, gpointer value, gpointer user_data)
84 g_free(key);
85 g_free(value);
87 return TRUE;
90 static gchar *forced_charset = NULL;
92 void procmime_force_charset(const gchar *str)
94 g_free(forced_charset);
95 forced_charset = NULL;
96 if (str)
97 forced_charset = g_strdup(str);
100 static EncodingType forced_encoding = 0;
102 void procmime_force_encoding(EncodingType encoding)
104 forced_encoding = encoding;
107 static gboolean free_func(GNode *node, gpointer data)
109 MimeInfo *mimeinfo = (MimeInfo *) node->data;
111 switch (mimeinfo->content) {
112 case MIMECONTENT_FILE:
113 if (mimeinfo->tmp)
114 claws_unlink(mimeinfo->data.filename);
115 g_free(mimeinfo->data.filename);
116 break;
118 case MIMECONTENT_MEM:
119 if (mimeinfo->tmp)
120 g_free(mimeinfo->data.mem);
121 default:
122 break;
125 g_free(mimeinfo->subtype);
126 g_free(mimeinfo->description);
127 g_free(mimeinfo->id);
128 g_free(mimeinfo->location);
130 g_hash_table_foreach_remove(mimeinfo->typeparameters,
131 procmime_mimeinfo_parameters_destroy, NULL);
132 g_hash_table_destroy(mimeinfo->typeparameters);
133 g_hash_table_foreach_remove(mimeinfo->dispositionparameters,
134 procmime_mimeinfo_parameters_destroy, NULL);
135 g_hash_table_destroy(mimeinfo->dispositionparameters);
137 if (mimeinfo->privacy)
138 privacy_free_privacydata(mimeinfo->privacy);
140 return FALSE;
143 void procmime_mimeinfo_free_all(MimeInfo **mimeinfo_ptr)
145 MimeInfo *mimeinfo = *mimeinfo_ptr;
146 GNode *node;
148 if (!mimeinfo)
149 return;
151 node = mimeinfo->node;
152 g_node_traverse(node, G_IN_ORDER, G_TRAVERSE_ALL, -1, free_func, NULL);
154 g_node_destroy(node);
156 g_free(mimeinfo);
157 *mimeinfo_ptr = NULL;
160 MimeInfo *procmime_mimeinfo_parent(MimeInfo *mimeinfo)
162 cm_return_val_if_fail(mimeinfo != NULL, NULL);
163 cm_return_val_if_fail(mimeinfo->node != NULL, NULL);
165 if (mimeinfo->node->parent == NULL)
166 return NULL;
167 return (MimeInfo *) mimeinfo->node->parent->data;
170 MimeInfo *procmime_mimeinfo_next(MimeInfo *mimeinfo)
172 cm_return_val_if_fail(mimeinfo != NULL, NULL);
173 cm_return_val_if_fail(mimeinfo->node != NULL, NULL);
175 if (mimeinfo->node->children)
176 return (MimeInfo *) mimeinfo->node->children->data;
177 if (mimeinfo->node->next)
178 return (MimeInfo *) mimeinfo->node->next->data;
180 if (mimeinfo->node->parent == NULL)
181 return NULL;
183 while (mimeinfo->node->parent != NULL) {
184 mimeinfo = (MimeInfo *) mimeinfo->node->parent->data;
185 if (mimeinfo->node->next)
186 return (MimeInfo *) mimeinfo->node->next->data;
189 return NULL;
192 MimeInfo *procmime_scan_message(MsgInfo *msginfo)
194 gchar *filename;
195 MimeInfo *mimeinfo;
197 filename = procmsg_get_message_file_path(msginfo);
198 if (!filename || !is_file_exist(filename)) {
199 g_free(filename);
200 return NULL;
203 if (!folder_has_parent_of_type(msginfo->folder, F_QUEUE) &&
204 !folder_has_parent_of_type(msginfo->folder, F_DRAFT))
205 mimeinfo = procmime_scan_file(filename);
206 else
207 mimeinfo = procmime_scan_queue_file(filename);
208 g_free(filename);
210 return mimeinfo;
213 MimeInfo *procmime_scan_message_short(MsgInfo *msginfo)
215 gchar *filename;
216 MimeInfo *mimeinfo;
218 filename = procmsg_get_message_file_path(msginfo);
219 if (!filename || !is_file_exist(filename)) {
220 g_free(filename);
221 return NULL;
224 if (!folder_has_parent_of_type(msginfo->folder, F_QUEUE) &&
225 !folder_has_parent_of_type(msginfo->folder, F_DRAFT))
226 mimeinfo = procmime_scan_file_short(filename);
227 else
228 mimeinfo = procmime_scan_queue_file_short(filename);
229 g_free(filename);
231 return mimeinfo;
234 enum
236 H_CONTENT_TRANSFER_ENCODING = 0,
237 H_CONTENT_TYPE = 1,
238 H_CONTENT_DISPOSITION = 2,
239 H_CONTENT_DESCRIPTION = 3,
240 H_SUBJECT = 4
243 const gchar *procmime_mimeinfo_get_parameter(MimeInfo *mimeinfo, const gchar *name)
245 const gchar *value;
247 cm_return_val_if_fail(mimeinfo != NULL, NULL);
248 cm_return_val_if_fail(name != NULL, NULL);
250 value = g_hash_table_lookup(mimeinfo->dispositionparameters, name);
251 if (value == NULL)
252 value = g_hash_table_lookup(mimeinfo->typeparameters, name);
254 return value;
257 #ifdef HAVE_FGETS_UNLOCKED
258 #define SC_FGETS fgets_unlocked
259 #define SC_FPUTS fputs_unlocked
260 #define SC_FPUTC fputc_unlocked
261 #define SC_FREAD fread_unlocked
262 #define SC_FWRITE fwrite_unlocked
263 #define SC_FEOF feof_unlocked
264 #define SC_FERROR ferror_unlocked
266 static FILE *procmime_fopen(const gchar *file, const gchar *mode)
268 FILE *fp = g_fopen(file, mode);
269 if (!fp)
270 return NULL;
271 flockfile(fp);
272 return fp;
274 static int procmime_fclose(FILE *fp)
276 funlockfile(fp);
277 return fclose(fp);
279 #else
280 #define SC_FGETS fgets
281 #define SC_FPUTS fputs
282 #define SC_FPUTC fputc
283 #define SC_FREAD fread
284 #define SC_FWRITE fwrite
285 #define SC_FEOF feof
286 #define SC_FERROR ferror
287 #define procmime_fopen g_fopen
288 #define procmime_fclose fclose
289 #endif
291 #define FLUSH_LASTLINE() { \
292 if (*lastline != '\0') { \
293 gint llen = 0; \
294 strretchomp(lastline); \
295 llen = strlen(lastline); \
296 if (lastline[llen-1] == ' ' && strcmp(lastline,"-- ")) { \
297 /* this is flowed */ \
298 if (delsp) \
299 lastline[llen-1] = '\0'; \
300 if (SC_FPUTS(lastline, outfp) == EOF) \
301 err = TRUE; \
302 } else { \
303 if (SC_FPUTS(lastline, outfp) == EOF) \
304 err = TRUE; \
305 if (SC_FPUTS("\n", outfp) == EOF) \
306 err = TRUE; \
309 strcpy(lastline, buf); \
312 gboolean procmime_decode_content(MimeInfo *mimeinfo)
314 gchar buf[BUFFSIZE];
315 gint readend;
316 gchar *tmpfilename;
317 FILE *outfp, *infp;
318 GStatBuf statbuf;
319 gboolean tmp_file = FALSE;
320 gboolean flowed = FALSE;
321 gboolean delsp = FALSE;
322 gboolean err = FALSE;
323 gint state = 0;
324 guint save = 0;
326 cm_return_val_if_fail(mimeinfo != NULL, FALSE);
328 EncodingType encoding = forced_encoding
329 ? forced_encoding
330 : mimeinfo->encoding_type;
331 gchar lastline[BUFFSIZE];
332 memset(lastline, 0, BUFFSIZE);
334 if (prefs_common.respect_flowed_format &&
335 mimeinfo->type == MIMETYPE_TEXT &&
336 !strcasecmp(mimeinfo->subtype, "plain")) {
337 if (procmime_mimeinfo_get_parameter(mimeinfo, "format") != NULL &&
338 !strcasecmp(procmime_mimeinfo_get_parameter(mimeinfo, "format"),"flowed"))
339 flowed = TRUE;
340 if (flowed &&
341 procmime_mimeinfo_get_parameter(mimeinfo, "delsp") != NULL &&
342 !strcasecmp(procmime_mimeinfo_get_parameter(mimeinfo, "delsp"),"yes"))
343 delsp = TRUE;
346 if (!flowed && (
347 encoding == ENC_UNKNOWN ||
348 encoding == ENC_BINARY ||
349 encoding == ENC_7BIT ||
350 encoding == ENC_8BIT
352 return TRUE;
354 if (mimeinfo->type == MIMETYPE_MULTIPART || mimeinfo->type == MIMETYPE_MESSAGE)
355 return TRUE;
357 if (mimeinfo->data.filename == NULL)
358 return FALSE;
360 infp = procmime_fopen(mimeinfo->data.filename, "rb");
361 if (!infp) {
362 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
363 return FALSE;
365 if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
366 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
367 procmime_fclose(infp);
368 return FALSE;
371 outfp = get_tmpfile_in_dir(get_mime_tmp_dir(), &tmpfilename);
372 if (!outfp) {
373 perror("tmpfile");
374 procmime_fclose(infp);
375 return FALSE;
377 #ifdef HAVE_FGETS_UNLOCKED
378 flockfile(outfp);
379 #endif
380 tmp_file = TRUE;
381 readend = mimeinfo->offset + mimeinfo->length;
383 if (encoding == ENC_QUOTED_PRINTABLE) {
384 while ((ftell(infp) < readend) && (SC_FGETS(buf, sizeof(buf), infp) != NULL)) {
385 gint len;
386 len = qp_decode_line(buf);
387 buf[len]='\0';
388 if (!flowed) {
389 if (SC_FWRITE(buf, 1, len, outfp) < len)
390 err = TRUE;
391 } else {
392 FLUSH_LASTLINE();
395 if (flowed)
396 FLUSH_LASTLINE();
397 } else if (encoding == ENC_BASE64) {
398 gchar outbuf[BUFFSIZE];
399 gint len, inlen, inread;
400 gboolean got_error = FALSE;
401 gboolean uncanonicalize = FALSE;
402 FILE *tmpfp = NULL;
403 gboolean null_bytes = FALSE;
404 gboolean starting = TRUE;
406 if (mimeinfo->type == MIMETYPE_TEXT ||
407 mimeinfo->type == MIMETYPE_MESSAGE) {
408 uncanonicalize = TRUE;
409 tmpfp = my_tmpfile();
410 if (!tmpfp) {
411 perror("my_tmpfile");
412 if (tmp_file)
413 procmime_fclose(outfp);
414 procmime_fclose(infp);
415 return FALSE;
417 #ifdef HAVE_FGETS_UNLOCKED
418 flockfile(tmpfp);
419 #endif
420 } else
421 tmpfp = outfp;
423 while ((inlen = MIN(readend - ftell(infp), sizeof(buf))) > 0 && !err) {
424 inread = SC_FREAD(buf, 1, inlen, infp);
425 len = g_base64_decode_step(buf, inlen, outbuf, &state, &save);
426 if (uncanonicalize == TRUE && strlen(outbuf) < len && starting) {
427 uncanonicalize = FALSE;
428 null_bytes = TRUE;
430 starting = FALSE;
431 if (((inread != inlen) || len < 0) && !got_error) {
432 g_warning("Bad BASE64 content.");
433 if (SC_FWRITE(_("[Error decoding BASE64]\n"),
434 sizeof(gchar),
435 strlen(_("[Error decoding BASE64]\n")),
436 tmpfp) < strlen(_("[Error decoding BASE64]\n")))
437 g_warning("error decoding BASE64");
438 got_error = TRUE;
439 continue;
440 } else if (len >= 0) {
441 /* print out the error message only once
442 * per block */
443 if (null_bytes) {
444 /* we won't uncanonicalize, output to outfp directly */
445 if (SC_FWRITE(outbuf, sizeof(gchar), len, outfp) < len)
446 err = TRUE;
447 } else {
448 if (SC_FWRITE(outbuf, sizeof(gchar), len, tmpfp) < len)
449 err = TRUE;
451 got_error = FALSE;
455 if (uncanonicalize) {
456 rewind(tmpfp);
457 while (SC_FGETS(buf, sizeof(buf), tmpfp) != NULL) {
458 strcrchomp(buf);
459 if (SC_FPUTS(buf, outfp) == EOF)
460 err = TRUE;
463 if (tmpfp != outfp)
464 procmime_fclose(tmpfp);
465 } else if (encoding == ENC_X_UUENCODE) {
466 gchar outbuf[BUFFSIZE];
467 gint len;
468 gboolean flag = FALSE;
470 while ((ftell(infp) < readend) && (SC_FGETS(buf, sizeof(buf), infp) != NULL)) {
471 if (!flag && strncmp(buf,"begin ", 6)) continue;
473 if (flag) {
474 len = fromuutobits(outbuf, buf);
475 if (len <= 0) {
476 if (len < 0)
477 g_warning("Bad UUENCODE content (%d)", len);
478 break;
480 if (SC_FWRITE(outbuf, sizeof(gchar), len, outfp) < len)
481 err = TRUE;
482 } else
483 flag = TRUE;
485 } else {
486 while ((ftell(infp) < readend) && (SC_FGETS(buf, sizeof(buf), infp) != NULL)) {
487 if (!flowed) {
488 if (SC_FPUTS(buf, outfp) == EOF)
489 err = TRUE;
490 } else {
491 FLUSH_LASTLINE();
494 if (flowed)
495 FLUSH_LASTLINE();
496 if (err == TRUE)
497 g_warning("write error");
500 procmime_fclose(outfp);
501 procmime_fclose(infp);
503 if (err == TRUE) {
504 return FALSE;
507 if (g_stat(tmpfilename, &statbuf) < 0) {
508 FILE_OP_ERROR(tmpfilename, "stat");
509 return FALSE;
512 if (mimeinfo->tmp)
513 claws_unlink(mimeinfo->data.filename);
514 g_free(mimeinfo->data.filename);
515 mimeinfo->data.filename = tmpfilename;
516 mimeinfo->tmp = TRUE;
517 mimeinfo->offset = 0;
518 mimeinfo->length = statbuf.st_size;
519 mimeinfo->encoding_type = ENC_BINARY;
521 return TRUE;
524 #define B64_LINE_SIZE 57
525 #define B64_BUFFSIZE 77
527 gboolean procmime_encode_content(MimeInfo *mimeinfo, EncodingType encoding)
529 FILE *infp = NULL, *outfp;
530 gint len;
531 gchar *tmpfilename;
532 GStatBuf statbuf;
533 gboolean err = FALSE;
535 if (mimeinfo->content == MIMECONTENT_EMPTY)
536 return TRUE;
538 if (mimeinfo->encoding_type != ENC_UNKNOWN &&
539 mimeinfo->encoding_type != ENC_BINARY &&
540 mimeinfo->encoding_type != ENC_7BIT &&
541 mimeinfo->encoding_type != ENC_8BIT)
542 if(!procmime_decode_content(mimeinfo))
543 return FALSE;
545 outfp = get_tmpfile_in_dir(get_mime_tmp_dir(), &tmpfilename);
546 if (!outfp) {
547 perror("tmpfile");
548 return FALSE;
550 #ifdef HAVE_FGETS_UNLOCKED
551 flockfile(outfp);
552 #endif
554 if (mimeinfo->content == MIMECONTENT_FILE && mimeinfo->data.filename) {
555 if ((infp = procmime_fopen(mimeinfo->data.filename, "rb")) == NULL) {
556 g_warning("Can't open file %s", mimeinfo->data.filename);
557 procmime_fclose(outfp);
558 return FALSE;
560 } else if (mimeinfo->content == MIMECONTENT_MEM) {
561 infp = str_open_as_stream(mimeinfo->data.mem);
562 if (infp == NULL) {
563 procmime_fclose(outfp);
564 return FALSE;
566 #ifdef HAVE_FGETS_UNLOCKED
567 flockfile(infp);
568 #endif
569 } else {
570 procmime_fclose(outfp);
571 g_warning("Unknown mimeinfo");
572 return FALSE;
575 if (encoding == ENC_BASE64) {
576 gchar inbuf[B64_LINE_SIZE], *out;
577 FILE *tmp_fp = infp;
578 gchar *tmp_file = NULL;
580 if (mimeinfo->type == MIMETYPE_TEXT ||
581 mimeinfo->type == MIMETYPE_MESSAGE) {
582 if (mimeinfo->content == MIMECONTENT_FILE) {
583 tmp_file = get_tmp_file();
584 if (canonicalize_file(mimeinfo->data.filename, tmp_file) < 0) {
585 g_free(tmp_file);
586 procmime_fclose(infp);
587 procmime_fclose(outfp);
588 return FALSE;
590 if ((tmp_fp = procmime_fopen(tmp_file, "rb")) == NULL) {
591 FILE_OP_ERROR(tmp_file, "fopen");
592 claws_unlink(tmp_file);
593 g_free(tmp_file);
594 procmime_fclose(infp);
595 procmime_fclose(outfp);
596 return FALSE;
598 } else {
599 gchar *out = canonicalize_str(mimeinfo->data.mem);
600 procmime_fclose(infp);
601 infp = str_open_as_stream(out);
602 tmp_fp = infp;
603 g_free(out);
604 if (infp == NULL) {
605 procmime_fclose(outfp);
606 return FALSE;
608 #ifdef HAVE_FGETS_UNLOCKED
609 flockfile(infp);
610 #endif
614 while ((len = SC_FREAD(inbuf, sizeof(gchar),
615 B64_LINE_SIZE, tmp_fp))
616 == B64_LINE_SIZE) {
617 out = g_base64_encode(inbuf, B64_LINE_SIZE);
618 if (SC_FPUTS(out, outfp) == EOF)
619 err = TRUE;
620 g_free(out);
621 if (SC_FPUTC('\n', outfp) == EOF)
622 err = TRUE;
624 if (len > 0 && SC_FEOF(tmp_fp)) {
625 out = g_base64_encode(inbuf, len);
626 if (SC_FPUTS(out, outfp) == EOF)
627 err = TRUE;
628 g_free(out);
629 if (SC_FPUTC('\n', outfp) == EOF)
630 err = TRUE;
633 if (tmp_file) {
634 procmime_fclose(tmp_fp);
635 claws_unlink(tmp_file);
636 g_free(tmp_file);
638 } else if (encoding == ENC_QUOTED_PRINTABLE) {
639 gchar inbuf[BUFFSIZE], outbuf[BUFFSIZE * 4];
641 while (SC_FGETS(inbuf, sizeof(inbuf), infp) != NULL) {
642 qp_encode_line(outbuf, inbuf);
644 if (!strncmp("From ", outbuf, sizeof("From ")-1)) {
645 gchar *tmpbuf = outbuf;
647 tmpbuf += sizeof("From ")-1;
649 if (SC_FPUTS("=46rom ", outfp) == EOF)
650 err = TRUE;
651 if (SC_FPUTS(tmpbuf, outfp) == EOF)
652 err = TRUE;
653 } else {
654 if (SC_FPUTS(outbuf, outfp) == EOF)
655 err = TRUE;
658 } else {
659 gchar buf[BUFFSIZE];
661 while (SC_FGETS(buf, sizeof(buf), infp) != NULL) {
662 strcrchomp(buf);
663 if (SC_FPUTS(buf, outfp) == EOF)
664 err = TRUE;
668 procmime_fclose(outfp);
669 procmime_fclose(infp);
671 if (err == TRUE)
672 return FALSE;
674 if (mimeinfo->content == MIMECONTENT_FILE) {
675 if (mimeinfo->tmp && (mimeinfo->data.filename != NULL))
676 claws_unlink(mimeinfo->data.filename);
677 g_free(mimeinfo->data.filename);
678 } else if (mimeinfo->content == MIMECONTENT_MEM) {
679 if (mimeinfo->tmp && (mimeinfo->data.mem != NULL))
680 g_free(mimeinfo->data.mem);
683 if (g_stat(tmpfilename, &statbuf) < 0) {
684 FILE_OP_ERROR(tmpfilename, "stat");
685 return FALSE;
687 mimeinfo->content = MIMECONTENT_FILE;
688 mimeinfo->data.filename = tmpfilename;
689 mimeinfo->tmp = TRUE;
690 mimeinfo->offset = 0;
691 mimeinfo->length = statbuf.st_size;
692 mimeinfo->encoding_type = encoding;
694 return TRUE;
697 gint procmime_get_part(const gchar *outfile, MimeInfo *mimeinfo)
699 FILE *infp, *outfp;
700 gchar buf[BUFFSIZE];
701 gint restlength, readlength;
702 gint saved_errno = 0;
704 cm_return_val_if_fail(outfile != NULL, -1);
705 cm_return_val_if_fail(mimeinfo != NULL, -1);
707 if (mimeinfo->encoding_type != ENC_BINARY && !procmime_decode_content(mimeinfo))
708 return -EINVAL;
710 if ((infp = procmime_fopen(mimeinfo->data.filename, "rb")) == NULL) {
711 saved_errno = errno;
712 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
713 return -(saved_errno);
715 if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
716 saved_errno = errno;
717 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
718 procmime_fclose(infp);
719 return -(saved_errno);
721 if ((outfp = procmime_fopen(outfile, "wb")) == NULL) {
722 saved_errno = errno;
723 FILE_OP_ERROR(outfile, "fopen");
724 procmime_fclose(infp);
725 return -(saved_errno);
728 restlength = mimeinfo->length;
730 while ((restlength > 0) && ((readlength = SC_FREAD(buf, 1, restlength > BUFFSIZE ? BUFFSIZE : restlength, infp)) > 0)) {
731 if (SC_FWRITE(buf, 1, readlength, outfp) != readlength) {
732 saved_errno = errno;
733 procmime_fclose(infp);
734 procmime_fclose(outfp);
735 return -(saved_errno);
737 restlength -= readlength;
740 procmime_fclose(infp);
741 if (procmime_fclose(outfp) == EOF) {
742 saved_errno = errno;
743 FILE_OP_ERROR(outfile, "fclose");
744 claws_unlink(outfile);
745 return -(saved_errno);
748 return 0;
751 gboolean procmime_scan_text_content(MimeInfo *mimeinfo,
752 gboolean (*scan_callback)(const gchar *str, gpointer cb_data),
753 gpointer cb_data)
755 FILE *tmpfp;
756 const gchar *src_codeset;
757 gboolean conv_fail = FALSE;
758 gchar buf[BUFFSIZE];
759 gchar *str;
760 gchar *tmpfile;
761 gboolean scan_ret = FALSE;
763 cm_return_val_if_fail(mimeinfo != NULL, TRUE);
764 cm_return_val_if_fail(scan_callback != NULL, TRUE);
766 if (!procmime_decode_content(mimeinfo))
767 return TRUE;
769 tmpfile = procmime_get_tmp_file_name(mimeinfo);
770 if (tmpfile == NULL)
771 return TRUE;
773 if (procmime_get_part(tmpfile, mimeinfo) < 0) {
774 g_free(tmpfile);
775 return TRUE;
778 tmpfp = procmime_fopen(tmpfile, "rb");
779 if (tmpfp == NULL) {
780 g_free(tmpfile);
781 return TRUE;
784 src_codeset = forced_charset
785 ? forced_charset :
786 procmime_mimeinfo_get_parameter(mimeinfo, "charset");
788 /* use supersets transparently when possible */
789 if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_ISO_8859_1))
790 src_codeset = CS_WINDOWS_1252;
791 else if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_X_GBK))
792 src_codeset = CS_GB18030;
793 else if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_GBK))
794 src_codeset = CS_GB18030;
795 else if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_GB2312))
796 src_codeset = CS_GB18030;
797 else if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_X_VIET_VPS))
798 src_codeset = CS_WINDOWS_874;
800 if (mimeinfo->type == MIMETYPE_TEXT && !g_ascii_strcasecmp(mimeinfo->subtype, "html")) {
801 SC_HTMLParser *parser;
802 CodeConverter *conv;
804 conv = conv_code_converter_new(src_codeset);
805 parser = sc_html_parser_new(tmpfp, conv);
806 while ((str = sc_html_parse(parser)) != NULL) {
807 if ((scan_ret = scan_callback(str, cb_data)) == TRUE)
808 break;
810 sc_html_parser_destroy(parser);
811 conv_code_converter_destroy(conv);
812 } else if (mimeinfo->type == MIMETYPE_TEXT && !g_ascii_strcasecmp(mimeinfo->subtype, "enriched")) {
813 ERTFParser *parser;
814 CodeConverter *conv;
816 conv = conv_code_converter_new(src_codeset);
817 parser = ertf_parser_new(tmpfp, conv);
818 while ((str = ertf_parse(parser)) != NULL) {
819 if ((scan_ret = scan_callback(str, cb_data)) == TRUE)
820 break;
822 ertf_parser_destroy(parser);
823 conv_code_converter_destroy(conv);
824 } else if (mimeinfo->type == MIMETYPE_TEXT && mimeinfo->disposition != DISPOSITIONTYPE_ATTACHMENT) {
825 while (SC_FGETS(buf, sizeof(buf), tmpfp) != NULL) {
826 str = conv_codeset_strdup(buf, src_codeset, CS_UTF_8);
827 if (str) {
828 if ((scan_ret = scan_callback(str, cb_data)) == TRUE) {
829 g_free(str);
830 break;
832 g_free(str);
833 } else {
834 conv_fail = TRUE;
835 if ((scan_ret = scan_callback(buf, cb_data)) == TRUE)
836 break;
841 if (conv_fail)
842 g_warning("procmime_get_text_content(): Code conversion failed.");
844 procmime_fclose(tmpfp);
845 claws_unlink(tmpfile);
846 g_free(tmpfile);
848 return scan_ret;
851 static gboolean scan_fputs_cb(const gchar *str, gpointer fp)
853 if (SC_FPUTS(str, (FILE *)fp) == EOF)
854 return TRUE;
856 return FALSE;
859 FILE *procmime_get_text_content(MimeInfo *mimeinfo)
861 FILE *outfp;
862 gboolean err;
864 if ((outfp = my_tmpfile()) == NULL) {
865 perror("my_tmpfile");
866 return NULL;
868 #ifdef HAVE_FGETS_UNLOCKED
869 flockfile(outfp);
870 #endif
872 err = procmime_scan_text_content(mimeinfo, scan_fputs_cb, outfp);
874 rewind(outfp);
875 if (err == TRUE) {
876 procmime_fclose(outfp);
877 return NULL;
879 #ifdef HAVE_FGETS_UNLOCKED
880 funlockfile(outfp);
881 #endif
882 return outfp;
886 FILE *procmime_get_binary_content(MimeInfo *mimeinfo)
888 FILE *outfp;
889 gchar *tmpfile;
891 cm_return_val_if_fail(mimeinfo != NULL, NULL);
893 if (!procmime_decode_content(mimeinfo))
894 return NULL;
896 tmpfile = procmime_get_tmp_file_name(mimeinfo);
897 if (tmpfile == NULL)
898 return NULL;
900 if (procmime_get_part(tmpfile, mimeinfo) < 0) {
901 g_free(tmpfile);
902 return NULL;
905 outfp = procmime_fopen(tmpfile, "rb");
906 if (outfp == NULL) {
907 g_unlink(tmpfile);
908 g_free(tmpfile);
909 return NULL;
912 g_unlink(tmpfile);
913 g_free(tmpfile);
915 #ifdef HAVE_FGETS_UNLOCKED
916 funlockfile(outfp);
917 #endif
918 return outfp;
921 /* search the first text part of (multipart) MIME message,
922 decode, convert it and output to outfp. */
923 FILE *procmime_get_first_text_content(MsgInfo *msginfo)
925 FILE *outfp = NULL;
926 MimeInfo *mimeinfo, *partinfo;
927 gboolean empty_ok = FALSE, short_scan = TRUE;
929 cm_return_val_if_fail(msginfo != NULL, NULL);
931 /* first we try to short-scan (for speed), refusing empty parts */
932 scan_again:
933 if (short_scan)
934 mimeinfo = procmime_scan_message_short(msginfo);
935 else
936 mimeinfo = procmime_scan_message(msginfo);
937 if (!mimeinfo) return NULL;
939 partinfo = mimeinfo;
940 while (partinfo && (partinfo->type != MIMETYPE_TEXT ||
941 (partinfo->length == 0 && !empty_ok))) {
942 partinfo = procmime_mimeinfo_next(partinfo);
944 if (partinfo)
945 outfp = procmime_get_text_content(partinfo);
946 else if (!empty_ok && short_scan) {
947 /* if short scan didn't find a non-empty part, rescan
948 * fully for non-empty parts
950 short_scan = FALSE;
951 procmime_mimeinfo_free_all(&mimeinfo);
952 goto scan_again;
953 } else if (!empty_ok && !short_scan) {
954 /* if full scan didn't find a non-empty part, rescan
955 * accepting empty parts
957 empty_ok = TRUE;
958 procmime_mimeinfo_free_all(&mimeinfo);
959 goto scan_again;
961 procmime_mimeinfo_free_all(&mimeinfo);
963 /* outfp already unlocked at this time */
964 return outfp;
968 static gboolean find_encrypted_func(GNode *node, gpointer data)
970 MimeInfo *mimeinfo = (MimeInfo *) node->data;
971 MimeInfo **encinfo = (MimeInfo **) data;
973 if (privacy_mimeinfo_is_encrypted(mimeinfo)) {
974 *encinfo = mimeinfo;
975 return TRUE;
978 return FALSE;
981 static MimeInfo *find_encrypted_part(MimeInfo *rootinfo)
983 MimeInfo *encinfo = NULL;
985 g_node_traverse(rootinfo->node, G_IN_ORDER, G_TRAVERSE_ALL, -1,
986 find_encrypted_func, &encinfo);
988 return encinfo;
991 /* search the first encrypted text part of (multipart) MIME message,
992 decode, convert it and output to outfp. */
993 FILE *procmime_get_first_encrypted_text_content(MsgInfo *msginfo)
995 FILE *outfp = NULL;
996 MimeInfo *mimeinfo, *partinfo, *encinfo;
998 cm_return_val_if_fail(msginfo != NULL, NULL);
1000 mimeinfo = procmime_scan_message(msginfo);
1001 if (!mimeinfo) {
1002 return NULL;
1005 partinfo = mimeinfo;
1006 if ((encinfo = find_encrypted_part(partinfo)) != NULL) {
1007 debug_print("decrypting message part\n");
1008 if (privacy_mimeinfo_decrypt(encinfo) < 0) {
1009 alertpanel_error(_("Couldn't decrypt: %s"),
1010 privacy_get_error());
1011 return NULL;
1014 partinfo = mimeinfo;
1015 while (partinfo && partinfo->type != MIMETYPE_TEXT) {
1016 partinfo = procmime_mimeinfo_next(partinfo);
1017 if (privacy_mimeinfo_is_signed(partinfo))
1018 procmsg_msginfo_set_flags(msginfo, 0, MSG_SIGNED);
1021 if (partinfo)
1022 outfp = procmime_get_text_content(partinfo);
1024 procmime_mimeinfo_free_all(&mimeinfo);
1026 /* outfp already unlocked at this time */
1027 return outfp;
1030 gboolean procmime_msginfo_is_encrypted(MsgInfo *msginfo)
1032 MimeInfo *mimeinfo, *partinfo;
1033 gboolean result = FALSE;
1035 cm_return_val_if_fail(msginfo != NULL, FALSE);
1037 mimeinfo = procmime_scan_message(msginfo);
1038 if (!mimeinfo) {
1039 return FALSE;
1042 partinfo = mimeinfo;
1043 result = (find_encrypted_part(partinfo) != NULL);
1044 procmime_mimeinfo_free_all(&mimeinfo);
1046 return result;
1049 gchar *procmime_get_tmp_file_name(MimeInfo *mimeinfo)
1051 static guint32 id = 0;
1052 gchar *base;
1053 gchar *filename;
1054 gchar f_prefix[10];
1056 cm_return_val_if_fail(mimeinfo != NULL, NULL);
1058 g_snprintf(f_prefix, sizeof(f_prefix), "%08x.", id++);
1060 if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
1061 base = g_strdup("mimetmp.html");
1062 else {
1063 const gchar *basetmp;
1065 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
1066 if (basetmp == NULL)
1067 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
1068 if (basetmp == NULL)
1069 basetmp = "mimetmp";
1070 basetmp = g_path_get_basename(basetmp);
1071 if (*basetmp == '\0')
1072 basetmp = g_strdup("mimetmp");
1073 base = conv_filename_from_utf8(basetmp);
1074 g_free((gchar*)basetmp);
1075 subst_for_shellsafe_filename(base);
1078 filename = g_strconcat(get_mime_tmp_dir(), G_DIR_SEPARATOR_S,
1079 f_prefix, base, NULL);
1081 g_free(base);
1083 return filename;
1086 static GList *mime_type_list = NULL;
1088 gchar *procmime_get_mime_type(const gchar *filename)
1090 const gchar *p;
1091 gchar *ext = NULL;
1092 gchar *base;
1093 #ifndef G_OS_WIN32
1094 static GHashTable *mime_type_table = NULL;
1095 MimeType *mime_type;
1097 if (!mime_type_table) {
1098 mime_type_table = procmime_get_mime_type_table();
1099 if (!mime_type_table) return NULL;
1101 #endif
1103 if (filename == NULL)
1104 return NULL;
1106 base = g_path_get_basename(filename);
1107 if ((p = strrchr(base, '.')) != NULL)
1108 ext = g_utf8_strdown(p + 1, -1);
1109 else
1110 ext = g_utf8_strdown(base, -1);
1111 g_free(base);
1113 #ifndef G_OS_WIN32
1114 mime_type = g_hash_table_lookup(mime_type_table, ext);
1116 if (mime_type) {
1117 gchar *str;
1118 str = g_strconcat(mime_type->type, "/", mime_type->sub_type,
1119 NULL);
1120 debug_print("got type %s for %s\n", str, ext);
1121 g_free(ext);
1122 return str;
1124 g_free(ext);
1125 return NULL;
1126 #else
1127 gchar *str = get_content_type_from_registry_with_ext(ext);
1129 g_free(ext);
1130 return str;
1131 #endif
1134 static guint procmime_str_hash(gconstpointer gptr)
1136 guint hash_result = 0;
1137 const char *str;
1139 for (str = gptr; str && *str; str++) {
1140 if (isupper(*str)) hash_result += (*str + ' ');
1141 else hash_result += *str;
1144 return hash_result;
1147 static gint procmime_str_equal(gconstpointer gptr1, gconstpointer gptr2)
1149 const char *str1 = gptr1;
1150 const char *str2 = gptr2;
1152 return !g_utf8_collate(str1, str2);
1155 static GHashTable *procmime_get_mime_type_table(void)
1157 GHashTable *table = NULL;
1158 GList *cur;
1159 MimeType *mime_type;
1160 gchar **exts;
1162 if (!mime_type_list) {
1163 mime_type_list = procmime_get_mime_type_list();
1164 if (!mime_type_list) return NULL;
1167 table = g_hash_table_new(procmime_str_hash, procmime_str_equal);
1169 for (cur = mime_type_list; cur != NULL; cur = cur->next) {
1170 gint i;
1171 gchar *key;
1173 mime_type = (MimeType *)cur->data;
1175 if (!mime_type->extension) continue;
1177 exts = g_strsplit(mime_type->extension, " ", 16);
1178 for (i = 0; exts[i] != NULL; i++) {
1179 /* Don't overwrite previously inserted extension */
1180 if (!g_hash_table_lookup(table, exts[i])) {
1181 key = g_strdup(exts[i]);
1182 g_hash_table_insert(table, key, mime_type);
1185 g_strfreev(exts);
1188 return table;
1191 GList *procmime_get_mime_type_list(void)
1193 GList *list = NULL;
1194 FILE *fp;
1195 gchar buf[BUFFSIZE];
1196 gchar *p;
1197 gchar *delim;
1198 MimeType *mime_type;
1199 gboolean fp_is_glob_file = TRUE;
1201 if (mime_type_list)
1202 return mime_type_list;
1204 #if defined(__NetBSD__) || defined(__OpenBSD__) || defined(__FreeBSD__)
1205 if ((fp = procmime_fopen(DATAROOTDIR "/mime/globs", "rb")) == NULL)
1206 #else
1207 if ((fp = procmime_fopen("/usr/share/mime/globs", "rb")) == NULL)
1208 #endif
1210 fp_is_glob_file = FALSE;
1211 if ((fp = procmime_fopen("/etc/mime.types", "rb")) == NULL) {
1212 if ((fp = procmime_fopen(SYSCONFDIR "/mime.types", "rb"))
1213 == NULL) {
1214 FILE_OP_ERROR(SYSCONFDIR "/mime.types",
1215 "fopen");
1216 return NULL;
1221 while (SC_FGETS(buf, sizeof(buf), fp) != NULL) {
1222 p = strchr(buf, '#');
1223 if (p) *p = '\0';
1224 g_strstrip(buf);
1226 p = buf;
1228 if (fp_is_glob_file) {
1229 while (*p && !g_ascii_isspace(*p) && (*p!=':')) p++;
1230 } else {
1231 while (*p && !g_ascii_isspace(*p)) p++;
1234 if (*p) {
1235 *p = '\0';
1236 p++;
1238 delim = strchr(buf, '/');
1239 if (delim == NULL) continue;
1240 *delim = '\0';
1242 mime_type = g_new(MimeType, 1);
1243 mime_type->type = g_strdup(buf);
1244 mime_type->sub_type = g_strdup(delim + 1);
1246 if (fp_is_glob_file) {
1247 while (*p && (g_ascii_isspace(*p)||(*p=='*')||(*p=='.'))) p++;
1248 } else {
1249 while (*p && g_ascii_isspace(*p)) p++;
1252 if (*p)
1253 mime_type->extension = g_utf8_strdown(p, -1);
1254 else
1255 mime_type->extension = NULL;
1257 list = g_list_append(list, mime_type);
1260 procmime_fclose(fp);
1262 if (!list)
1263 g_warning("Can't read mime.types");
1265 return list;
1268 EncodingType procmime_get_encoding_for_charset(const gchar *charset)
1270 if (!charset)
1271 return ENC_8BIT;
1272 else if (!g_ascii_strncasecmp(charset, "ISO-2022-", 9) ||
1273 !g_ascii_strcasecmp(charset, "US-ASCII"))
1274 return ENC_7BIT;
1275 else if (!g_ascii_strcasecmp(charset, "ISO-8859-5") ||
1276 !g_ascii_strncasecmp(charset, "KOI8-", 5) ||
1277 !g_ascii_strcasecmp(charset, "X-MAC-CYRILLIC") ||
1278 !g_ascii_strcasecmp(charset, "MAC-CYRILLIC") ||
1279 !g_ascii_strcasecmp(charset, "Windows-1251"))
1280 return ENC_8BIT;
1281 else if (!g_ascii_strncasecmp(charset, "ISO-8859-", 9))
1282 return ENC_QUOTED_PRINTABLE;
1283 else if (!g_ascii_strncasecmp(charset, "UTF-8", 5))
1284 return ENC_QUOTED_PRINTABLE;
1285 else
1286 return ENC_8BIT;
1289 EncodingType procmime_get_encoding_for_text_file(const gchar *file, gboolean *has_binary)
1291 FILE *fp;
1292 guchar buf[BUFFSIZE];
1293 size_t len;
1294 size_t octet_chars = 0;
1295 size_t total_len = 0;
1296 gfloat octet_percentage;
1297 gboolean force_b64 = FALSE;
1299 if ((fp = procmime_fopen(file, "rb")) == NULL) {
1300 FILE_OP_ERROR(file, "fopen");
1301 return ENC_UNKNOWN;
1304 while ((len = SC_FREAD(buf, sizeof(guchar), sizeof(buf), fp)) > 0) {
1305 guchar *p;
1306 gint i;
1308 for (p = buf, i = 0; i < len; ++p, ++i) {
1309 if (*p & 0x80)
1310 ++octet_chars;
1311 if (*p == '\0') {
1312 force_b64 = TRUE;
1313 *has_binary = TRUE;
1316 total_len += len;
1319 procmime_fclose(fp);
1321 if (total_len > 0)
1322 octet_percentage = (gfloat)octet_chars / (gfloat)total_len;
1323 else
1324 octet_percentage = 0.0;
1326 debug_print("procmime_get_encoding_for_text_file(): "
1327 "8bit chars: %zd / %zd (%f%%)\n", octet_chars, total_len,
1328 100.0 * octet_percentage);
1330 if (octet_percentage > 0.20 || force_b64) {
1331 debug_print("using BASE64\n");
1332 return ENC_BASE64;
1333 } else if (octet_chars > 0) {
1334 debug_print("using quoted-printable\n");
1335 return ENC_QUOTED_PRINTABLE;
1336 } else {
1337 debug_print("using 7bit\n");
1338 return ENC_7BIT;
1342 struct EncodingTable
1344 gchar *str;
1345 EncodingType enc_type;
1348 struct EncodingTable encoding_table[] = {
1349 {"7bit", ENC_7BIT},
1350 {"8bit", ENC_8BIT},
1351 {"binary", ENC_BINARY},
1352 {"quoted-printable", ENC_QUOTED_PRINTABLE},
1353 {"base64", ENC_BASE64},
1354 {"x-uuencode", ENC_UNKNOWN},
1355 {NULL, ENC_UNKNOWN},
1358 const gchar *procmime_get_encoding_str(EncodingType encoding)
1360 struct EncodingTable *enc_table;
1362 for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1363 if (enc_table->enc_type == encoding)
1364 return enc_table->str;
1366 return NULL;
1369 /* --- NEW MIME STUFF --- */
1370 struct TypeTable
1372 gchar *str;
1373 MimeMediaType type;
1376 static struct TypeTable mime_type_table[] = {
1377 {"text", MIMETYPE_TEXT},
1378 {"image", MIMETYPE_IMAGE},
1379 {"audio", MIMETYPE_AUDIO},
1380 {"video", MIMETYPE_VIDEO},
1381 {"application", MIMETYPE_APPLICATION},
1382 {"message", MIMETYPE_MESSAGE},
1383 {"multipart", MIMETYPE_MULTIPART},
1384 {NULL, 0},
1387 const gchar *procmime_get_media_type_str(MimeMediaType type)
1389 struct TypeTable *type_table;
1391 for (type_table = mime_type_table; type_table->str != NULL; type_table++) {
1392 if (type_table->type == type)
1393 return type_table->str;
1395 return NULL;
1398 MimeMediaType procmime_get_media_type(const gchar *str)
1400 struct TypeTable *typetablearray;
1402 for (typetablearray = mime_type_table; typetablearray->str != NULL; typetablearray++)
1403 if (g_ascii_strncasecmp(str, typetablearray->str, strlen(typetablearray->str)) == 0)
1404 return typetablearray->type;
1406 return MIMETYPE_UNKNOWN;
1410 *\brief Safe wrapper for content type string.
1412 *\return const gchar * Pointer to content type string.
1414 gchar *procmime_get_content_type_str(MimeMediaType type,
1415 const char *subtype)
1417 const gchar *type_str = NULL;
1419 if (subtype == NULL || !(type_str = procmime_get_media_type_str(type)))
1420 return g_strdup("unknown");
1421 return g_strdup_printf("%s/%s", type_str, subtype);
1424 static int procmime_parse_mimepart(MimeInfo *parent,
1425 gchar *content_type,
1426 gchar *content_encoding,
1427 gchar *content_description,
1428 gchar *content_id,
1429 gchar *content_disposition,
1430 gchar *content_location,
1431 const gchar *original_msgid,
1432 const gchar *disposition_notification_hdr,
1433 const gchar *filename,
1434 guint offset,
1435 guint length,
1436 gboolean short_scan);
1438 static void procmime_parse_message_rfc822(MimeInfo *mimeinfo, gboolean short_scan)
1440 HeaderEntry hentry[] = {{"Content-Type:", NULL, TRUE},
1441 {"Content-Transfer-Encoding:",
1442 NULL, FALSE},
1443 {"Content-Description:",
1444 NULL, TRUE},
1445 {"Content-ID:",
1446 NULL, TRUE},
1447 {"Content-Disposition:",
1448 NULL, TRUE},
1449 {"Content-Location:",
1450 NULL, TRUE},
1451 {"MIME-Version:",
1452 NULL, TRUE},
1453 {"Original-Message-ID:",
1454 NULL, TRUE},
1455 {"Disposition:",
1456 NULL, TRUE},
1457 {NULL, NULL, FALSE}};
1458 guint content_start, i;
1459 FILE *fp;
1460 gchar *tmp;
1461 gint len = 0;
1463 procmime_decode_content(mimeinfo);
1465 fp = procmime_fopen(mimeinfo->data.filename, "rb");
1466 if (fp == NULL) {
1467 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1468 return;
1470 if (fseek(fp, mimeinfo->offset, SEEK_SET) < 0) {
1471 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
1472 procmime_fclose(fp);
1473 return;
1475 procheader_get_header_fields(fp, hentry);
1476 if (hentry[0].body != NULL) {
1477 tmp = conv_unmime_header(hentry[0].body, NULL, FALSE);
1478 g_free(hentry[0].body);
1479 hentry[0].body = tmp;
1481 if (hentry[2].body != NULL) {
1482 tmp = conv_unmime_header(hentry[2].body, NULL, FALSE);
1483 g_free(hentry[2].body);
1484 hentry[2].body = tmp;
1486 if (hentry[4].body != NULL) {
1487 tmp = conv_unmime_header(hentry[4].body, NULL, FALSE);
1488 g_free(hentry[4].body);
1489 hentry[4].body = tmp;
1491 if (hentry[5].body != NULL) {
1492 tmp = conv_unmime_header(hentry[5].body, NULL, FALSE);
1493 g_free(hentry[5].body);
1494 hentry[5].body = tmp;
1496 if (hentry[7].body != NULL) {
1497 tmp = conv_unmime_header(hentry[7].body, NULL, FALSE);
1498 g_free(hentry[7].body);
1499 hentry[7].body = tmp;
1501 if (hentry[8].body != NULL) {
1502 tmp = conv_unmime_header(hentry[8].body, NULL, FALSE);
1503 g_free(hentry[8].body);
1504 hentry[8].body = tmp;
1507 content_start = ftell(fp);
1508 procmime_fclose(fp);
1510 len = mimeinfo->length - (content_start - mimeinfo->offset);
1511 if (len < 0)
1512 len = 0;
1513 procmime_parse_mimepart(mimeinfo,
1514 hentry[0].body, hentry[1].body,
1515 hentry[2].body, hentry[3].body,
1516 hentry[4].body, hentry[5].body,
1517 hentry[7].body, hentry[8].body,
1518 mimeinfo->data.filename, content_start,
1519 len, short_scan);
1521 for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1522 g_free(hentry[i].body);
1523 hentry[i].body = NULL;
1527 static void procmime_parse_disposition_notification(MimeInfo *mimeinfo,
1528 const gchar *original_msgid, const gchar *disposition_notification_hdr,
1529 gboolean short_scan)
1531 HeaderEntry hentry[] = {{"Original-Message-ID:", NULL, TRUE},
1532 {"Disposition:", NULL, TRUE},
1533 {NULL, NULL, FALSE}};
1534 guint i;
1535 FILE *fp;
1536 gchar *orig_msg_id = NULL;
1537 gchar *disp = NULL;
1539 procmime_decode_content(mimeinfo);
1541 debug_print("parse disposition notification\n");
1542 fp = procmime_fopen(mimeinfo->data.filename, "rb");
1543 if (fp == NULL) {
1544 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1545 return;
1547 if (fseek(fp, mimeinfo->offset, SEEK_SET) < 0) {
1548 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
1549 procmime_fclose(fp);
1550 return;
1553 if (original_msgid && disposition_notification_hdr) {
1554 hentry[0].body = g_strdup(original_msgid);
1555 hentry[1].body = g_strdup(disposition_notification_hdr);
1556 } else {
1557 procheader_get_header_fields(fp, hentry);
1560 procmime_fclose(fp);
1562 if (!hentry[0].body || !hentry[1].body) {
1563 debug_print("MsgId %s, Disp %s\n",
1564 hentry[0].body ? hentry[0].body:"(nil)",
1565 hentry[1].body ? hentry[1].body:"(nil)");
1566 goto bail;
1569 orig_msg_id = g_strdup(hentry[0].body);
1570 disp = g_strdup(hentry[1].body);
1572 extract_parenthesis(orig_msg_id, '<', '>');
1573 remove_space(orig_msg_id);
1575 if (strstr(disp, "displayed")) {
1576 /* find sent message, if possible */
1577 MsgInfo *info = NULL;
1578 GList *flist;
1579 debug_print("%s has been displayed.\n", orig_msg_id);
1580 for (flist = folder_get_list(); flist != NULL; flist = g_list_next(flist)) {
1581 FolderItem *outbox = ((Folder *)(flist->data))->outbox;
1582 if (!outbox) {
1583 debug_print("skipping folder with no outbox...\n");
1584 continue;
1586 info = folder_item_get_msginfo_by_msgid(outbox, orig_msg_id);
1587 debug_print("%s %s in %s\n", info?"found":"didn't find", orig_msg_id, outbox->path);
1588 if (info) {
1589 procmsg_msginfo_set_flags(info, MSG_RETRCPT_GOT, 0);
1590 procmsg_msginfo_free(&info);
1594 g_free(orig_msg_id);
1595 g_free(disp);
1596 bail:
1597 for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1598 g_free(hentry[i].body);
1599 hentry[i].body = NULL;
1603 #define GET_HEADERS() { \
1604 procheader_get_header_fields(fp, hentry); \
1605 if (hentry[0].body != NULL) { \
1606 tmp = conv_unmime_header(hentry[0].body, NULL, FALSE); \
1607 g_free(hentry[0].body); \
1608 hentry[0].body = tmp; \
1610 if (hentry[2].body != NULL) { \
1611 tmp = conv_unmime_header(hentry[2].body, NULL, FALSE); \
1612 g_free(hentry[2].body); \
1613 hentry[2].body = tmp; \
1615 if (hentry[4].body != NULL) { \
1616 tmp = conv_unmime_header(hentry[4].body, NULL, FALSE); \
1617 g_free(hentry[4].body); \
1618 hentry[4].body = tmp; \
1620 if (hentry[5].body != NULL) { \
1621 tmp = conv_unmime_header(hentry[5].body, NULL, FALSE); \
1622 g_free(hentry[5].body); \
1623 hentry[5].body = tmp; \
1625 if (hentry[6].body != NULL) { \
1626 tmp = conv_unmime_header(hentry[6].body, NULL, FALSE); \
1627 g_free(hentry[6].body); \
1628 hentry[6].body = tmp; \
1630 if (hentry[7].body != NULL) { \
1631 tmp = conv_unmime_header(hentry[7].body, NULL, FALSE); \
1632 g_free(hentry[7].body); \
1633 hentry[7].body = tmp; \
1637 static void procmime_parse_multipart(MimeInfo *mimeinfo, gboolean short_scan)
1639 HeaderEntry hentry[] = {{"Content-Type:", NULL, TRUE},
1640 {"Content-Transfer-Encoding:",
1641 NULL, FALSE},
1642 {"Content-Description:",
1643 NULL, TRUE},
1644 {"Content-ID:",
1645 NULL, TRUE},
1646 {"Content-Disposition:",
1647 NULL, TRUE},
1648 {"Content-Location:",
1649 NULL, TRUE},
1650 {"Original-Message-ID:",
1651 NULL, TRUE},
1652 {"Disposition:",
1653 NULL, TRUE},
1654 {NULL, NULL, FALSE}};
1655 gchar *tmp;
1656 gchar *boundary;
1657 gint boundary_len = 0, lastoffset = -1, i;
1658 gchar buf[BUFFSIZE];
1659 FILE *fp;
1660 int result = 0;
1661 gboolean start_found = FALSE;
1662 gboolean end_found = FALSE;
1664 boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
1665 if (!boundary)
1666 return;
1667 boundary_len = strlen(boundary);
1669 procmime_decode_content(mimeinfo);
1671 fp = procmime_fopen(mimeinfo->data.filename, "rb");
1672 if (fp == NULL) {
1673 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1674 return;
1677 if (fseek(fp, mimeinfo->offset, SEEK_SET) < 0) {
1678 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
1679 procmime_fclose(fp);
1680 return;
1683 while (SC_FGETS(buf, sizeof(buf), fp) != NULL && result == 0) {
1684 if (ftell(fp) - 1 > (mimeinfo->offset + mimeinfo->length))
1685 break;
1687 if (IS_BOUNDARY(buf, boundary, boundary_len)) {
1688 start_found = TRUE;
1690 if (lastoffset != -1) {
1691 gint len = (ftell(fp) - strlen(buf)) - lastoffset - 1;
1692 if (len < 0)
1693 len = 0;
1694 result = procmime_parse_mimepart(mimeinfo,
1695 hentry[0].body, hentry[1].body,
1696 hentry[2].body, hentry[3].body,
1697 hentry[4].body, hentry[5].body,
1698 hentry[6].body, hentry[7].body,
1699 mimeinfo->data.filename, lastoffset,
1700 len, short_scan);
1701 if (result == 1 && short_scan)
1702 break;
1706 if (buf[2 + boundary_len] == '-' &&
1707 buf[2 + boundary_len + 1] == '-') {
1708 end_found = TRUE;
1709 break;
1711 for (i = 0; i < (sizeof hentry / sizeof hentry[0]) ; i++) {
1712 g_free(hentry[i].body);
1713 hentry[i].body = NULL;
1715 GET_HEADERS();
1716 lastoffset = ftell(fp);
1720 if (start_found && !end_found && lastoffset != -1) {
1721 gint len = (ftell(fp) - strlen(buf)) - lastoffset - 1;
1723 if (len >= 0) {
1724 result = procmime_parse_mimepart(mimeinfo,
1725 hentry[0].body, hentry[1].body,
1726 hentry[2].body, hentry[3].body,
1727 hentry[4].body, hentry[5].body,
1728 hentry[6].body, hentry[7].body,
1729 mimeinfo->data.filename, lastoffset,
1730 len, short_scan);
1732 mimeinfo->broken = TRUE;
1735 for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1736 g_free(hentry[i].body);
1737 hentry[i].body = NULL;
1739 procmime_fclose(fp);
1742 static void parse_parameters(const gchar *parameters, GHashTable *table)
1744 gchar *params, *param, *next;
1745 GSList *convlist = NULL, *concatlist = NULL, *cur;
1747 params = g_strdup(parameters);
1748 param = params;
1749 next = params;
1750 for (; next != NULL; param = next) {
1751 gchar *attribute, *value, *tmp, *down_attr, *orig_down_attr;
1752 gint len;
1753 gboolean convert = FALSE;
1755 next = strchr_with_skip_quote(param, '"', ';');
1756 if (next != NULL) {
1757 next[0] = '\0';
1758 next++;
1761 g_strstrip(param);
1763 attribute = param;
1764 value = strchr(attribute, '=');
1765 if (value == NULL)
1766 continue;
1768 value[0] = '\0';
1769 value++;
1770 while (value[0] != '\0' && value[0] == ' ')
1771 value++;
1773 down_attr = g_utf8_strdown(attribute, -1);
1774 orig_down_attr = down_attr;
1776 len = down_attr ? strlen(down_attr):0;
1777 if (len > 0 && down_attr[len - 1] == '*') {
1778 gchar *srcpos, *dstpos, *endpos;
1780 convert = TRUE;
1781 down_attr[len - 1] = '\0';
1783 srcpos = value;
1784 dstpos = value;
1785 endpos = value + strlen(value);
1786 while (srcpos < endpos) {
1787 if (*srcpos != '%')
1788 *dstpos = *srcpos;
1789 else {
1790 guchar dstvalue;
1792 if (!get_hex_value(&dstvalue, srcpos[1], srcpos[2]))
1793 *dstpos = '?';
1794 else
1795 *dstpos = dstvalue;
1796 srcpos += 2;
1798 srcpos++;
1799 dstpos++;
1801 *dstpos = '\0';
1802 if (value[0] == '"')
1803 extract_quote(value, '"');
1804 } else {
1805 if (value[0] == '"')
1806 extract_quote(value, '"');
1807 else if ((tmp = strchr(value, ' ')) != NULL)
1808 *tmp = '\0';
1811 if (down_attr) {
1812 while (down_attr[0] == ' ')
1813 down_attr++;
1814 while (down_attr[strlen(down_attr)-1] == ' ')
1815 down_attr[strlen(down_attr)-1] = '\0';
1818 while (value[0] != '\0' && value[0] == ' ')
1819 value++;
1820 while (value[strlen(value)-1] == ' ')
1821 value[strlen(value)-1] = '\0';
1823 if (down_attr && strrchr(down_attr, '*') != NULL) {
1824 gchar *tmpattr;
1826 tmpattr = g_strdup(down_attr);
1827 tmp = strrchr(tmpattr, '*');
1828 tmp[0] = '\0';
1830 if ((tmp[1] == '0') && (tmp[2] == '\0') &&
1831 (g_slist_find_custom(concatlist, down_attr, (GCompareFunc)g_strcmp0) == NULL))
1832 concatlist = g_slist_prepend(concatlist, g_strdup(tmpattr));
1834 if (convert && (g_slist_find_custom(convlist, tmpattr, (GCompareFunc)g_strcmp0) == NULL))
1835 convlist = g_slist_prepend(convlist, g_strdup(tmpattr));
1837 g_free(tmpattr);
1838 } else if (convert) {
1839 if (g_slist_find_custom(convlist, down_attr, (GCompareFunc)g_strcmp0) == NULL)
1840 convlist = g_slist_prepend(convlist, g_strdup(down_attr));
1843 if (g_hash_table_lookup(table, down_attr) == NULL)
1844 g_hash_table_insert(table, g_strdup(down_attr), g_strdup(value));
1845 g_free(orig_down_attr);
1848 for (cur = concatlist; cur != NULL; cur = g_slist_next(cur)) {
1849 gchar *attribute, *attrwnum, *partvalue;
1850 gint n = 0;
1851 GString *value;
1853 attribute = (gchar *) cur->data;
1854 value = g_string_sized_new(64);
1856 attrwnum = g_strdup_printf("%s*%d", attribute, n);
1857 while ((partvalue = g_hash_table_lookup(table, attrwnum)) != NULL) {
1858 g_string_append(value, partvalue);
1860 g_hash_table_remove(table, attrwnum);
1861 g_free(attrwnum);
1862 n++;
1863 attrwnum = g_strdup_printf("%s*%d", attribute, n);
1865 g_free(attrwnum);
1867 g_hash_table_insert(table, g_strdup(attribute), g_strdup(value->str));
1868 g_string_free(value, TRUE);
1870 slist_free_strings_full(concatlist);
1872 for (cur = convlist; cur != NULL; cur = g_slist_next(cur)) {
1873 gchar *attribute, *key, *value;
1874 gchar *charset, *lang, *oldvalue, *newvalue;
1876 attribute = (gchar *) cur->data;
1877 if (!g_hash_table_lookup_extended(
1878 table, attribute, (gpointer *)(gchar *) &key, (gpointer *)(gchar *) &value))
1879 continue;
1881 charset = value;
1882 if (charset == NULL)
1883 continue;
1884 lang = strchr(charset, '\'');
1885 if (lang == NULL)
1886 continue;
1887 lang[0] = '\0';
1888 lang++;
1889 oldvalue = strchr(lang, '\'');
1890 if (oldvalue == NULL)
1891 continue;
1892 oldvalue[0] = '\0';
1893 oldvalue++;
1895 newvalue = conv_codeset_strdup(oldvalue, charset, CS_UTF_8);
1897 g_hash_table_remove(table, attribute);
1898 g_free(key);
1899 g_free(value);
1901 g_hash_table_insert(table, g_strdup(attribute), newvalue);
1903 slist_free_strings_full(convlist);
1905 g_free(params);
1908 static void procmime_parse_content_type(const gchar *content_type, MimeInfo *mimeinfo)
1910 cm_return_if_fail(content_type != NULL);
1911 cm_return_if_fail(mimeinfo != NULL);
1913 /* RFC 2045, page 13 says that the mime subtype is MANDATORY;
1914 * if it's not available we use the default Content-Type */
1915 if ((content_type[0] == '\0') || (strchr(content_type, '/') == NULL)) {
1916 mimeinfo->type = MIMETYPE_TEXT;
1917 mimeinfo->subtype = g_strdup("plain");
1918 if (g_hash_table_lookup(mimeinfo->typeparameters,
1919 "charset") == NULL) {
1920 g_hash_table_insert(mimeinfo->typeparameters,
1921 g_strdup("charset"),
1922 g_strdup(
1923 conv_get_locale_charset_str_no_utf8()));
1925 } else {
1926 gchar *type, *subtype, *params;
1928 type = g_strdup(content_type);
1929 subtype = strchr(type, '/') + 1;
1930 *(subtype - 1) = '\0';
1931 if ((params = strchr(subtype, ';')) != NULL) {
1932 params[0] = '\0';
1933 params++;
1936 mimeinfo->type = procmime_get_media_type(type);
1937 mimeinfo->subtype = g_strstrip(g_strdup(subtype));
1939 /* Get mimeinfo->typeparameters */
1940 if (params != NULL)
1941 parse_parameters(params, mimeinfo->typeparameters);
1943 g_free(type);
1947 static void procmime_parse_content_disposition(const gchar *content_disposition, MimeInfo *mimeinfo)
1949 gchar *tmp, *params;
1951 cm_return_if_fail(content_disposition != NULL);
1952 cm_return_if_fail(mimeinfo != NULL);
1954 tmp = g_strdup(content_disposition);
1955 if ((params = strchr(tmp, ';')) != NULL) {
1956 params[0] = '\0';
1957 params++;
1959 g_strstrip(tmp);
1961 if (!g_ascii_strcasecmp(tmp, "inline"))
1962 mimeinfo->disposition = DISPOSITIONTYPE_INLINE;
1963 else if (!g_ascii_strcasecmp(tmp, "attachment"))
1964 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1965 else
1966 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1968 if (params != NULL)
1969 parse_parameters(params, mimeinfo->dispositionparameters);
1971 g_free(tmp);
1975 static void procmime_parse_content_encoding(const gchar *content_encoding, MimeInfo *mimeinfo)
1977 struct EncodingTable *enc_table;
1979 for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1980 if (g_ascii_strcasecmp(enc_table->str, content_encoding) == 0) {
1981 mimeinfo->encoding_type = enc_table->enc_type;
1982 return;
1985 mimeinfo->encoding_type = ENC_UNKNOWN;
1986 return;
1989 static GSList *registered_parsers = NULL;
1991 static MimeParser *procmime_get_mimeparser_for_type(MimeMediaType type, const gchar *sub_type)
1993 GSList *cur;
1994 for (cur = registered_parsers; cur; cur = cur->next) {
1995 MimeParser *parser = (MimeParser *)cur->data;
1996 if (parser->type == type && !strcmp2(parser->sub_type, sub_type))
1997 return parser;
1999 return NULL;
2002 void procmime_mimeparser_register(MimeParser *parser)
2004 if (!procmime_get_mimeparser_for_type(parser->type, parser->sub_type))
2005 registered_parsers = g_slist_append(registered_parsers, parser);
2009 void procmime_mimeparser_unregister(MimeParser *parser)
2011 registered_parsers = g_slist_remove(registered_parsers, parser);
2014 static gboolean procmime_mimeparser_parse(MimeParser *parser, MimeInfo *mimeinfo)
2016 cm_return_val_if_fail(parser->parse != NULL, FALSE);
2017 return parser->parse(parser, mimeinfo);
2020 static int procmime_parse_mimepart(MimeInfo *parent,
2021 gchar *content_type,
2022 gchar *content_encoding,
2023 gchar *content_description,
2024 gchar *content_id,
2025 gchar *content_disposition,
2026 gchar *content_location,
2027 const gchar *original_msgid,
2028 const gchar *disposition_notification_hdr,
2029 const gchar *filename,
2030 guint offset,
2031 guint length,
2032 gboolean short_scan)
2034 MimeInfo *mimeinfo;
2035 MimeParser *parser = NULL;
2036 gboolean parsed = FALSE;
2037 int result = 0;
2039 /* Create MimeInfo */
2040 mimeinfo = procmime_mimeinfo_new();
2041 mimeinfo->content = MIMECONTENT_FILE;
2043 if (parent != NULL) {
2044 if (g_node_depth(parent->node) > 32) {
2045 /* 32 is an arbitrary value
2046 * this avoids DOSsing ourselves
2047 * with enormous messages
2049 procmime_mimeinfo_free_all(&mimeinfo);
2050 return -1;
2052 g_node_append(parent->node, mimeinfo->node);
2054 mimeinfo->data.filename = g_strdup(filename);
2055 mimeinfo->offset = offset;
2056 mimeinfo->length = length;
2058 if (content_type != NULL) {
2059 g_strchomp(content_type);
2060 procmime_parse_content_type(content_type, mimeinfo);
2061 } else {
2062 mimeinfo->type = MIMETYPE_TEXT;
2063 mimeinfo->subtype = g_strdup("plain");
2064 if (g_hash_table_lookup(mimeinfo->typeparameters,
2065 "charset") == NULL) {
2066 g_hash_table_insert(mimeinfo->typeparameters,
2067 g_strdup("charset"),
2068 g_strdup(
2069 conv_get_locale_charset_str_no_utf8()));
2073 if (content_encoding != NULL) {
2074 g_strchomp(content_encoding);
2075 procmime_parse_content_encoding(content_encoding, mimeinfo);
2076 } else {
2077 mimeinfo->encoding_type = ENC_UNKNOWN;
2080 if (content_description != NULL)
2081 mimeinfo->description = g_strdup(content_description);
2082 else
2083 mimeinfo->description = NULL;
2085 if (content_id != NULL)
2086 mimeinfo->id = g_strdup(content_id);
2087 else
2088 mimeinfo->id = NULL;
2090 if (content_location != NULL)
2091 mimeinfo->location = g_strdup(content_location);
2092 else
2093 mimeinfo->location = NULL;
2095 if (content_disposition != NULL) {
2096 g_strchomp(content_disposition);
2097 procmime_parse_content_disposition(content_disposition, mimeinfo);
2098 } else
2099 mimeinfo->disposition = DISPOSITIONTYPE_UNKNOWN;
2101 /* Call parser for mime type */
2102 if ((parser = procmime_get_mimeparser_for_type(mimeinfo->type, mimeinfo->subtype)) != NULL) {
2103 parsed = procmime_mimeparser_parse(parser, mimeinfo);
2105 if (!parsed) {
2106 switch (mimeinfo->type) {
2107 case MIMETYPE_TEXT:
2108 if (g_ascii_strcasecmp(mimeinfo->subtype, "plain") == 0 && short_scan) {
2109 return 1;
2111 break;
2113 case MIMETYPE_MESSAGE:
2114 if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
2115 procmime_parse_message_rfc822(mimeinfo, short_scan);
2117 if (g_ascii_strcasecmp(mimeinfo->subtype, "disposition-notification") == 0) {
2118 procmime_parse_disposition_notification(mimeinfo,
2119 original_msgid, disposition_notification_hdr, short_scan);
2121 break;
2123 case MIMETYPE_MULTIPART:
2124 procmime_parse_multipart(mimeinfo, short_scan);
2125 break;
2127 case MIMETYPE_APPLICATION:
2128 if (g_ascii_strcasecmp(mimeinfo->subtype, "octet-stream") == 0
2129 && original_msgid && *original_msgid
2130 && disposition_notification_hdr && *disposition_notification_hdr) {
2131 procmime_parse_disposition_notification(mimeinfo,
2132 original_msgid, disposition_notification_hdr, short_scan);
2134 break;
2135 default:
2136 break;
2140 return result;
2143 static gchar *typenames[] = {
2144 "text",
2145 "image",
2146 "audio",
2147 "video",
2148 "application",
2149 "message",
2150 "multipart",
2151 "unknown",
2154 static gboolean output_func(GNode *node, gpointer data)
2156 guint i, depth;
2157 MimeInfo *mimeinfo = (MimeInfo *) node->data;
2159 depth = g_node_depth(node);
2160 for (i = 0; i < depth; i++)
2161 g_print(" ");
2162 g_print("%s/%s (offset:%d length:%d encoding: %d)\n", typenames[mimeinfo->type], mimeinfo->subtype, mimeinfo->offset, mimeinfo->length, mimeinfo->encoding_type);
2164 return FALSE;
2167 static void output_mime_structure(MimeInfo *mimeinfo, int indent)
2169 g_node_traverse(mimeinfo->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1, output_func, NULL);
2172 static MimeInfo *procmime_scan_file_with_offset(const gchar *filename, int offset, gboolean short_scan)
2174 MimeInfo *mimeinfo;
2175 GStatBuf buf;
2177 if (g_stat(filename, &buf) < 0) {
2178 FILE_OP_ERROR(filename, "stat");
2179 return NULL;
2182 mimeinfo = procmime_mimeinfo_new();
2183 mimeinfo->content = MIMECONTENT_FILE;
2184 mimeinfo->encoding_type = ENC_UNKNOWN;
2185 mimeinfo->type = MIMETYPE_MESSAGE;
2186 mimeinfo->subtype = g_strdup("rfc822");
2187 mimeinfo->data.filename = g_strdup(filename);
2188 mimeinfo->offset = offset;
2189 mimeinfo->length = buf.st_size - offset;
2191 procmime_parse_message_rfc822(mimeinfo, short_scan);
2192 if (debug_get_mode())
2193 output_mime_structure(mimeinfo, 0);
2195 return mimeinfo;
2198 static MimeInfo *procmime_scan_file_full(const gchar *filename, gboolean short_scan)
2200 MimeInfo *mimeinfo;
2202 cm_return_val_if_fail(filename != NULL, NULL);
2204 mimeinfo = procmime_scan_file_with_offset(filename, 0, short_scan);
2206 return mimeinfo;
2209 MimeInfo *procmime_scan_file(const gchar *filename)
2211 return procmime_scan_file_full(filename, FALSE);
2214 static MimeInfo *procmime_scan_file_short(const gchar *filename)
2216 return procmime_scan_file_full(filename, TRUE);
2219 static MimeInfo *procmime_scan_queue_file_full(const gchar *filename, gboolean short_scan)
2221 FILE *fp;
2222 MimeInfo *mimeinfo;
2223 gchar buf[BUFFSIZE];
2224 gint offset = 0;
2226 cm_return_val_if_fail(filename != NULL, NULL);
2228 /* Open file */
2229 if ((fp = procmime_fopen(filename, "rb")) == NULL)
2230 return NULL;
2231 /* Skip queue header */
2232 while (SC_FGETS(buf, sizeof(buf), fp) != NULL) {
2233 /* new way */
2234 if ((!strncmp(buf, "X-Claws-End-Special-Headers: 1",
2235 strlen("X-Claws-End-Special-Headers:"))) ||
2236 (!strncmp(buf, "X-Sylpheed-End-Special-Headers: 1",
2237 strlen("X-Sylpheed-End-Special-Headers:"))))
2238 break;
2239 /* old way */
2240 if (buf[0] == '\r' || buf[0] == '\n') break;
2241 /* from other mailers */
2242 if (!strncmp(buf, "Date: ", 6)
2243 || !strncmp(buf, "To: ", 4)
2244 || !strncmp(buf, "From: ", 6)
2245 || !strncmp(buf, "Subject: ", 9)) {
2246 rewind(fp);
2247 break;
2250 offset = ftell(fp);
2251 procmime_fclose(fp);
2253 mimeinfo = procmime_scan_file_with_offset(filename, offset, short_scan);
2255 return mimeinfo;
2258 MimeInfo *procmime_scan_queue_file(const gchar *filename)
2260 return procmime_scan_queue_file_full(filename, FALSE);
2263 static MimeInfo *procmime_scan_queue_file_short(const gchar *filename)
2265 return procmime_scan_queue_file_full(filename, TRUE);
2268 typedef enum {
2269 ENC_AS_TOKEN,
2270 ENC_AS_QUOTED_STRING,
2271 ENC_AS_EXTENDED,
2272 ENC_AS_ENCWORD
2273 } EncodeAs;
2275 typedef struct _ParametersData {
2276 FILE *fp;
2277 guint len;
2278 gint error;
2279 } ParametersData;
2281 static void write_parameters(gpointer key, gpointer value, gpointer user_data)
2283 gchar *param = key;
2284 gchar *val = value, *valpos, *tmp;
2285 ParametersData *pdata = (ParametersData *)user_data;
2286 GString *buf = g_string_new("");
2287 gint len;
2289 EncodeAs encas = ENC_AS_TOKEN;
2291 for (valpos = val; *valpos != 0; valpos++) {
2292 if (!IS_ASCII(*valpos)) {
2293 encas = ENC_AS_ENCWORD;
2294 break;
2297 /* CTLs */
2298 if (((*valpos >= 0) && (*valpos < 037)) || (*valpos == 0177)) {
2299 encas = ENC_AS_QUOTED_STRING;
2300 continue;
2303 /* tspecials + SPACE */
2304 switch (*valpos) {
2305 case ' ':
2306 case '(':
2307 case ')':
2308 case '<':
2309 case '>':
2310 case '@':
2311 case ',':
2312 case ';':
2313 case ':':
2314 case '\\':
2315 case '"':
2316 case '/':
2317 case '[':
2318 case ']':
2319 case '?':
2320 case '=':
2321 encas = ENC_AS_QUOTED_STRING;
2322 continue;
2326 switch (encas) {
2327 case ENC_AS_TOKEN:
2328 g_string_append_printf(buf, "%s=%s", param, val);
2329 break;
2331 case ENC_AS_QUOTED_STRING:
2332 g_string_append_printf(buf, "%s=\"%s\"", param, val);
2333 break;
2335 #if 0 /* we don't use that for now */
2336 case ENC_AS_EXTENDED:
2337 if (!g_utf8_validate(val, -1, NULL))
2338 g_string_append_printf(buf, "%s*=%s''", param,
2339 conv_get_locale_charset_str());
2340 else
2341 g_string_append_printf(buf, "%s*=%s''", param,
2342 CS_INTERNAL);
2343 for (valpos = val; *valpos != '\0'; valpos++) {
2344 if (IS_ASCII(*valpos) && isalnum(*valpos)) {
2345 g_string_append_printf(buf, "%c", *valpos);
2346 } else {
2347 gchar hexstr[3] = "XX";
2348 get_hex_str(hexstr, *valpos);
2349 g_string_append_printf(buf, "%%%s", hexstr);
2352 break;
2353 #else
2354 case ENC_AS_EXTENDED:
2355 debug_print("Unhandled ENC_AS_EXTENDED.\n");
2356 break;
2357 #endif
2358 case ENC_AS_ENCWORD:
2359 len = MAX(strlen(val)*6, 512);
2360 tmp = g_malloc(len+1);
2361 codeconv_set_strict(TRUE);
2362 conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2363 prefs_common.outgoing_charset);
2364 codeconv_set_strict(FALSE);
2365 if (!tmp || !*tmp) {
2366 codeconv_set_strict(TRUE);
2367 conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2368 conv_get_outgoing_charset_str());
2369 codeconv_set_strict(FALSE);
2371 if (!tmp || !*tmp) {
2372 codeconv_set_strict(TRUE);
2373 conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2374 CS_UTF_8);
2375 codeconv_set_strict(FALSE);
2377 if (!tmp || !*tmp) {
2378 conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2379 CS_UTF_8);
2381 g_string_append_printf(buf, "%s=\"%s\"", param, tmp);
2382 g_free(tmp);
2383 break;
2387 if (buf->str && strlen(buf->str)) {
2388 tmp = strstr(buf->str, "\n");
2389 if (tmp)
2390 len = (tmp - buf->str);
2391 else
2392 len = strlen(buf->str);
2393 if (pdata->len + len > 76) {
2394 if (fprintf(pdata->fp, ";\n %s", buf->str) < 0)
2395 pdata->error = TRUE;
2396 pdata->len = strlen(buf->str) + 1;
2397 } else {
2398 if (fprintf(pdata->fp, "; %s", buf->str) < 0)
2399 pdata->error = TRUE;
2400 pdata->len += strlen(buf->str) + 2;
2403 g_string_free(buf, TRUE);
2406 #define TRY(func) { \
2407 if (!(func)) { \
2408 return -1; \
2412 int procmime_write_mime_header(MimeInfo *mimeinfo, FILE *fp)
2414 struct TypeTable *type_table;
2415 ParametersData *pdata = g_new0(ParametersData, 1);
2416 debug_print("procmime_write_mime_header\n");
2418 pdata->fp = fp;
2419 pdata->error = FALSE;
2420 for (type_table = mime_type_table; type_table->str != NULL; type_table++)
2421 if (mimeinfo->type == type_table->type) {
2422 gchar *buf = g_strdup_printf(
2423 "Content-Type: %s/%s", type_table->str, mimeinfo->subtype);
2424 if (fprintf(fp, "%s", buf) < 0) {
2425 g_free(buf);
2426 g_free(pdata);
2427 return -1;
2429 pdata->len = strlen(buf);
2430 g_free(buf);
2431 break;
2433 g_hash_table_foreach(mimeinfo->typeparameters, write_parameters, pdata);
2434 if (pdata->error == TRUE) {
2435 g_free(pdata);
2436 return -1;
2438 g_free(pdata);
2440 TRY(fprintf(fp, "\n") >= 0);
2442 if (mimeinfo->encoding_type != ENC_UNKNOWN)
2443 TRY(fprintf(fp, "Content-Transfer-Encoding: %s\n", procmime_get_encoding_str(mimeinfo->encoding_type)) >= 0);
2445 if (mimeinfo->description != NULL)
2446 TRY(fprintf(fp, "Content-Description: %s\n", mimeinfo->description) >= 0);
2448 if (mimeinfo->id != NULL)
2449 TRY(fprintf(fp, "Content-ID: %s\n", mimeinfo->id) >= 0);
2451 if (mimeinfo->location != NULL)
2452 TRY(fprintf(fp, "Content-Location: %s\n", mimeinfo->location) >= 0);
2454 if (mimeinfo->disposition != DISPOSITIONTYPE_UNKNOWN) {
2455 ParametersData *pdata = g_new0(ParametersData, 1);
2456 gchar *buf = NULL;
2457 if (mimeinfo->disposition == DISPOSITIONTYPE_INLINE)
2458 buf = g_strdup("Content-Disposition: inline");
2459 else if (mimeinfo->disposition == DISPOSITIONTYPE_ATTACHMENT)
2460 buf = g_strdup("Content-Disposition: attachment");
2461 else
2462 buf = g_strdup("Content-Disposition: unknown");
2464 if (fprintf(fp, "%s", buf) < 0) {
2465 g_free(buf);
2466 g_free(pdata);
2467 return -1;
2469 pdata->len = strlen(buf);
2470 g_free(buf);
2472 pdata->fp = fp;
2473 pdata->error = FALSE;
2474 g_hash_table_foreach(mimeinfo->dispositionparameters, write_parameters, pdata);
2475 if (pdata->error == TRUE) {
2476 g_free(pdata);
2477 return -1;
2479 g_free(pdata);
2480 TRY(fprintf(fp, "\n") >= 0);
2483 TRY(fprintf(fp, "\n") >= 0);
2485 return 0;
2488 static gint procmime_write_message_rfc822(MimeInfo *mimeinfo, FILE *fp)
2490 FILE *infp;
2491 GNode *childnode;
2492 MimeInfo *child;
2493 gchar buf[BUFFSIZE];
2494 gboolean skip = FALSE;;
2495 size_t len;
2497 debug_print("procmime_write_message_rfc822\n");
2499 /* write header */
2500 switch (mimeinfo->content) {
2501 case MIMECONTENT_FILE:
2502 if ((infp = procmime_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2503 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2504 return -1;
2506 if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
2507 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
2508 procmime_fclose(infp);
2509 return -1;
2511 while (SC_FGETS(buf, sizeof(buf), infp) == buf) {
2512 strcrchomp(buf);
2513 if (buf[0] == '\n' && buf[1] == '\0')
2514 break;
2515 if (skip && (buf[0] == ' ' || buf[0] == '\t'))
2516 continue;
2517 if (g_ascii_strncasecmp(buf, "MIME-Version:", 13) == 0 ||
2518 g_ascii_strncasecmp(buf, "Content-Type:", 13) == 0 ||
2519 g_ascii_strncasecmp(buf, "Content-Transfer-Encoding:", 26) == 0 ||
2520 g_ascii_strncasecmp(buf, "Content-Description:", 20) == 0 ||
2521 g_ascii_strncasecmp(buf, "Content-ID:", 11) == 0 ||
2522 g_ascii_strncasecmp(buf, "Content-Location:", 17) == 0 ||
2523 g_ascii_strncasecmp(buf, "Content-Disposition:", 20) == 0) {
2524 skip = TRUE;
2525 continue;
2527 len = strlen(buf);
2528 if (SC_FWRITE(buf, sizeof(gchar), len, fp) < len) {
2529 g_warning("failed to dump %zd bytes from file", len);
2530 procmime_fclose(infp);
2531 return -1;
2533 skip = FALSE;
2535 procmime_fclose(infp);
2536 break;
2538 case MIMECONTENT_MEM:
2539 len = strlen(mimeinfo->data.mem);
2540 if (SC_FWRITE(mimeinfo->data.mem, sizeof(gchar), len, fp) < len) {
2541 g_warning("failed to dump %zd bytes from mem", len);
2542 return -1;
2544 break;
2546 default:
2547 break;
2550 childnode = mimeinfo->node->children;
2551 if (childnode == NULL)
2552 return -1;
2554 child = (MimeInfo *) childnode->data;
2555 if (fprintf(fp, "MIME-Version: 1.0\n") < 0) {
2556 g_warning("failed to write mime version");
2557 return -1;
2559 if (procmime_write_mime_header(child, fp) < 0)
2560 return -1;
2561 return procmime_write_mimeinfo(child, fp);
2564 static gint procmime_write_multipart(MimeInfo *mimeinfo, FILE *fp)
2566 FILE *infp;
2567 GNode *childnode;
2568 gchar *boundary, *str, *str2;
2569 gchar buf[BUFFSIZE];
2570 gboolean firstboundary;
2571 size_t len;
2573 debug_print("procmime_write_multipart\n");
2575 boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
2577 switch (mimeinfo->content) {
2578 case MIMECONTENT_FILE:
2579 if ((infp = procmime_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2580 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2581 return -1;
2583 if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
2584 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
2585 procmime_fclose(infp);
2586 return -1;
2588 while (SC_FGETS(buf, sizeof(buf), infp) == buf) {
2589 if (IS_BOUNDARY(buf, boundary, strlen(boundary)))
2590 break;
2591 len = strlen(buf);
2592 if (SC_FWRITE(buf, sizeof(gchar), len, fp) < len) {
2593 g_warning("failed to write %zd", len);
2594 procmime_fclose(infp);
2595 return -1;
2598 procmime_fclose(infp);
2599 break;
2601 case MIMECONTENT_MEM:
2602 str = g_strdup(mimeinfo->data.mem);
2603 if (((str2 = strstr(str, boundary)) != NULL) && ((str2 - str) >= 2) &&
2604 (*(str2 - 1) == '-') && (*(str2 - 2) == '-'))
2605 *(str2 - 2) = '\0';
2606 len = strlen(str);
2607 if (SC_FWRITE(str, sizeof(gchar), len, fp) < len) {
2608 g_warning("failed to write %zd from mem", len);
2609 g_free(str);
2610 return -1;
2612 g_free(str);
2613 break;
2615 default:
2616 break;
2619 childnode = mimeinfo->node->children;
2620 firstboundary = TRUE;
2621 while (childnode != NULL) {
2622 MimeInfo *child = childnode->data;
2624 if (firstboundary)
2625 firstboundary = FALSE;
2626 else
2627 TRY(fprintf(fp, "\n") >= 0);
2629 TRY(fprintf(fp, "--%s\n", boundary) >= 0);
2631 if (procmime_write_mime_header(child, fp) < 0)
2632 return -1;
2633 if (procmime_write_mimeinfo(child, fp) < 0)
2634 return -1;
2636 childnode = g_node_next_sibling(childnode);
2638 TRY(fprintf(fp, "\n--%s--\n", boundary) >= 0);
2640 return 0;
2643 gint procmime_write_mimeinfo(MimeInfo *mimeinfo, FILE *fp)
2645 FILE *infp;
2646 size_t len;
2647 debug_print("procmime_write_mimeinfo\n");
2649 if (G_NODE_IS_LEAF(mimeinfo->node)) {
2650 switch (mimeinfo->content) {
2651 case MIMECONTENT_FILE:
2652 if ((infp = procmime_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2653 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2654 return -1;
2656 copy_file_part_to_fp(infp, mimeinfo->offset, mimeinfo->length, fp);
2657 procmime_fclose(infp);
2658 return 0;
2660 case MIMECONTENT_MEM:
2661 len = strlen(mimeinfo->data.mem);
2662 if (SC_FWRITE(mimeinfo->data.mem, sizeof(gchar), len, fp) < len)
2663 return -1;
2664 return 0;
2666 default:
2667 return 0;
2669 } else {
2670 /* Call writer for mime type */
2671 switch (mimeinfo->type) {
2672 case MIMETYPE_MESSAGE:
2673 if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
2674 return procmime_write_message_rfc822(mimeinfo, fp);
2676 break;
2678 case MIMETYPE_MULTIPART:
2679 return procmime_write_multipart(mimeinfo, fp);
2681 default:
2682 break;
2685 return -1;
2688 return 0;
2691 gchar *procmime_get_part_file_name(MimeInfo *mimeinfo)
2693 gchar *base;
2695 if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
2696 base = g_strdup("mimetmp.html");
2697 else {
2698 const gchar *basetmp;
2699 gchar *basename;
2701 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
2702 if (basetmp == NULL)
2703 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
2704 if (basetmp == NULL)
2705 basetmp = "mimetmp";
2706 basename = g_path_get_basename(basetmp);
2707 if (*basename == '\0') {
2708 g_free(basename);
2709 basename = g_strdup("mimetmp");
2711 base = conv_filename_from_utf8(basename);
2712 g_free(basename);
2713 subst_for_shellsafe_filename(base);
2716 return base;