Fix bug #3574: Template addressing
[claws.git] / src / procmime.c
blobc29da8c7ad90c9b512dcb69f043192f5f95b5724
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 EncodingType encoding = forced_encoding
327 ? forced_encoding
328 : mimeinfo->encoding_type;
329 gchar lastline[BUFFSIZE];
330 memset(lastline, 0, BUFFSIZE);
332 cm_return_val_if_fail(mimeinfo != NULL, FALSE);
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 perror("fopen");
363 return FALSE;
365 if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
366 perror("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("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;
462 procmime_fclose(tmpfp);
464 } else if (encoding == ENC_X_UUENCODE) {
465 gchar outbuf[BUFFSIZE];
466 gint len;
467 gboolean flag = FALSE;
469 while ((ftell(infp) < readend) && (SC_FGETS(buf, sizeof(buf), infp) != NULL)) {
470 if (!flag && strncmp(buf,"begin ", 6)) continue;
472 if (flag) {
473 len = fromuutobits(outbuf, buf);
474 if (len <= 0) {
475 if (len < 0)
476 g_warning("Bad UUENCODE content (%d)", len);
477 break;
479 if (SC_FWRITE(outbuf, sizeof(gchar), len, outfp) < len)
480 err = TRUE;
481 } else
482 flag = TRUE;
484 } else {
485 while ((ftell(infp) < readend) && (SC_FGETS(buf, sizeof(buf), infp) != NULL)) {
486 if (!flowed) {
487 if (SC_FPUTS(buf, outfp) == EOF)
488 err = TRUE;
489 } else {
490 FLUSH_LASTLINE();
493 if (flowed)
494 FLUSH_LASTLINE();
495 if (err == TRUE)
496 g_warning("write error");
499 procmime_fclose(outfp);
500 procmime_fclose(infp);
502 if (err == TRUE) {
503 return FALSE;
506 if (g_stat(tmpfilename, &statbuf) < 0) {
507 FILE_OP_ERROR(tmpfilename, "stat");
508 return FALSE;
511 if (mimeinfo->tmp)
512 claws_unlink(mimeinfo->data.filename);
513 g_free(mimeinfo->data.filename);
514 mimeinfo->data.filename = tmpfilename;
515 mimeinfo->tmp = TRUE;
516 mimeinfo->offset = 0;
517 mimeinfo->length = statbuf.st_size;
518 mimeinfo->encoding_type = ENC_BINARY;
520 return TRUE;
523 #define B64_LINE_SIZE 57
524 #define B64_BUFFSIZE 77
526 gboolean procmime_encode_content(MimeInfo *mimeinfo, EncodingType encoding)
528 FILE *infp = NULL, *outfp;
529 gint len;
530 gchar *tmpfilename;
531 GStatBuf statbuf;
532 gboolean err = FALSE;
534 if (mimeinfo->content == MIMECONTENT_EMPTY)
535 return TRUE;
537 if (mimeinfo->encoding_type != ENC_UNKNOWN &&
538 mimeinfo->encoding_type != ENC_BINARY &&
539 mimeinfo->encoding_type != ENC_7BIT &&
540 mimeinfo->encoding_type != ENC_8BIT)
541 if(!procmime_decode_content(mimeinfo))
542 return FALSE;
544 outfp = get_tmpfile_in_dir(get_mime_tmp_dir(), &tmpfilename);
545 if (!outfp) {
546 perror("tmpfile");
547 return FALSE;
549 #ifdef HAVE_FGETS_UNLOCKED
550 flockfile(outfp);
551 #endif
553 if (mimeinfo->content == MIMECONTENT_FILE && mimeinfo->data.filename) {
554 if ((infp = procmime_fopen(mimeinfo->data.filename, "rb")) == NULL) {
555 g_warning("Can't open file %s", mimeinfo->data.filename);
556 procmime_fclose(outfp);
557 return FALSE;
559 } else if (mimeinfo->content == MIMECONTENT_MEM) {
560 infp = str_open_as_stream(mimeinfo->data.mem);
561 if (infp == NULL) {
562 procmime_fclose(outfp);
563 return FALSE;
565 #ifdef HAVE_FGETS_UNLOCKED
566 flockfile(infp);
567 #endif
568 } else {
569 procmime_fclose(outfp);
570 g_warning("Unknown mimeinfo");
571 return FALSE;
574 if (encoding == ENC_BASE64) {
575 gchar inbuf[B64_LINE_SIZE], *out;
576 FILE *tmp_fp = infp;
577 gchar *tmp_file = NULL;
579 if (mimeinfo->type == MIMETYPE_TEXT ||
580 mimeinfo->type == MIMETYPE_MESSAGE) {
581 if (mimeinfo->content == MIMECONTENT_FILE) {
582 tmp_file = get_tmp_file();
583 if (canonicalize_file(mimeinfo->data.filename, tmp_file) < 0) {
584 g_free(tmp_file);
585 procmime_fclose(infp);
586 procmime_fclose(outfp);
587 return FALSE;
589 if ((tmp_fp = procmime_fopen(tmp_file, "rb")) == NULL) {
590 FILE_OP_ERROR(tmp_file, "fopen");
591 claws_unlink(tmp_file);
592 g_free(tmp_file);
593 procmime_fclose(infp);
594 procmime_fclose(outfp);
595 return FALSE;
597 } else {
598 gchar *out = canonicalize_str(mimeinfo->data.mem);
599 procmime_fclose(infp);
600 infp = str_open_as_stream(out);
601 tmp_fp = infp;
602 g_free(out);
603 if (infp == NULL) {
604 procmime_fclose(outfp);
605 return FALSE;
607 #ifdef HAVE_FGETS_UNLOCKED
608 flockfile(infp);
609 #endif
613 while ((len = SC_FREAD(inbuf, sizeof(gchar),
614 B64_LINE_SIZE, tmp_fp))
615 == B64_LINE_SIZE) {
616 out = g_base64_encode(inbuf, B64_LINE_SIZE);
617 if (SC_FPUTS(out, outfp) == EOF)
618 err = TRUE;
619 g_free(out);
620 if (SC_FPUTC('\n', outfp) == EOF)
621 err = TRUE;
623 if (len > 0 && SC_FEOF(tmp_fp)) {
624 out = g_base64_encode(inbuf, len);
625 if (SC_FPUTS(out, outfp) == EOF)
626 err = TRUE;
627 g_free(out);
628 if (SC_FPUTC('\n', outfp) == EOF)
629 err = TRUE;
632 if (tmp_file) {
633 procmime_fclose(tmp_fp);
634 claws_unlink(tmp_file);
635 g_free(tmp_file);
637 } else if (encoding == ENC_QUOTED_PRINTABLE) {
638 gchar inbuf[BUFFSIZE], outbuf[BUFFSIZE * 4];
640 while (SC_FGETS(inbuf, sizeof(inbuf), infp) != NULL) {
641 qp_encode_line(outbuf, inbuf);
643 if (!strncmp("From ", outbuf, sizeof("From ")-1)) {
644 gchar *tmpbuf = outbuf;
646 tmpbuf += sizeof("From ")-1;
648 if (SC_FPUTS("=46rom ", outfp) == EOF)
649 err = TRUE;
650 if (SC_FPUTS(tmpbuf, outfp) == EOF)
651 err = TRUE;
652 } else {
653 if (SC_FPUTS(outbuf, outfp) == EOF)
654 err = TRUE;
657 } else {
658 gchar buf[BUFFSIZE];
660 while (SC_FGETS(buf, sizeof(buf), infp) != NULL) {
661 strcrchomp(buf);
662 if (SC_FPUTS(buf, outfp) == EOF)
663 err = TRUE;
667 procmime_fclose(outfp);
668 procmime_fclose(infp);
670 if (err == TRUE)
671 return FALSE;
673 if (mimeinfo->content == MIMECONTENT_FILE) {
674 if (mimeinfo->tmp && (mimeinfo->data.filename != NULL))
675 claws_unlink(mimeinfo->data.filename);
676 g_free(mimeinfo->data.filename);
677 } else if (mimeinfo->content == MIMECONTENT_MEM) {
678 if (mimeinfo->tmp && (mimeinfo->data.mem != NULL))
679 g_free(mimeinfo->data.mem);
682 if (g_stat(tmpfilename, &statbuf) < 0) {
683 FILE_OP_ERROR(tmpfilename, "stat");
684 return FALSE;
686 mimeinfo->content = MIMECONTENT_FILE;
687 mimeinfo->data.filename = tmpfilename;
688 mimeinfo->tmp = TRUE;
689 mimeinfo->offset = 0;
690 mimeinfo->length = statbuf.st_size;
691 mimeinfo->encoding_type = encoding;
693 return TRUE;
696 gint procmime_get_part(const gchar *outfile, MimeInfo *mimeinfo)
698 FILE *infp, *outfp;
699 gchar buf[BUFFSIZE];
700 gint restlength, readlength;
701 gint saved_errno = 0;
703 cm_return_val_if_fail(outfile != NULL, -1);
704 cm_return_val_if_fail(mimeinfo != NULL, -1);
706 if (mimeinfo->encoding_type != ENC_BINARY && !procmime_decode_content(mimeinfo))
707 return -EINVAL;
709 if ((infp = procmime_fopen(mimeinfo->data.filename, "rb")) == NULL) {
710 saved_errno = errno;
711 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
712 return -(saved_errno);
714 if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
715 saved_errno = errno;
716 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
717 procmime_fclose(infp);
718 return -(saved_errno);
720 if ((outfp = procmime_fopen(outfile, "wb")) == NULL) {
721 saved_errno = errno;
722 FILE_OP_ERROR(outfile, "fopen");
723 procmime_fclose(infp);
724 return -(saved_errno);
727 restlength = mimeinfo->length;
729 while ((restlength > 0) && ((readlength = SC_FREAD(buf, 1, restlength > BUFFSIZE ? BUFFSIZE : restlength, infp)) > 0)) {
730 if (SC_FWRITE(buf, 1, readlength, outfp) != readlength) {
731 saved_errno = errno;
732 procmime_fclose(infp);
733 procmime_fclose(outfp);
734 return -(saved_errno);
736 restlength -= readlength;
739 procmime_fclose(infp);
740 if (procmime_fclose(outfp) == EOF) {
741 saved_errno = errno;
742 FILE_OP_ERROR(outfile, "fclose");
743 claws_unlink(outfile);
744 return -(saved_errno);
747 return 0;
750 gboolean procmime_scan_text_content(MimeInfo *mimeinfo,
751 gboolean (*scan_callback)(const gchar *str, gpointer cb_data),
752 gpointer cb_data)
754 FILE *tmpfp;
755 const gchar *src_codeset;
756 gboolean conv_fail = FALSE;
757 gchar buf[BUFFSIZE];
758 gchar *str;
759 gchar *tmpfile;
760 gboolean scan_ret = FALSE;
762 cm_return_val_if_fail(mimeinfo != NULL, TRUE);
763 cm_return_val_if_fail(scan_callback != NULL, TRUE);
765 if (!procmime_decode_content(mimeinfo))
766 return TRUE;
768 tmpfile = procmime_get_tmp_file_name(mimeinfo);
769 if (tmpfile == NULL)
770 return TRUE;
772 if (procmime_get_part(tmpfile, mimeinfo) < 0) {
773 g_free(tmpfile);
774 return TRUE;
777 tmpfp = procmime_fopen(tmpfile, "rb");
778 if (tmpfp == NULL) {
779 g_free(tmpfile);
780 return TRUE;
783 src_codeset = forced_charset
784 ? forced_charset :
785 procmime_mimeinfo_get_parameter(mimeinfo, "charset");
787 /* use supersets transparently when possible */
788 if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_ISO_8859_1))
789 src_codeset = CS_WINDOWS_1252;
790 else if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_X_GBK))
791 src_codeset = CS_GB18030;
792 else if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_GBK))
793 src_codeset = CS_GB18030;
794 else if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_GB2312))
795 src_codeset = CS_GB18030;
796 else if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_X_VIET_VPS))
797 src_codeset = CS_WINDOWS_874;
799 if (mimeinfo->type == MIMETYPE_TEXT && !g_ascii_strcasecmp(mimeinfo->subtype, "html")) {
800 SC_HTMLParser *parser;
801 CodeConverter *conv;
803 conv = conv_code_converter_new(src_codeset);
804 parser = sc_html_parser_new(tmpfp, conv);
805 while ((str = sc_html_parse(parser)) != NULL) {
806 if ((scan_ret = scan_callback(str, cb_data)) == TRUE)
807 break;
809 sc_html_parser_destroy(parser);
810 conv_code_converter_destroy(conv);
811 } else if (mimeinfo->type == MIMETYPE_TEXT && !g_ascii_strcasecmp(mimeinfo->subtype, "enriched")) {
812 ERTFParser *parser;
813 CodeConverter *conv;
815 conv = conv_code_converter_new(src_codeset);
816 parser = ertf_parser_new(tmpfp, conv);
817 while ((str = ertf_parse(parser)) != NULL) {
818 if ((scan_ret = scan_callback(str, cb_data)) == TRUE)
819 break;
821 ertf_parser_destroy(parser);
822 conv_code_converter_destroy(conv);
823 } else if (mimeinfo->type == MIMETYPE_TEXT && mimeinfo->disposition != DISPOSITIONTYPE_ATTACHMENT) {
824 while (SC_FGETS(buf, sizeof(buf), tmpfp) != NULL) {
825 str = conv_codeset_strdup(buf, src_codeset, CS_UTF_8);
826 if (str) {
827 if ((scan_ret = scan_callback(str, cb_data)) == TRUE) {
828 g_free(str);
829 break;
831 g_free(str);
832 } else {
833 conv_fail = TRUE;
834 if ((scan_ret = scan_callback(buf, cb_data)) == TRUE)
835 break;
840 if (conv_fail)
841 g_warning("procmime_get_text_content(): Code conversion failed.");
843 procmime_fclose(tmpfp);
844 claws_unlink(tmpfile);
845 g_free(tmpfile);
847 return scan_ret;
850 static gboolean scan_fputs_cb(const gchar *str, gpointer fp)
852 if (SC_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("tmpfile");
865 return NULL;
867 #ifdef HAVE_FGETS_UNLOCKED
868 flockfile(outfp);
869 #endif
871 err = procmime_scan_text_content(mimeinfo, scan_fputs_cb, outfp);
873 rewind(outfp);
874 if (err == TRUE) {
875 procmime_fclose(outfp);
876 return NULL;
878 #ifdef HAVE_FGETS_UNLOCKED
879 funlockfile(outfp);
880 #endif
881 return outfp;
885 FILE *procmime_get_binary_content(MimeInfo *mimeinfo)
887 FILE *outfp;
888 gchar *tmpfile;
890 cm_return_val_if_fail(mimeinfo != NULL, NULL);
892 if (!procmime_decode_content(mimeinfo))
893 return NULL;
895 tmpfile = procmime_get_tmp_file_name(mimeinfo);
896 if (tmpfile == NULL)
897 return NULL;
899 if (procmime_get_part(tmpfile, mimeinfo) < 0) {
900 g_free(tmpfile);
901 return NULL;
904 outfp = procmime_fopen(tmpfile, "rb");
905 if (outfp == NULL) {
906 g_unlink(tmpfile);
907 g_free(tmpfile);
908 return NULL;
911 g_unlink(tmpfile);
912 g_free(tmpfile);
914 #ifdef HAVE_FGETS_UNLOCKED
915 funlockfile(outfp);
916 #endif
917 return outfp;
920 /* search the first text part of (multipart) MIME message,
921 decode, convert it and output to outfp. */
922 FILE *procmime_get_first_text_content(MsgInfo *msginfo)
924 FILE *outfp = NULL;
925 MimeInfo *mimeinfo, *partinfo;
926 gboolean empty_ok = FALSE, short_scan = TRUE;
928 cm_return_val_if_fail(msginfo != NULL, NULL);
930 /* first we try to short-scan (for speed), refusing empty parts */
931 scan_again:
932 if (short_scan)
933 mimeinfo = procmime_scan_message_short(msginfo);
934 else
935 mimeinfo = procmime_scan_message(msginfo);
936 if (!mimeinfo) return NULL;
938 partinfo = mimeinfo;
939 while (partinfo && (partinfo->type != MIMETYPE_TEXT ||
940 (partinfo->length == 0 && !empty_ok))) {
941 partinfo = procmime_mimeinfo_next(partinfo);
943 if (partinfo)
944 outfp = procmime_get_text_content(partinfo);
945 else if (!empty_ok && short_scan) {
946 /* if short scan didn't find a non-empty part, rescan
947 * fully for non-empty parts
949 short_scan = FALSE;
950 procmime_mimeinfo_free_all(&mimeinfo);
951 goto scan_again;
952 } else if (!empty_ok && !short_scan) {
953 /* if full scan didn't find a non-empty part, rescan
954 * accepting empty parts
956 empty_ok = TRUE;
957 procmime_mimeinfo_free_all(&mimeinfo);
958 goto scan_again;
960 procmime_mimeinfo_free_all(&mimeinfo);
962 /* outfp already unlocked at this time */
963 return outfp;
967 static gboolean find_encrypted_func(GNode *node, gpointer data)
969 MimeInfo *mimeinfo = (MimeInfo *) node->data;
970 MimeInfo **encinfo = (MimeInfo **) data;
972 if (privacy_mimeinfo_is_encrypted(mimeinfo)) {
973 *encinfo = mimeinfo;
974 return TRUE;
977 return FALSE;
980 static MimeInfo *find_encrypted_part(MimeInfo *rootinfo)
982 MimeInfo *encinfo = NULL;
984 g_node_traverse(rootinfo->node, G_IN_ORDER, G_TRAVERSE_ALL, -1,
985 find_encrypted_func, &encinfo);
987 return encinfo;
990 /* search the first encrypted text part of (multipart) MIME message,
991 decode, convert it and output to outfp. */
992 FILE *procmime_get_first_encrypted_text_content(MsgInfo *msginfo)
994 FILE *outfp = NULL;
995 MimeInfo *mimeinfo, *partinfo, *encinfo;
997 cm_return_val_if_fail(msginfo != NULL, NULL);
999 mimeinfo = procmime_scan_message(msginfo);
1000 if (!mimeinfo) {
1001 return NULL;
1004 partinfo = mimeinfo;
1005 if ((encinfo = find_encrypted_part(partinfo)) != NULL) {
1006 debug_print("decrypting message part\n");
1007 if (privacy_mimeinfo_decrypt(encinfo) < 0) {
1008 alertpanel_error(_("Couldn't decrypt: %s"),
1009 privacy_get_error());
1010 return NULL;
1013 partinfo = mimeinfo;
1014 while (partinfo && partinfo->type != MIMETYPE_TEXT) {
1015 partinfo = procmime_mimeinfo_next(partinfo);
1016 if (privacy_mimeinfo_is_signed(partinfo))
1017 procmsg_msginfo_set_flags(msginfo, 0, MSG_SIGNED);
1020 if (partinfo)
1021 outfp = procmime_get_text_content(partinfo);
1023 procmime_mimeinfo_free_all(&mimeinfo);
1025 /* outfp already unlocked at this time */
1026 return outfp;
1029 gboolean procmime_msginfo_is_encrypted(MsgInfo *msginfo)
1031 MimeInfo *mimeinfo, *partinfo;
1032 gboolean result = FALSE;
1034 cm_return_val_if_fail(msginfo != NULL, FALSE);
1036 mimeinfo = procmime_scan_message(msginfo);
1037 if (!mimeinfo) {
1038 return FALSE;
1041 partinfo = mimeinfo;
1042 result = (find_encrypted_part(partinfo) != NULL);
1043 procmime_mimeinfo_free_all(&mimeinfo);
1045 return result;
1048 gchar *procmime_get_tmp_file_name(MimeInfo *mimeinfo)
1050 static guint32 id = 0;
1051 gchar *base;
1052 gchar *filename;
1053 gchar f_prefix[10];
1055 cm_return_val_if_fail(mimeinfo != NULL, NULL);
1057 g_snprintf(f_prefix, sizeof(f_prefix), "%08x.", id++);
1059 if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
1060 base = g_strdup("mimetmp.html");
1061 else {
1062 const gchar *basetmp;
1064 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
1065 if (basetmp == NULL)
1066 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
1067 if (basetmp == NULL)
1068 basetmp = "mimetmp";
1069 basetmp = g_path_get_basename(basetmp);
1070 if (*basetmp == '\0')
1071 basetmp = g_strdup("mimetmp");
1072 base = conv_filename_from_utf8(basetmp);
1073 g_free((gchar*)basetmp);
1074 subst_for_shellsafe_filename(base);
1077 filename = g_strconcat(get_mime_tmp_dir(), G_DIR_SEPARATOR_S,
1078 f_prefix, base, NULL);
1080 g_free(base);
1082 return filename;
1085 static GList *mime_type_list = NULL;
1087 gchar *procmime_get_mime_type(const gchar *filename)
1089 const gchar *p;
1090 gchar *ext = NULL;
1091 gchar *base;
1092 #ifndef G_OS_WIN32
1093 static GHashTable *mime_type_table = NULL;
1094 MimeType *mime_type;
1096 if (!mime_type_table) {
1097 mime_type_table = procmime_get_mime_type_table();
1098 if (!mime_type_table) return NULL;
1100 #endif
1102 if (filename == NULL)
1103 return NULL;
1105 base = g_path_get_basename(filename);
1106 if ((p = strrchr(base, '.')) != NULL)
1107 ext = g_utf8_strdown(p + 1, -1);
1108 else
1109 ext = g_utf8_strdown(base, -1);
1110 g_free(base);
1112 #ifndef G_OS_WIN32
1113 mime_type = g_hash_table_lookup(mime_type_table, ext);
1115 if (mime_type) {
1116 gchar *str;
1117 str = g_strconcat(mime_type->type, "/", mime_type->sub_type,
1118 NULL);
1119 debug_print("got type %s for %s\n", str, ext);
1120 g_free(ext);
1121 return str;
1123 return NULL;
1124 #else
1125 gchar *str = get_content_type_from_registry_with_ext(ext);
1127 g_free(ext);
1128 return str;
1129 #endif
1132 static guint procmime_str_hash(gconstpointer gptr)
1134 guint hash_result = 0;
1135 const char *str;
1137 for (str = gptr; str && *str; str++) {
1138 if (isupper(*str)) hash_result += (*str + ' ');
1139 else hash_result += *str;
1142 return hash_result;
1145 static gint procmime_str_equal(gconstpointer gptr1, gconstpointer gptr2)
1147 const char *str1 = gptr1;
1148 const char *str2 = gptr2;
1150 return !g_utf8_collate(str1, str2);
1153 static GHashTable *procmime_get_mime_type_table(void)
1155 GHashTable *table = NULL;
1156 GList *cur;
1157 MimeType *mime_type;
1158 gchar **exts;
1160 if (!mime_type_list) {
1161 mime_type_list = procmime_get_mime_type_list();
1162 if (!mime_type_list) return NULL;
1165 table = g_hash_table_new(procmime_str_hash, procmime_str_equal);
1167 for (cur = mime_type_list; cur != NULL; cur = cur->next) {
1168 gint i;
1169 gchar *key;
1171 mime_type = (MimeType *)cur->data;
1173 if (!mime_type->extension) continue;
1175 exts = g_strsplit(mime_type->extension, " ", 16);
1176 for (i = 0; exts[i] != NULL; i++) {
1177 /* Don't overwrite previously inserted extension */
1178 if (!g_hash_table_lookup(table, exts[i])) {
1179 key = g_strdup(exts[i]);
1180 g_hash_table_insert(table, key, mime_type);
1183 g_strfreev(exts);
1186 return table;
1189 GList *procmime_get_mime_type_list(void)
1191 GList *list = NULL;
1192 FILE *fp;
1193 gchar buf[BUFFSIZE];
1194 gchar *p;
1195 gchar *delim;
1196 MimeType *mime_type;
1197 gboolean fp_is_glob_file = TRUE;
1199 if (mime_type_list)
1200 return mime_type_list;
1202 #if defined(__NetBSD__) || defined(__OpenBSD__) || defined(__FreeBSD__)
1203 if ((fp = procmime_fopen(DATAROOTDIR "/mime/globs", "rb")) == NULL)
1204 #else
1205 if ((fp = procmime_fopen("/usr/share/mime/globs", "rb")) == NULL)
1206 #endif
1208 fp_is_glob_file = FALSE;
1209 if ((fp = procmime_fopen("/etc/mime.types", "rb")) == NULL) {
1210 if ((fp = procmime_fopen(SYSCONFDIR "/mime.types", "rb"))
1211 == NULL) {
1212 FILE_OP_ERROR(SYSCONFDIR "/mime.types",
1213 "fopen");
1214 return NULL;
1219 while (SC_FGETS(buf, sizeof(buf), fp) != NULL) {
1220 p = strchr(buf, '#');
1221 if (p) *p = '\0';
1222 g_strstrip(buf);
1224 p = buf;
1226 if (fp_is_glob_file) {
1227 while (*p && !g_ascii_isspace(*p) && (*p!=':')) p++;
1228 } else {
1229 while (*p && !g_ascii_isspace(*p)) p++;
1232 if (*p) {
1233 *p = '\0';
1234 p++;
1236 delim = strchr(buf, '/');
1237 if (delim == NULL) continue;
1238 *delim = '\0';
1240 mime_type = g_new(MimeType, 1);
1241 mime_type->type = g_strdup(buf);
1242 mime_type->sub_type = g_strdup(delim + 1);
1244 if (fp_is_glob_file) {
1245 while (*p && (g_ascii_isspace(*p)||(*p=='*')||(*p=='.'))) p++;
1246 } else {
1247 while (*p && g_ascii_isspace(*p)) p++;
1250 if (*p)
1251 mime_type->extension = g_utf8_strdown(p, -1);
1252 else
1253 mime_type->extension = NULL;
1255 list = g_list_append(list, mime_type);
1258 procmime_fclose(fp);
1260 if (!list)
1261 g_warning("Can't read mime.types");
1263 return list;
1266 EncodingType procmime_get_encoding_for_charset(const gchar *charset)
1268 if (!charset)
1269 return ENC_8BIT;
1270 else if (!g_ascii_strncasecmp(charset, "ISO-2022-", 9) ||
1271 !g_ascii_strcasecmp(charset, "US-ASCII"))
1272 return ENC_7BIT;
1273 else if (!g_ascii_strcasecmp(charset, "ISO-8859-5") ||
1274 !g_ascii_strncasecmp(charset, "KOI8-", 5) ||
1275 !g_ascii_strcasecmp(charset, "X-MAC-CYRILLIC") ||
1276 !g_ascii_strcasecmp(charset, "MAC-CYRILLIC") ||
1277 !g_ascii_strcasecmp(charset, "Windows-1251"))
1278 return ENC_8BIT;
1279 else if (!g_ascii_strncasecmp(charset, "ISO-8859-", 9))
1280 return ENC_QUOTED_PRINTABLE;
1281 else if (!g_ascii_strncasecmp(charset, "UTF-8", 5))
1282 return ENC_QUOTED_PRINTABLE;
1283 else
1284 return ENC_8BIT;
1287 EncodingType procmime_get_encoding_for_text_file(const gchar *file, gboolean *has_binary)
1289 FILE *fp;
1290 guchar buf[BUFFSIZE];
1291 size_t len;
1292 size_t octet_chars = 0;
1293 size_t total_len = 0;
1294 gfloat octet_percentage;
1295 gboolean force_b64 = FALSE;
1297 if ((fp = procmime_fopen(file, "rb")) == NULL) {
1298 FILE_OP_ERROR(file, "fopen");
1299 return ENC_UNKNOWN;
1302 while ((len = SC_FREAD(buf, sizeof(guchar), sizeof(buf), fp)) > 0) {
1303 guchar *p;
1304 gint i;
1306 for (p = buf, i = 0; i < len; ++p, ++i) {
1307 if (*p & 0x80)
1308 ++octet_chars;
1309 if (*p == '\0') {
1310 force_b64 = TRUE;
1311 *has_binary = TRUE;
1314 total_len += len;
1317 procmime_fclose(fp);
1319 if (total_len > 0)
1320 octet_percentage = (gfloat)octet_chars / (gfloat)total_len;
1321 else
1322 octet_percentage = 0.0;
1324 debug_print("procmime_get_encoding_for_text_file(): "
1325 "8bit chars: %zd / %zd (%f%%)\n", octet_chars, total_len,
1326 100.0 * octet_percentage);
1328 if (octet_percentage > 0.20 || force_b64) {
1329 debug_print("using BASE64\n");
1330 return ENC_BASE64;
1331 } else if (octet_chars > 0) {
1332 debug_print("using quoted-printable\n");
1333 return ENC_QUOTED_PRINTABLE;
1334 } else {
1335 debug_print("using 7bit\n");
1336 return ENC_7BIT;
1340 struct EncodingTable
1342 gchar *str;
1343 EncodingType enc_type;
1346 struct EncodingTable encoding_table[] = {
1347 {"7bit", ENC_7BIT},
1348 {"8bit", ENC_8BIT},
1349 {"binary", ENC_BINARY},
1350 {"quoted-printable", ENC_QUOTED_PRINTABLE},
1351 {"base64", ENC_BASE64},
1352 {"x-uuencode", ENC_UNKNOWN},
1353 {NULL, ENC_UNKNOWN},
1356 const gchar *procmime_get_encoding_str(EncodingType encoding)
1358 struct EncodingTable *enc_table;
1360 for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1361 if (enc_table->enc_type == encoding)
1362 return enc_table->str;
1364 return NULL;
1367 /* --- NEW MIME STUFF --- */
1368 struct TypeTable
1370 gchar *str;
1371 MimeMediaType type;
1374 static struct TypeTable mime_type_table[] = {
1375 {"text", MIMETYPE_TEXT},
1376 {"image", MIMETYPE_IMAGE},
1377 {"audio", MIMETYPE_AUDIO},
1378 {"video", MIMETYPE_VIDEO},
1379 {"application", MIMETYPE_APPLICATION},
1380 {"message", MIMETYPE_MESSAGE},
1381 {"multipart", MIMETYPE_MULTIPART},
1382 {NULL, 0},
1385 const gchar *procmime_get_media_type_str(MimeMediaType type)
1387 struct TypeTable *type_table;
1389 for (type_table = mime_type_table; type_table->str != NULL; type_table++) {
1390 if (type_table->type == type)
1391 return type_table->str;
1393 return NULL;
1396 MimeMediaType procmime_get_media_type(const gchar *str)
1398 struct TypeTable *typetablearray;
1400 for (typetablearray = mime_type_table; typetablearray->str != NULL; typetablearray++)
1401 if (g_ascii_strncasecmp(str, typetablearray->str, strlen(typetablearray->str)) == 0)
1402 return typetablearray->type;
1404 return MIMETYPE_UNKNOWN;
1408 *\brief Safe wrapper for content type string.
1410 *\return const gchar * Pointer to content type string.
1412 gchar *procmime_get_content_type_str(MimeMediaType type,
1413 const char *subtype)
1415 const gchar *type_str = NULL;
1417 if (subtype == NULL || !(type_str = procmime_get_media_type_str(type)))
1418 return g_strdup("unknown");
1419 return g_strdup_printf("%s/%s", type_str, subtype);
1422 static int procmime_parse_mimepart(MimeInfo *parent,
1423 gchar *content_type,
1424 gchar *content_encoding,
1425 gchar *content_description,
1426 gchar *content_id,
1427 gchar *content_disposition,
1428 gchar *content_location,
1429 const gchar *original_msgid,
1430 const gchar *disposition_notification_hdr,
1431 const gchar *filename,
1432 guint offset,
1433 guint length,
1434 gboolean short_scan);
1436 static void procmime_parse_message_rfc822(MimeInfo *mimeinfo, gboolean short_scan)
1438 HeaderEntry hentry[] = {{"Content-Type:", NULL, TRUE},
1439 {"Content-Transfer-Encoding:",
1440 NULL, FALSE},
1441 {"Content-Description:",
1442 NULL, TRUE},
1443 {"Content-ID:",
1444 NULL, TRUE},
1445 {"Content-Disposition:",
1446 NULL, TRUE},
1447 {"Content-Location:",
1448 NULL, TRUE},
1449 {"MIME-Version:",
1450 NULL, TRUE},
1451 {"Original-Message-ID:",
1452 NULL, TRUE},
1453 {"Disposition:",
1454 NULL, TRUE},
1455 {NULL, NULL, FALSE}};
1456 guint content_start, i;
1457 FILE *fp;
1458 gchar *tmp;
1459 gint len = 0;
1461 procmime_decode_content(mimeinfo);
1463 fp = procmime_fopen(mimeinfo->data.filename, "rb");
1464 if (fp == NULL) {
1465 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1466 return;
1468 if (fseek(fp, mimeinfo->offset, SEEK_SET) < 0) {
1469 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
1470 procmime_fclose(fp);
1471 return;
1473 procheader_get_header_fields(fp, hentry);
1474 if (hentry[0].body != NULL) {
1475 tmp = conv_unmime_header(hentry[0].body, NULL, FALSE);
1476 g_free(hentry[0].body);
1477 hentry[0].body = tmp;
1479 if (hentry[2].body != NULL) {
1480 tmp = conv_unmime_header(hentry[2].body, NULL, FALSE);
1481 g_free(hentry[2].body);
1482 hentry[2].body = tmp;
1484 if (hentry[4].body != NULL) {
1485 tmp = conv_unmime_header(hentry[4].body, NULL, FALSE);
1486 g_free(hentry[4].body);
1487 hentry[4].body = tmp;
1489 if (hentry[5].body != NULL) {
1490 tmp = conv_unmime_header(hentry[5].body, NULL, FALSE);
1491 g_free(hentry[5].body);
1492 hentry[5].body = tmp;
1494 if (hentry[7].body != NULL) {
1495 tmp = conv_unmime_header(hentry[7].body, NULL, FALSE);
1496 g_free(hentry[7].body);
1497 hentry[7].body = tmp;
1499 if (hentry[8].body != NULL) {
1500 tmp = conv_unmime_header(hentry[8].body, NULL, FALSE);
1501 g_free(hentry[8].body);
1502 hentry[8].body = tmp;
1505 content_start = ftell(fp);
1506 procmime_fclose(fp);
1508 len = mimeinfo->length - (content_start - mimeinfo->offset);
1509 if (len < 0)
1510 len = 0;
1511 procmime_parse_mimepart(mimeinfo,
1512 hentry[0].body, hentry[1].body,
1513 hentry[2].body, hentry[3].body,
1514 hentry[4].body, hentry[5].body,
1515 hentry[7].body, hentry[8].body,
1516 mimeinfo->data.filename, content_start,
1517 len, short_scan);
1519 for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1520 g_free(hentry[i].body);
1521 hentry[i].body = NULL;
1525 static void procmime_parse_disposition_notification(MimeInfo *mimeinfo,
1526 const gchar *original_msgid, const gchar *disposition_notification_hdr,
1527 gboolean short_scan)
1529 HeaderEntry hentry[] = {{"Original-Message-ID:", NULL, TRUE},
1530 {"Disposition:", NULL, TRUE},
1531 {NULL, NULL, FALSE}};
1532 guint i;
1533 FILE *fp;
1534 gchar *orig_msg_id = NULL;
1535 gchar *disp = NULL;
1537 procmime_decode_content(mimeinfo);
1539 debug_print("parse disposition notification\n");
1540 fp = procmime_fopen(mimeinfo->data.filename, "rb");
1541 if (fp == NULL) {
1542 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1543 return;
1545 if (fseek(fp, mimeinfo->offset, SEEK_SET) < 0) {
1546 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
1547 procmime_fclose(fp);
1548 return;
1551 if (original_msgid && disposition_notification_hdr) {
1552 hentry[0].body = g_strdup(original_msgid);
1553 hentry[1].body = g_strdup(disposition_notification_hdr);
1554 } else {
1555 procheader_get_header_fields(fp, hentry);
1558 procmime_fclose(fp);
1560 if (!hentry[0].body || !hentry[1].body) {
1561 debug_print("MsgId %s, Disp %s\n",
1562 hentry[0].body ? hentry[0].body:"(nil)",
1563 hentry[1].body ? hentry[1].body:"(nil)");
1564 goto bail;
1567 orig_msg_id = g_strdup(hentry[0].body);
1568 disp = g_strdup(hentry[1].body);
1570 extract_parenthesis(orig_msg_id, '<', '>');
1571 remove_space(orig_msg_id);
1573 if (strstr(disp, "displayed")) {
1574 /* find sent message, if possible */
1575 MsgInfo *info = NULL;
1576 GList *flist;
1577 debug_print("%s has been displayed.\n", orig_msg_id);
1578 for (flist = folder_get_list(); flist != NULL; flist = g_list_next(flist)) {
1579 FolderItem *outbox = ((Folder *)(flist->data))->outbox;
1580 if (!outbox) {
1581 debug_print("skipping folder with no outbox...\n");
1582 continue;
1584 info = folder_item_get_msginfo_by_msgid(outbox, orig_msg_id);
1585 debug_print("%s %s in %s\n", info?"found":"didn't find", orig_msg_id, outbox->path);
1586 if (info) {
1587 procmsg_msginfo_set_flags(info, MSG_RETRCPT_GOT, 0);
1588 procmsg_msginfo_free(&info);
1592 g_free(orig_msg_id);
1593 g_free(disp);
1594 bail:
1595 for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1596 g_free(hentry[i].body);
1597 hentry[i].body = NULL;
1601 #define GET_HEADERS() { \
1602 procheader_get_header_fields(fp, hentry); \
1603 if (hentry[0].body != NULL) { \
1604 tmp = conv_unmime_header(hentry[0].body, NULL, FALSE); \
1605 g_free(hentry[0].body); \
1606 hentry[0].body = tmp; \
1608 if (hentry[2].body != NULL) { \
1609 tmp = conv_unmime_header(hentry[2].body, NULL, FALSE); \
1610 g_free(hentry[2].body); \
1611 hentry[2].body = tmp; \
1613 if (hentry[4].body != NULL) { \
1614 tmp = conv_unmime_header(hentry[4].body, NULL, FALSE); \
1615 g_free(hentry[4].body); \
1616 hentry[4].body = tmp; \
1618 if (hentry[5].body != NULL) { \
1619 tmp = conv_unmime_header(hentry[5].body, NULL, FALSE); \
1620 g_free(hentry[5].body); \
1621 hentry[5].body = tmp; \
1623 if (hentry[6].body != NULL) { \
1624 tmp = conv_unmime_header(hentry[6].body, NULL, FALSE); \
1625 g_free(hentry[6].body); \
1626 hentry[6].body = tmp; \
1628 if (hentry[7].body != NULL) { \
1629 tmp = conv_unmime_header(hentry[7].body, NULL, FALSE); \
1630 g_free(hentry[7].body); \
1631 hentry[7].body = tmp; \
1635 static void procmime_parse_multipart(MimeInfo *mimeinfo, gboolean short_scan)
1637 HeaderEntry hentry[] = {{"Content-Type:", NULL, TRUE},
1638 {"Content-Transfer-Encoding:",
1639 NULL, FALSE},
1640 {"Content-Description:",
1641 NULL, TRUE},
1642 {"Content-ID:",
1643 NULL, TRUE},
1644 {"Content-Disposition:",
1645 NULL, TRUE},
1646 {"Content-Location:",
1647 NULL, TRUE},
1648 {"Original-Message-ID:",
1649 NULL, TRUE},
1650 {"Disposition:",
1651 NULL, TRUE},
1652 {NULL, NULL, FALSE}};
1653 gchar *tmp;
1654 gchar *boundary;
1655 gint boundary_len = 0, lastoffset = -1, i;
1656 gchar buf[BUFFSIZE];
1657 FILE *fp;
1658 int result = 0;
1659 gboolean start_found = FALSE;
1660 gboolean end_found = FALSE;
1662 boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
1663 if (!boundary)
1664 return;
1665 boundary_len = strlen(boundary);
1667 procmime_decode_content(mimeinfo);
1669 fp = procmime_fopen(mimeinfo->data.filename, "rb");
1670 if (fp == NULL) {
1671 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1672 return;
1675 if (fseek(fp, mimeinfo->offset, SEEK_SET) < 0) {
1676 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
1677 procmime_fclose(fp);
1678 return;
1681 while (SC_FGETS(buf, sizeof(buf), fp) != NULL && result == 0) {
1682 if (ftell(fp) - 1 > (mimeinfo->offset + mimeinfo->length))
1683 break;
1685 if (IS_BOUNDARY(buf, boundary, boundary_len)) {
1686 start_found = TRUE;
1688 if (lastoffset != -1) {
1689 gint len = (ftell(fp) - strlen(buf)) - lastoffset - 1;
1690 if (len < 0)
1691 len = 0;
1692 result = procmime_parse_mimepart(mimeinfo,
1693 hentry[0].body, hentry[1].body,
1694 hentry[2].body, hentry[3].body,
1695 hentry[4].body, hentry[5].body,
1696 hentry[6].body, hentry[7].body,
1697 mimeinfo->data.filename, lastoffset,
1698 len, short_scan);
1699 if (result == 1 && short_scan)
1700 break;
1704 if (buf[2 + boundary_len] == '-' &&
1705 buf[2 + boundary_len + 1] == '-') {
1706 end_found = TRUE;
1707 break;
1709 for (i = 0; i < (sizeof hentry / sizeof hentry[0]) ; i++) {
1710 g_free(hentry[i].body);
1711 hentry[i].body = NULL;
1713 GET_HEADERS();
1714 lastoffset = ftell(fp);
1718 if (start_found && !end_found && lastoffset != -1) {
1719 gint len = (ftell(fp) - strlen(buf)) - lastoffset - 1;
1721 if (len >= 0) {
1722 result = procmime_parse_mimepart(mimeinfo,
1723 hentry[0].body, hentry[1].body,
1724 hentry[2].body, hentry[3].body,
1725 hentry[4].body, hentry[5].body,
1726 hentry[6].body, hentry[7].body,
1727 mimeinfo->data.filename, lastoffset,
1728 len, short_scan);
1730 mimeinfo->broken = TRUE;
1733 for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1734 g_free(hentry[i].body);
1735 hentry[i].body = NULL;
1737 procmime_fclose(fp);
1740 static void parse_parameters(const gchar *parameters, GHashTable *table)
1742 gchar *params, *param, *next;
1743 GSList *convlist = NULL, *concatlist = NULL, *cur;
1745 params = g_strdup(parameters);
1746 param = params;
1747 next = params;
1748 for (; next != NULL; param = next) {
1749 gchar *attribute, *value, *tmp, *down_attr, *orig_down_attr;
1750 gint len;
1751 gboolean convert = FALSE;
1753 next = strchr_with_skip_quote(param, '"', ';');
1754 if (next != NULL) {
1755 next[0] = '\0';
1756 next++;
1759 g_strstrip(param);
1761 attribute = param;
1762 value = strchr(attribute, '=');
1763 if (value == NULL)
1764 continue;
1766 value[0] = '\0';
1767 value++;
1768 while (value[0] != '\0' && value[0] == ' ')
1769 value++;
1771 down_attr = g_utf8_strdown(attribute, -1);
1772 orig_down_attr = down_attr;
1774 len = down_attr ? strlen(down_attr):0;
1775 if (len > 0 && down_attr[len - 1] == '*') {
1776 gchar *srcpos, *dstpos, *endpos;
1778 convert = TRUE;
1779 down_attr[len - 1] = '\0';
1781 srcpos = value;
1782 dstpos = value;
1783 endpos = value + strlen(value);
1784 while (srcpos < endpos) {
1785 if (*srcpos != '%')
1786 *dstpos = *srcpos;
1787 else {
1788 guchar dstvalue;
1790 if (!get_hex_value(&dstvalue, srcpos[1], srcpos[2]))
1791 *dstpos = '?';
1792 else
1793 *dstpos = dstvalue;
1794 srcpos += 2;
1796 srcpos++;
1797 dstpos++;
1799 *dstpos = '\0';
1800 if (value[0] == '"')
1801 extract_quote(value, '"');
1802 } else {
1803 if (value[0] == '"')
1804 extract_quote(value, '"');
1805 else if ((tmp = strchr(value, ' ')) != NULL)
1806 *tmp = '\0';
1809 if (down_attr) {
1810 while (down_attr[0] == ' ')
1811 down_attr++;
1812 while (down_attr[strlen(down_attr)-1] == ' ')
1813 down_attr[strlen(down_attr)-1] = '\0';
1816 while (value[0] != '\0' && value[0] == ' ')
1817 value++;
1818 while (value[strlen(value)-1] == ' ')
1819 value[strlen(value)-1] = '\0';
1821 if (down_attr && strrchr(down_attr, '*') != NULL) {
1822 gchar *tmpattr;
1824 tmpattr = g_strdup(down_attr);
1825 tmp = strrchr(tmpattr, '*');
1826 tmp[0] = '\0';
1828 if ((tmp[1] == '0') && (tmp[2] == '\0') &&
1829 (g_slist_find_custom(concatlist, down_attr, (GCompareFunc)g_strcmp0) == NULL))
1830 concatlist = g_slist_prepend(concatlist, g_strdup(tmpattr));
1832 if (convert && (g_slist_find_custom(convlist, tmpattr, (GCompareFunc)g_strcmp0) == NULL))
1833 convlist = g_slist_prepend(convlist, g_strdup(tmpattr));
1835 g_free(tmpattr);
1836 } else if (convert) {
1837 if (g_slist_find_custom(convlist, down_attr, (GCompareFunc)g_strcmp0) == NULL)
1838 convlist = g_slist_prepend(convlist, g_strdup(down_attr));
1841 if (g_hash_table_lookup(table, down_attr) == NULL)
1842 g_hash_table_insert(table, g_strdup(down_attr), g_strdup(value));
1843 g_free(orig_down_attr);
1846 for (cur = concatlist; cur != NULL; cur = g_slist_next(cur)) {
1847 gchar *attribute, *attrwnum, *partvalue;
1848 gint n = 0;
1849 GString *value;
1851 attribute = (gchar *) cur->data;
1852 value = g_string_sized_new(64);
1854 attrwnum = g_strdup_printf("%s*%d", attribute, n);
1855 while ((partvalue = g_hash_table_lookup(table, attrwnum)) != NULL) {
1856 g_string_append(value, partvalue);
1858 g_hash_table_remove(table, attrwnum);
1859 g_free(attrwnum);
1860 n++;
1861 attrwnum = g_strdup_printf("%s*%d", attribute, n);
1863 g_free(attrwnum);
1865 g_hash_table_insert(table, g_strdup(attribute), g_strdup(value->str));
1866 g_string_free(value, TRUE);
1868 slist_free_strings_full(concatlist);
1870 for (cur = convlist; cur != NULL; cur = g_slist_next(cur)) {
1871 gchar *attribute, *key, *value;
1872 gchar *charset, *lang, *oldvalue, *newvalue;
1874 attribute = (gchar *) cur->data;
1875 if (!g_hash_table_lookup_extended(
1876 table, attribute, (gpointer *)(gchar *) &key, (gpointer *)(gchar *) &value))
1877 continue;
1879 charset = value;
1880 if (charset == NULL)
1881 continue;
1882 lang = strchr(charset, '\'');
1883 if (lang == NULL)
1884 continue;
1885 lang[0] = '\0';
1886 lang++;
1887 oldvalue = strchr(lang, '\'');
1888 if (oldvalue == NULL)
1889 continue;
1890 oldvalue[0] = '\0';
1891 oldvalue++;
1893 newvalue = conv_codeset_strdup(oldvalue, charset, CS_UTF_8);
1895 g_hash_table_remove(table, attribute);
1896 g_free(key);
1897 g_free(value);
1899 g_hash_table_insert(table, g_strdup(attribute), newvalue);
1901 slist_free_strings_full(convlist);
1903 g_free(params);
1906 static void procmime_parse_content_type(const gchar *content_type, MimeInfo *mimeinfo)
1908 cm_return_if_fail(content_type != NULL);
1909 cm_return_if_fail(mimeinfo != NULL);
1911 /* RFC 2045, page 13 says that the mime subtype is MANDATORY;
1912 * if it's not available we use the default Content-Type */
1913 if ((content_type[0] == '\0') || (strchr(content_type, '/') == NULL)) {
1914 mimeinfo->type = MIMETYPE_TEXT;
1915 mimeinfo->subtype = g_strdup("plain");
1916 if (g_hash_table_lookup(mimeinfo->typeparameters,
1917 "charset") == NULL) {
1918 g_hash_table_insert(mimeinfo->typeparameters,
1919 g_strdup("charset"),
1920 g_strdup(
1921 conv_get_locale_charset_str_no_utf8()));
1923 } else {
1924 gchar *type, *subtype, *params;
1926 type = g_strdup(content_type);
1927 subtype = strchr(type, '/') + 1;
1928 *(subtype - 1) = '\0';
1929 if ((params = strchr(subtype, ';')) != NULL) {
1930 params[0] = '\0';
1931 params++;
1934 mimeinfo->type = procmime_get_media_type(type);
1935 mimeinfo->subtype = g_strstrip(g_strdup(subtype));
1937 /* Get mimeinfo->typeparameters */
1938 if (params != NULL)
1939 parse_parameters(params, mimeinfo->typeparameters);
1941 g_free(type);
1945 static void procmime_parse_content_disposition(const gchar *content_disposition, MimeInfo *mimeinfo)
1947 gchar *tmp, *params;
1949 cm_return_if_fail(content_disposition != NULL);
1950 cm_return_if_fail(mimeinfo != NULL);
1952 tmp = g_strdup(content_disposition);
1953 if ((params = strchr(tmp, ';')) != NULL) {
1954 params[0] = '\0';
1955 params++;
1957 g_strstrip(tmp);
1959 if (!g_ascii_strcasecmp(tmp, "inline"))
1960 mimeinfo->disposition = DISPOSITIONTYPE_INLINE;
1961 else if (!g_ascii_strcasecmp(tmp, "attachment"))
1962 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1963 else
1964 mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1966 if (params != NULL)
1967 parse_parameters(params, mimeinfo->dispositionparameters);
1969 g_free(tmp);
1973 static void procmime_parse_content_encoding(const gchar *content_encoding, MimeInfo *mimeinfo)
1975 struct EncodingTable *enc_table;
1977 for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1978 if (g_ascii_strcasecmp(enc_table->str, content_encoding) == 0) {
1979 mimeinfo->encoding_type = enc_table->enc_type;
1980 return;
1983 mimeinfo->encoding_type = ENC_UNKNOWN;
1984 return;
1987 static GSList *registered_parsers = NULL;
1989 static MimeParser *procmime_get_mimeparser_for_type(MimeMediaType type, const gchar *sub_type)
1991 GSList *cur;
1992 for (cur = registered_parsers; cur; cur = cur->next) {
1993 MimeParser *parser = (MimeParser *)cur->data;
1994 if (parser->type == type && !strcmp2(parser->sub_type, sub_type))
1995 return parser;
1997 return NULL;
2000 void procmime_mimeparser_register(MimeParser *parser)
2002 if (!procmime_get_mimeparser_for_type(parser->type, parser->sub_type))
2003 registered_parsers = g_slist_append(registered_parsers, parser);
2007 void procmime_mimeparser_unregister(MimeParser *parser)
2009 registered_parsers = g_slist_remove(registered_parsers, parser);
2012 static gboolean procmime_mimeparser_parse(MimeParser *parser, MimeInfo *mimeinfo)
2014 cm_return_val_if_fail(parser->parse != NULL, FALSE);
2015 return parser->parse(parser, mimeinfo);
2018 static int procmime_parse_mimepart(MimeInfo *parent,
2019 gchar *content_type,
2020 gchar *content_encoding,
2021 gchar *content_description,
2022 gchar *content_id,
2023 gchar *content_disposition,
2024 gchar *content_location,
2025 const gchar *original_msgid,
2026 const gchar *disposition_notification_hdr,
2027 const gchar *filename,
2028 guint offset,
2029 guint length,
2030 gboolean short_scan)
2032 MimeInfo *mimeinfo;
2033 MimeParser *parser = NULL;
2034 gboolean parsed = FALSE;
2035 int result = 0;
2037 /* Create MimeInfo */
2038 mimeinfo = procmime_mimeinfo_new();
2039 mimeinfo->content = MIMECONTENT_FILE;
2041 if (parent != NULL) {
2042 if (g_node_depth(parent->node) > 32) {
2043 /* 32 is an arbitrary value
2044 * this avoids DOSsing ourselves
2045 * with enormous messages
2047 procmime_mimeinfo_free_all(&mimeinfo);
2048 return -1;
2050 g_node_append(parent->node, mimeinfo->node);
2052 mimeinfo->data.filename = g_strdup(filename);
2053 mimeinfo->offset = offset;
2054 mimeinfo->length = length;
2056 if (content_type != NULL) {
2057 g_strchomp(content_type);
2058 procmime_parse_content_type(content_type, mimeinfo);
2059 } else {
2060 mimeinfo->type = MIMETYPE_TEXT;
2061 mimeinfo->subtype = g_strdup("plain");
2062 if (g_hash_table_lookup(mimeinfo->typeparameters,
2063 "charset") == NULL) {
2064 g_hash_table_insert(mimeinfo->typeparameters,
2065 g_strdup("charset"),
2066 g_strdup(
2067 conv_get_locale_charset_str_no_utf8()));
2071 if (content_encoding != NULL) {
2072 g_strchomp(content_encoding);
2073 procmime_parse_content_encoding(content_encoding, mimeinfo);
2074 } else {
2075 mimeinfo->encoding_type = ENC_UNKNOWN;
2078 if (content_description != NULL)
2079 mimeinfo->description = g_strdup(content_description);
2080 else
2081 mimeinfo->description = NULL;
2083 if (content_id != NULL)
2084 mimeinfo->id = g_strdup(content_id);
2085 else
2086 mimeinfo->id = NULL;
2088 if (content_location != NULL)
2089 mimeinfo->location = g_strdup(content_location);
2090 else
2091 mimeinfo->location = NULL;
2093 if (content_disposition != NULL) {
2094 g_strchomp(content_disposition);
2095 procmime_parse_content_disposition(content_disposition, mimeinfo);
2096 } else
2097 mimeinfo->disposition = DISPOSITIONTYPE_UNKNOWN;
2099 /* Call parser for mime type */
2100 if ((parser = procmime_get_mimeparser_for_type(mimeinfo->type, mimeinfo->subtype)) != NULL) {
2101 parsed = procmime_mimeparser_parse(parser, mimeinfo);
2103 if (!parsed) {
2104 switch (mimeinfo->type) {
2105 case MIMETYPE_TEXT:
2106 if (g_ascii_strcasecmp(mimeinfo->subtype, "plain") == 0 && short_scan) {
2107 return 1;
2109 break;
2111 case MIMETYPE_MESSAGE:
2112 if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
2113 procmime_parse_message_rfc822(mimeinfo, short_scan);
2115 if (g_ascii_strcasecmp(mimeinfo->subtype, "disposition-notification") == 0) {
2116 procmime_parse_disposition_notification(mimeinfo,
2117 original_msgid, disposition_notification_hdr, short_scan);
2119 break;
2121 case MIMETYPE_MULTIPART:
2122 procmime_parse_multipart(mimeinfo, short_scan);
2123 break;
2125 case MIMETYPE_APPLICATION:
2126 if (g_ascii_strcasecmp(mimeinfo->subtype, "octet-stream") == 0
2127 && original_msgid && *original_msgid
2128 && disposition_notification_hdr && *disposition_notification_hdr) {
2129 procmime_parse_disposition_notification(mimeinfo,
2130 original_msgid, disposition_notification_hdr, short_scan);
2132 break;
2133 default:
2134 break;
2138 return result;
2141 static gchar *typenames[] = {
2142 "text",
2143 "image",
2144 "audio",
2145 "video",
2146 "application",
2147 "message",
2148 "multipart",
2149 "unknown",
2152 static gboolean output_func(GNode *node, gpointer data)
2154 guint i, depth;
2155 MimeInfo *mimeinfo = (MimeInfo *) node->data;
2157 depth = g_node_depth(node);
2158 for (i = 0; i < depth; i++)
2159 g_print(" ");
2160 g_print("%s/%s (offset:%d length:%d encoding: %d)\n", typenames[mimeinfo->type], mimeinfo->subtype, mimeinfo->offset, mimeinfo->length, mimeinfo->encoding_type);
2162 return FALSE;
2165 static void output_mime_structure(MimeInfo *mimeinfo, int indent)
2167 g_node_traverse(mimeinfo->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1, output_func, NULL);
2170 static MimeInfo *procmime_scan_file_with_offset(const gchar *filename, int offset, gboolean short_scan)
2172 MimeInfo *mimeinfo;
2173 GStatBuf buf;
2175 if (g_stat(filename, &buf) < 0) {
2176 FILE_OP_ERROR(filename, "stat");
2177 return NULL;
2180 mimeinfo = procmime_mimeinfo_new();
2181 mimeinfo->content = MIMECONTENT_FILE;
2182 mimeinfo->encoding_type = ENC_UNKNOWN;
2183 mimeinfo->type = MIMETYPE_MESSAGE;
2184 mimeinfo->subtype = g_strdup("rfc822");
2185 mimeinfo->data.filename = g_strdup(filename);
2186 mimeinfo->offset = offset;
2187 mimeinfo->length = buf.st_size - offset;
2189 procmime_parse_message_rfc822(mimeinfo, short_scan);
2190 if (debug_get_mode())
2191 output_mime_structure(mimeinfo, 0);
2193 return mimeinfo;
2196 static MimeInfo *procmime_scan_file_full(const gchar *filename, gboolean short_scan)
2198 MimeInfo *mimeinfo;
2200 cm_return_val_if_fail(filename != NULL, NULL);
2202 mimeinfo = procmime_scan_file_with_offset(filename, 0, short_scan);
2204 return mimeinfo;
2207 MimeInfo *procmime_scan_file(const gchar *filename)
2209 return procmime_scan_file_full(filename, FALSE);
2212 static MimeInfo *procmime_scan_file_short(const gchar *filename)
2214 return procmime_scan_file_full(filename, TRUE);
2217 static MimeInfo *procmime_scan_queue_file_full(const gchar *filename, gboolean short_scan)
2219 FILE *fp;
2220 MimeInfo *mimeinfo;
2221 gchar buf[BUFFSIZE];
2222 gint offset = 0;
2224 cm_return_val_if_fail(filename != NULL, NULL);
2226 /* Open file */
2227 if ((fp = procmime_fopen(filename, "rb")) == NULL)
2228 return NULL;
2229 /* Skip queue header */
2230 while (SC_FGETS(buf, sizeof(buf), fp) != NULL) {
2231 /* new way */
2232 if ((!strncmp(buf, "X-Claws-End-Special-Headers: 1",
2233 strlen("X-Claws-End-Special-Headers:"))) ||
2234 (!strncmp(buf, "X-Sylpheed-End-Special-Headers: 1",
2235 strlen("X-Sylpheed-End-Special-Headers:"))))
2236 break;
2237 /* old way */
2238 if (buf[0] == '\r' || buf[0] == '\n') break;
2239 /* from other mailers */
2240 if (!strncmp(buf, "Date: ", 6)
2241 || !strncmp(buf, "To: ", 4)
2242 || !strncmp(buf, "From: ", 6)
2243 || !strncmp(buf, "Subject: ", 9)) {
2244 rewind(fp);
2245 break;
2248 offset = ftell(fp);
2249 procmime_fclose(fp);
2251 mimeinfo = procmime_scan_file_with_offset(filename, offset, short_scan);
2253 return mimeinfo;
2256 MimeInfo *procmime_scan_queue_file(const gchar *filename)
2258 return procmime_scan_queue_file_full(filename, FALSE);
2261 static MimeInfo *procmime_scan_queue_file_short(const gchar *filename)
2263 return procmime_scan_queue_file_full(filename, TRUE);
2266 typedef enum {
2267 ENC_AS_TOKEN,
2268 ENC_AS_QUOTED_STRING,
2269 ENC_AS_EXTENDED,
2270 ENC_AS_ENCWORD
2271 } EncodeAs;
2273 typedef struct _ParametersData {
2274 FILE *fp;
2275 guint len;
2276 gint error;
2277 } ParametersData;
2279 static void write_parameters(gpointer key, gpointer value, gpointer user_data)
2281 gchar *param = key;
2282 gchar *val = value, *valpos, *tmp;
2283 ParametersData *pdata = (ParametersData *)user_data;
2284 GString *buf = g_string_new("");
2285 gint len;
2287 EncodeAs encas = ENC_AS_TOKEN;
2289 for (valpos = val; *valpos != 0; valpos++) {
2290 if (!IS_ASCII(*valpos)) {
2291 encas = ENC_AS_ENCWORD;
2292 break;
2295 /* CTLs */
2296 if (((*valpos >= 0) && (*valpos < 037)) || (*valpos == 0177)) {
2297 encas = ENC_AS_QUOTED_STRING;
2298 continue;
2301 /* tspecials + SPACE */
2302 switch (*valpos) {
2303 case ' ':
2304 case '(':
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 encas = ENC_AS_QUOTED_STRING;
2320 continue;
2324 switch (encas) {
2325 case ENC_AS_TOKEN:
2326 g_string_append_printf(buf, "%s=%s", param, val);
2327 break;
2329 case ENC_AS_QUOTED_STRING:
2330 g_string_append_printf(buf, "%s=\"%s\"", param, val);
2331 break;
2333 #if 0 /* we don't use that for now */
2334 case ENC_AS_EXTENDED:
2335 if (!g_utf8_validate(val, -1, NULL))
2336 g_string_append_printf(buf, "%s*=%s''", param,
2337 conv_get_locale_charset_str());
2338 else
2339 g_string_append_printf(buf, "%s*=%s''", param,
2340 CS_INTERNAL);
2341 for (valpos = val; *valpos != '\0'; valpos++) {
2342 if (IS_ASCII(*valpos) && isalnum(*valpos)) {
2343 g_string_append_printf(buf, "%c", *valpos);
2344 } else {
2345 gchar hexstr[3] = "XX";
2346 get_hex_str(hexstr, *valpos);
2347 g_string_append_printf(buf, "%%%s", hexstr);
2350 break;
2351 #else
2352 case ENC_AS_EXTENDED:
2353 debug_print("Unhandled ENC_AS_EXTENDED.\n");
2354 break;
2355 #endif
2356 case ENC_AS_ENCWORD:
2357 len = MAX(strlen(val)*6, 512);
2358 tmp = g_malloc(len+1);
2359 codeconv_set_strict(TRUE);
2360 conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2361 prefs_common.outgoing_charset);
2362 codeconv_set_strict(FALSE);
2363 if (!tmp || !*tmp) {
2364 codeconv_set_strict(TRUE);
2365 conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2366 conv_get_outgoing_charset_str());
2367 codeconv_set_strict(FALSE);
2369 if (!tmp || !*tmp) {
2370 codeconv_set_strict(TRUE);
2371 conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2372 CS_UTF_8);
2373 codeconv_set_strict(FALSE);
2375 if (!tmp || !*tmp) {
2376 conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2377 CS_UTF_8);
2379 g_string_append_printf(buf, "%s=\"%s\"", param, tmp);
2380 g_free(tmp);
2381 break;
2385 if (buf->str && strlen(buf->str)) {
2386 tmp = strstr(buf->str, "\n");
2387 if (tmp)
2388 len = (tmp - buf->str);
2389 else
2390 len = strlen(buf->str);
2391 if (pdata->len + len > 76) {
2392 if (fprintf(pdata->fp, ";\n %s", buf->str) < 0)
2393 pdata->error = TRUE;
2394 pdata->len = strlen(buf->str) + 1;
2395 } else {
2396 if (fprintf(pdata->fp, "; %s", buf->str) < 0)
2397 pdata->error = TRUE;
2398 pdata->len += strlen(buf->str) + 2;
2401 g_string_free(buf, TRUE);
2404 #define TRY(func) { \
2405 if (!(func)) { \
2406 return -1; \
2410 int procmime_write_mime_header(MimeInfo *mimeinfo, FILE *fp)
2412 struct TypeTable *type_table;
2413 ParametersData *pdata = g_new0(ParametersData, 1);
2414 debug_print("procmime_write_mime_header\n");
2416 pdata->fp = fp;
2417 pdata->error = FALSE;
2418 for (type_table = mime_type_table; type_table->str != NULL; type_table++)
2419 if (mimeinfo->type == type_table->type) {
2420 gchar *buf = g_strdup_printf(
2421 "Content-Type: %s/%s", type_table->str, mimeinfo->subtype);
2422 if (fprintf(fp, "%s", buf) < 0) {
2423 g_free(buf);
2424 g_free(pdata);
2425 return -1;
2427 pdata->len = strlen(buf);
2428 g_free(buf);
2429 break;
2431 g_hash_table_foreach(mimeinfo->typeparameters, write_parameters, pdata);
2432 if (pdata->error == TRUE) {
2433 g_free(pdata);
2434 return -1;
2436 g_free(pdata);
2438 TRY(fprintf(fp, "\n") >= 0);
2440 if (mimeinfo->encoding_type != ENC_UNKNOWN)
2441 TRY(fprintf(fp, "Content-Transfer-Encoding: %s\n", procmime_get_encoding_str(mimeinfo->encoding_type)) >= 0);
2443 if (mimeinfo->description != NULL)
2444 TRY(fprintf(fp, "Content-Description: %s\n", mimeinfo->description) >= 0);
2446 if (mimeinfo->id != NULL)
2447 TRY(fprintf(fp, "Content-ID: %s\n", mimeinfo->id) >= 0);
2449 if (mimeinfo->location != NULL)
2450 TRY(fprintf(fp, "Content-Location: %s\n", mimeinfo->location) >= 0);
2452 if (mimeinfo->disposition != DISPOSITIONTYPE_UNKNOWN) {
2453 ParametersData *pdata = g_new0(ParametersData, 1);
2454 gchar *buf = NULL;
2455 if (mimeinfo->disposition == DISPOSITIONTYPE_INLINE)
2456 buf = g_strdup("Content-Disposition: inline");
2457 else if (mimeinfo->disposition == DISPOSITIONTYPE_ATTACHMENT)
2458 buf = g_strdup("Content-Disposition: attachment");
2459 else
2460 buf = g_strdup("Content-Disposition: unknown");
2462 if (fprintf(fp, "%s", buf) < 0) {
2463 g_free(buf);
2464 g_free(pdata);
2465 return -1;
2467 pdata->len = strlen(buf);
2468 g_free(buf);
2470 pdata->fp = fp;
2471 pdata->error = FALSE;
2472 g_hash_table_foreach(mimeinfo->dispositionparameters, write_parameters, pdata);
2473 if (pdata->error == TRUE) {
2474 g_free(pdata);
2475 return -1;
2477 g_free(pdata);
2478 TRY(fprintf(fp, "\n") >= 0);
2481 TRY(fprintf(fp, "\n") >= 0);
2483 return 0;
2486 static gint procmime_write_message_rfc822(MimeInfo *mimeinfo, FILE *fp)
2488 FILE *infp;
2489 GNode *childnode;
2490 MimeInfo *child;
2491 gchar buf[BUFFSIZE];
2492 gboolean skip = FALSE;;
2493 size_t len;
2495 debug_print("procmime_write_message_rfc822\n");
2497 /* write header */
2498 switch (mimeinfo->content) {
2499 case MIMECONTENT_FILE:
2500 if ((infp = procmime_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2501 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2502 return -1;
2504 if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
2505 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
2506 procmime_fclose(infp);
2507 return -1;
2509 while (SC_FGETS(buf, sizeof(buf), infp) == buf) {
2510 strcrchomp(buf);
2511 if (buf[0] == '\n' && buf[1] == '\0')
2512 break;
2513 if (skip && (buf[0] == ' ' || buf[0] == '\t'))
2514 continue;
2515 if (g_ascii_strncasecmp(buf, "MIME-Version:", 13) == 0 ||
2516 g_ascii_strncasecmp(buf, "Content-Type:", 13) == 0 ||
2517 g_ascii_strncasecmp(buf, "Content-Transfer-Encoding:", 26) == 0 ||
2518 g_ascii_strncasecmp(buf, "Content-Description:", 20) == 0 ||
2519 g_ascii_strncasecmp(buf, "Content-ID:", 11) == 0 ||
2520 g_ascii_strncasecmp(buf, "Content-Location:", 17) == 0 ||
2521 g_ascii_strncasecmp(buf, "Content-Disposition:", 20) == 0) {
2522 skip = TRUE;
2523 continue;
2525 len = strlen(buf);
2526 if (SC_FWRITE(buf, sizeof(gchar), len, fp) < len) {
2527 g_warning("failed to dump %zd bytes from file", len);
2528 procmime_fclose(infp);
2529 return -1;
2531 skip = FALSE;
2533 procmime_fclose(infp);
2534 break;
2536 case MIMECONTENT_MEM:
2537 len = strlen(mimeinfo->data.mem);
2538 if (SC_FWRITE(mimeinfo->data.mem, sizeof(gchar), len, fp) < len) {
2539 g_warning("failed to dump %zd bytes from mem", len);
2540 return -1;
2542 break;
2544 default:
2545 break;
2548 childnode = mimeinfo->node->children;
2549 if (childnode == NULL)
2550 return -1;
2552 child = (MimeInfo *) childnode->data;
2553 if (fprintf(fp, "MIME-Version: 1.0\n") < 0) {
2554 g_warning("failed to write mime version");
2555 return -1;
2557 if (procmime_write_mime_header(child, fp) < 0)
2558 return -1;
2559 return procmime_write_mimeinfo(child, fp);
2562 static gint procmime_write_multipart(MimeInfo *mimeinfo, FILE *fp)
2564 FILE *infp;
2565 GNode *childnode;
2566 gchar *boundary, *str, *str2;
2567 gchar buf[BUFFSIZE];
2568 gboolean firstboundary;
2569 size_t len;
2571 debug_print("procmime_write_multipart\n");
2573 boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
2575 switch (mimeinfo->content) {
2576 case MIMECONTENT_FILE:
2577 if ((infp = procmime_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2578 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2579 return -1;
2581 if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
2582 FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
2583 procmime_fclose(infp);
2584 return -1;
2586 while (SC_FGETS(buf, sizeof(buf), infp) == buf) {
2587 if (IS_BOUNDARY(buf, boundary, strlen(boundary)))
2588 break;
2589 len = strlen(buf);
2590 if (SC_FWRITE(buf, sizeof(gchar), len, fp) < len) {
2591 g_warning("failed to write %zd", len);
2592 procmime_fclose(infp);
2593 return -1;
2596 procmime_fclose(infp);
2597 break;
2599 case MIMECONTENT_MEM:
2600 str = g_strdup(mimeinfo->data.mem);
2601 if (((str2 = strstr(str, boundary)) != NULL) && ((str2 - str) >= 2) &&
2602 (*(str2 - 1) == '-') && (*(str2 - 2) == '-'))
2603 *(str2 - 2) = '\0';
2604 len = strlen(str);
2605 if (SC_FWRITE(str, sizeof(gchar), len, fp) < len) {
2606 g_warning("failed to write %zd from mem", len);
2607 g_free(str);
2608 return -1;
2610 g_free(str);
2611 break;
2613 default:
2614 break;
2617 childnode = mimeinfo->node->children;
2618 firstboundary = TRUE;
2619 while (childnode != NULL) {
2620 MimeInfo *child = childnode->data;
2622 if (firstboundary)
2623 firstboundary = FALSE;
2624 else
2625 TRY(fprintf(fp, "\n") >= 0);
2627 TRY(fprintf(fp, "--%s\n", boundary) >= 0);
2629 if (procmime_write_mime_header(child, fp) < 0)
2630 return -1;
2631 if (procmime_write_mimeinfo(child, fp) < 0)
2632 return -1;
2634 childnode = g_node_next_sibling(childnode);
2636 TRY(fprintf(fp, "\n--%s--\n", boundary) >= 0);
2638 return 0;
2641 gint procmime_write_mimeinfo(MimeInfo *mimeinfo, FILE *fp)
2643 FILE *infp;
2644 size_t len;
2645 debug_print("procmime_write_mimeinfo\n");
2647 if (G_NODE_IS_LEAF(mimeinfo->node)) {
2648 switch (mimeinfo->content) {
2649 case MIMECONTENT_FILE:
2650 if ((infp = procmime_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2651 FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
2652 return -1;
2654 copy_file_part_to_fp(infp, mimeinfo->offset, mimeinfo->length, fp);
2655 procmime_fclose(infp);
2656 return 0;
2658 case MIMECONTENT_MEM:
2659 len = strlen(mimeinfo->data.mem);
2660 if (SC_FWRITE(mimeinfo->data.mem, sizeof(gchar), len, fp) < len)
2661 return -1;
2662 return 0;
2664 default:
2665 return 0;
2667 } else {
2668 /* Call writer for mime type */
2669 switch (mimeinfo->type) {
2670 case MIMETYPE_MESSAGE:
2671 if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
2672 return procmime_write_message_rfc822(mimeinfo, fp);
2674 break;
2676 case MIMETYPE_MULTIPART:
2677 return procmime_write_multipart(mimeinfo, fp);
2679 default:
2680 break;
2683 return -1;
2686 return 0;
2689 gchar *procmime_get_part_file_name(MimeInfo *mimeinfo)
2691 gchar *base;
2693 if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
2694 base = g_strdup("mimetmp.html");
2695 else {
2696 const gchar *basetmp;
2697 gchar *basename;
2699 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
2700 if (basetmp == NULL)
2701 basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
2702 if (basetmp == NULL)
2703 basetmp = "mimetmp";
2704 basename = g_path_get_basename(basetmp);
2705 if (*basename == '\0') {
2706 g_free(basename);
2707 basename = g_strdup("mimetmp");
2709 base = conv_filename_from_utf8(basename);
2710 g_free(basename);
2711 subst_for_shellsafe_filename(base);
2714 return base;