1 /*
2  * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2020 the Claws Mail Team and Hiroyuki Yamamoto
4  *
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.
9  *
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.
14  *
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/>.
17  */
18 
19 #ifdef HAVE_CONFIG_H
20 #  include "config.h"
21 #include "claws-features.h"
22 #endif
23 
24 #include <stdio.h>
25 
26 #include "defs.h"
27 
28 #include <glib.h>
29 #include <glib/gi18n.h>
30 #include <string.h>
31 #if HAVE_LOCALE_H
32 #  include <locale.h>
33 #endif
34 #include <ctype.h>
35 #include <sys/types.h>
36 #include <sys/stat.h>
37 #include <unistd.h>
38 #include <errno.h>
39 
40 #include "procmime.h"
41 #include "procheader.h"
42 #include "quoted-printable.h"
43 #include "uuencode.h"
44 #include "unmime.h"
45 #include "html.h"
46 #include "enriched.h"
47 #include "codeconv.h"
48 #include "utils.h"
49 #include "prefs_common.h"
50 #include "prefs_gtk.h"
51 #include "alertpanel.h"
52 #include "timing.h"
53 #include "privacy.h"
54 #include "account.h"
55 #include "file-utils.h"
56 
57 static GHashTable *procmime_get_mime_type_table	(void);
58 static MimeInfo *procmime_scan_file_short(const gchar *filename);
59 static MimeInfo *procmime_scan_queue_file_short(const gchar *filename);
60 static MimeInfo *procmime_scan_queue_file_full(const gchar *filename, gboolean short_scan);
61 
procmime_mimeinfo_new(void)62 MimeInfo *procmime_mimeinfo_new(void)
63 {
64 	MimeInfo *mimeinfo;
65 
66 	mimeinfo = g_new0(MimeInfo, 1);
67 
68 	mimeinfo->content	 = MIMECONTENT_EMPTY;
69 	mimeinfo->data.filename	 = NULL;
70 
71 	mimeinfo->type     	 = MIMETYPE_UNKNOWN;
72 	mimeinfo->encoding_type  = ENC_UNKNOWN;
73 	mimeinfo->typeparameters = g_hash_table_new(g_str_hash, g_str_equal);
74 
75 	mimeinfo->disposition	 = DISPOSITIONTYPE_UNKNOWN;
76 	mimeinfo->dispositionparameters
77 				 = g_hash_table_new(g_str_hash, g_str_equal);
78 
79 	mimeinfo->node           = g_node_new(mimeinfo);
80 
81 	return mimeinfo;
82 }
83 
procmime_mimeinfo_parameters_destroy(gpointer key,gpointer value,gpointer user_data)84 static gboolean procmime_mimeinfo_parameters_destroy(gpointer key, gpointer value, gpointer user_data)
85 {
86 	g_free(key);
87 	g_free(value);
88 
89 	return TRUE;
90 }
91 
92 static gchar *forced_charset = NULL;
93 
procmime_force_charset(const gchar * str)94 void procmime_force_charset(const gchar *str)
95 {
96 	g_free(forced_charset);
97 	forced_charset = NULL;
98 	if (str)
99 		forced_charset = g_strdup(str);
100 }
101 
102 static EncodingType forced_encoding = 0;
103 
procmime_force_encoding(EncodingType encoding)104 void procmime_force_encoding(EncodingType encoding)
105 {
106 	forced_encoding = encoding;
107 }
108 
free_func(GNode * node,gpointer data)109 static gboolean free_func(GNode *node, gpointer data)
110 {
111 	MimeInfo *mimeinfo = (MimeInfo *) node->data;
112 
113 	switch (mimeinfo->content) {
114 	case MIMECONTENT_FILE:
115 		if (mimeinfo->tmp)
116 			claws_unlink(mimeinfo->data.filename);
117 		g_free(mimeinfo->data.filename);
118 		break;
119 
120 	case MIMECONTENT_MEM:
121 		if (mimeinfo->tmp)
122 			g_free(mimeinfo->data.mem);
123 	default:
124 		break;
125 	}
126 
127 	g_free(mimeinfo->subtype);
128 	g_free(mimeinfo->description);
129 	g_free(mimeinfo->id);
130 	g_free(mimeinfo->location);
131 
132 	g_hash_table_foreach_remove(mimeinfo->typeparameters,
133 		procmime_mimeinfo_parameters_destroy, NULL);
134 	g_hash_table_destroy(mimeinfo->typeparameters);
135 	g_hash_table_foreach_remove(mimeinfo->dispositionparameters,
136 		procmime_mimeinfo_parameters_destroy, NULL);
137 	g_hash_table_destroy(mimeinfo->dispositionparameters);
138 
139 	if (mimeinfo->privacy)
140 		privacy_free_privacydata(mimeinfo->privacy);
141 
142 	g_free(mimeinfo);
143 
144 	return FALSE;
145 }
146 
procmime_mimeinfo_free_all(MimeInfo ** mimeinfo_ptr)147 void procmime_mimeinfo_free_all(MimeInfo **mimeinfo_ptr)
148 {
149 	MimeInfo *mimeinfo = *mimeinfo_ptr;
150 	GNode *node;
151 
152 	if (!mimeinfo)
153 		return;
154 
155 	node = mimeinfo->node;
156 	g_node_traverse(node, G_IN_ORDER, G_TRAVERSE_ALL, -1, free_func, NULL);
157 
158 	g_node_destroy(node);
159 
160 	*mimeinfo_ptr = NULL;
161 }
162 
procmime_mimeinfo_parent(MimeInfo * mimeinfo)163 MimeInfo *procmime_mimeinfo_parent(MimeInfo *mimeinfo)
164 {
165 	cm_return_val_if_fail(mimeinfo != NULL, NULL);
166 	cm_return_val_if_fail(mimeinfo->node != NULL, NULL);
167 
168 	if (mimeinfo->node->parent == NULL)
169 		return NULL;
170 	return (MimeInfo *) mimeinfo->node->parent->data;
171 }
172 
procmime_mimeinfo_next(MimeInfo * mimeinfo)173 MimeInfo *procmime_mimeinfo_next(MimeInfo *mimeinfo)
174 {
175 	cm_return_val_if_fail(mimeinfo != NULL, NULL);
176 	cm_return_val_if_fail(mimeinfo->node != NULL, NULL);
177 
178 	if (mimeinfo->node->children)
179 		return (MimeInfo *) mimeinfo->node->children->data;
180 	if (mimeinfo->node->next)
181 		return (MimeInfo *) mimeinfo->node->next->data;
182 
183 	if (mimeinfo->node->parent == NULL)
184 		return NULL;
185 
186 	while (mimeinfo->node->parent != NULL) {
187 		mimeinfo = (MimeInfo *) mimeinfo->node->parent->data;
188 		if (mimeinfo->node->next)
189 			return (MimeInfo *) mimeinfo->node->next->data;
190 	}
191 
192 	return NULL;
193 }
194 
procmime_scan_message(MsgInfo * msginfo)195 MimeInfo *procmime_scan_message(MsgInfo *msginfo)
196 {
197 	gchar *filename;
198 	MimeInfo *mimeinfo;
199 
200     	filename = procmsg_get_message_file_path(msginfo);
201 	if (!filename || !is_file_exist(filename)) {
202 		g_free(filename);
203 		return NULL;
204 	}
205 
206 	if (!folder_has_parent_of_type(msginfo->folder, F_QUEUE) &&
207 	    !folder_has_parent_of_type(msginfo->folder, F_DRAFT))
208 		mimeinfo = procmime_scan_file(filename);
209 	else
210 		mimeinfo = procmime_scan_queue_file(filename);
211 	g_free(filename);
212 
213 	return mimeinfo;
214 }
215 
procmime_scan_message_short(MsgInfo * msginfo)216 MimeInfo *procmime_scan_message_short(MsgInfo *msginfo)
217 {
218 	gchar *filename;
219 	MimeInfo *mimeinfo;
220 
221 	filename = procmsg_get_message_file_path(msginfo);
222 	if (!filename || !is_file_exist(filename)) {
223 		g_free(filename);
224 		return NULL;
225 	}
226 
227 	if (!folder_has_parent_of_type(msginfo->folder, F_QUEUE) &&
228 	    !folder_has_parent_of_type(msginfo->folder, F_DRAFT))
229 		mimeinfo = procmime_scan_file_short(filename);
230 	else
231 		mimeinfo = procmime_scan_queue_file_short(filename);
232 	g_free(filename);
233 
234 	return mimeinfo;
235 }
236 
237 enum
238 {
239 	H_CONTENT_TRANSFER_ENCODING = 0,
240 	H_CONTENT_TYPE		    = 1,
241 	H_CONTENT_DISPOSITION	    = 2,
242 	H_CONTENT_DESCRIPTION	    = 3,
243 	H_SUBJECT              	    = 4
244 };
245 
procmime_mimeinfo_get_parameter(MimeInfo * mimeinfo,const gchar * name)246 const gchar *procmime_mimeinfo_get_parameter(MimeInfo *mimeinfo, const gchar *name)
247 {
248 	const gchar *value;
249 
250 	cm_return_val_if_fail(mimeinfo != NULL, NULL);
251 	cm_return_val_if_fail(name != NULL, NULL);
252 
253 	value = g_hash_table_lookup(mimeinfo->dispositionparameters, name);
254 	if (value == NULL)
255 		value = g_hash_table_lookup(mimeinfo->typeparameters, name);
256 
257 	return value;
258 }
259 
260 #define FLUSH_LASTLINE() {							\
261 	if (*lastline != '\0') {						\
262 		gint llen = 0;							\
263 		strretchomp(lastline);						\
264 		llen = strlen(lastline);					\
265 		if (lastline[llen-1] == ' ' && !account_sigsep_matchlist_str_found(lastline, "%s") &&	\
266 		    !(llen == 2 && lastline[1] == ' ' && strchr(prefs_common.quote_chars, lastline[0]))) {					\
267 			/* this is flowed */					\
268 			if (delsp)						\
269 				lastline[llen-1] = '\0';			\
270 			if (claws_fputs(lastline, outfp) == EOF)			\
271 				err = TRUE;					\
272 		} else {							\
273 			if (claws_fputs(lastline, outfp) == EOF)			\
274 				err = TRUE;					\
275 			if (claws_fputs("\n", outfp) == EOF)				\
276 				err = TRUE;					\
277 		}								\
278 	} 									\
279 	strcpy(lastline, buf);							\
280 }
281 
procmime_decode_content(MimeInfo * mimeinfo)282 gboolean procmime_decode_content(MimeInfo *mimeinfo)
283 {
284 	gchar buf[BUFFSIZE];
285 	gint readend;
286 	gchar *tmpfilename;
287 	FILE *outfp, *infp;
288 	GStatBuf statbuf;
289 	gboolean tmp_file = FALSE;
290 	gboolean flowed = FALSE;
291 	gboolean delsp = FALSE;
292 	gboolean err = FALSE;
293 	gint state = 0;
294 	guint save = 0;
295 
296 	cm_return_val_if_fail(mimeinfo != NULL, FALSE);
297 
298 	EncodingType encoding = forced_encoding
299 				? forced_encoding
300 				: mimeinfo->encoding_type;
301 	gchar lastline[BUFFSIZE];
302 	memset(lastline, 0, BUFFSIZE);
303 
304 	if (prefs_common.respect_flowed_format &&
305 	    mimeinfo->type == MIMETYPE_TEXT &&
306 	    !strcasecmp(mimeinfo->subtype, "plain")) {
307 		if (procmime_mimeinfo_get_parameter(mimeinfo, "format") != NULL &&
308 		    !strcasecmp(procmime_mimeinfo_get_parameter(mimeinfo, "format"),"flowed"))
309 			flowed = TRUE;
310 		if (flowed &&
311 		    procmime_mimeinfo_get_parameter(mimeinfo, "delsp") != NULL &&
312 		    !strcasecmp(procmime_mimeinfo_get_parameter(mimeinfo, "delsp"),"yes"))
313 			delsp = TRUE;
314 	}
315 
316 	if (!flowed && (
317 	     encoding == ENC_UNKNOWN ||
318 	     encoding == ENC_BINARY ||
319 	     encoding == ENC_7BIT ||
320 	     encoding == ENC_8BIT
321 	    ))
322 		return TRUE;
323 
324 	if (mimeinfo->type == MIMETYPE_MULTIPART || mimeinfo->type == MIMETYPE_MESSAGE)
325 		return TRUE;
326 
327 	if (mimeinfo->data.filename == NULL)
328 		return FALSE;
329 
330 	infp = claws_fopen(mimeinfo->data.filename, "rb");
331 	if (!infp) {
332 		FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
333 		return FALSE;
334 	}
335 	if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
336 		FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
337 		claws_fclose(infp);
338 		return FALSE;
339 	}
340 
341 	outfp = get_tmpfile_in_dir(get_mime_tmp_dir(), &tmpfilename);
342 	if (!outfp) {
343 		perror("tmpfile");
344 		claws_fclose(infp);
345 		return FALSE;
346 	}
347 
348 	tmp_file = TRUE;
349 	readend = mimeinfo->offset + mimeinfo->length;
350 
351 	account_sigsep_matchlist_create(); /* FLUSH_LASTLINE will use it */
352 
353 	*buf = '\0';
354 	if (encoding == ENC_QUOTED_PRINTABLE) {
355 		while ((ftell(infp) < readend) && (claws_fgets(buf, sizeof(buf), infp) != NULL)) {
356 			gint len;
357 			len = qp_decode_line(buf);
358 			buf[len] = '\0';
359 			if (!flowed) {
360 				if (claws_fwrite(buf, 1, len, outfp) < len)
361 					err = TRUE;
362 			} else {
363 				FLUSH_LASTLINE();
364 			}
365 		}
366 		if (flowed)
367 			FLUSH_LASTLINE();
368 	} else if (encoding == ENC_BASE64) {
369 		gchar outbuf[BUFFSIZE + 1];
370 		gint len, inlen, inread;
371 		gboolean got_error = FALSE;
372 		gboolean uncanonicalize = FALSE;
373 		FILE *tmpfp = NULL;
374 		gboolean null_bytes = FALSE;
375 		gboolean starting = TRUE;
376 
377 		if (mimeinfo->type == MIMETYPE_TEXT ||
378 		    mimeinfo->type == MIMETYPE_MESSAGE) {
379 			uncanonicalize = TRUE;
380 			tmpfp = my_tmpfile();
381 			if (!tmpfp) {
382 				perror("my_tmpfile");
383 				if (tmp_file)
384 					claws_fclose(outfp);
385 				claws_fclose(infp);
386 				return FALSE;
387 			}
388 		} else
389 			tmpfp = outfp;
390 
391 		while ((inlen = MIN(readend - ftell(infp), sizeof(buf))) > 0 && !err) {
392 			inread = claws_fread(buf, 1, inlen, infp);
393 			memset(outbuf, 0, sizeof(buf));
394 			len = g_base64_decode_step(buf, inlen, outbuf, &state, &save);
395 			if (uncanonicalize == TRUE && strlen(outbuf) < len && starting) {
396 				uncanonicalize = FALSE;
397 				null_bytes = TRUE;
398 			}
399 			starting = FALSE;
400 			if (((inread != inlen) || len < 0) && !got_error) {
401 				g_warning("Bad BASE64 content.");
402 				if (claws_fwrite(_("[Error decoding BASE64]\n"),
403 					sizeof(gchar),
404 					strlen(_("[Error decoding BASE64]\n")),
405 					tmpfp) < strlen(_("[Error decoding BASE64]\n")))
406 					g_warning("error decoding BASE64");
407 				got_error = TRUE;
408 				continue;
409 			} else if (len >= 0) {
410 				/* print out the error message only once
411 				 * per block */
412 				if (null_bytes) {
413 					/* we won't uncanonicalize, output to outfp directly */
414 					if (claws_fwrite(outbuf, sizeof(gchar), len, outfp) < len)
415 						err = TRUE;
416 				} else {
417 					if (claws_fwrite(outbuf, sizeof(gchar), len, tmpfp) < len)
418 						err = TRUE;
419 				}
420 				got_error = FALSE;
421 			}
422 		}
423 
424 		if (uncanonicalize) {
425 			rewind(tmpfp);
426 			while (claws_fgets(buf, sizeof(buf), tmpfp) != NULL) {
427 				strcrchomp(buf);
428 				if (claws_fputs(buf, outfp) == EOF)
429 					err = TRUE;
430 			}
431 		}
432 		if (tmpfp != outfp) {
433 			claws_fclose(tmpfp);
434 		}
435 	} else if (encoding == ENC_X_UUENCODE) {
436 		gchar outbuf[BUFFSIZE];
437 		gint len;
438 		gboolean flag = FALSE;
439 
440 		while ((ftell(infp) < readend) && (claws_fgets(buf, sizeof(buf), infp) != NULL)) {
441 			if (!flag && strncmp(buf,"begin ", 6)) continue;
442 
443 			if (flag) {
444 				len = fromuutobits(outbuf, buf);
445 				if (len <= 0) {
446 					if (len < 0)
447 						g_warning("Bad UUENCODE content (%d)", len);
448 					break;
449 				}
450 				if (claws_fwrite(outbuf, sizeof(gchar), len, outfp) < len)
451 					err = TRUE;
452 			} else
453 				flag = TRUE;
454 		}
455 	} else {
456 		while ((ftell(infp) < readend) && (claws_fgets(buf, sizeof(buf), infp) != NULL)) {
457 			if (!flowed) {
458 				if (claws_fputs(buf, outfp) == EOF)
459 					err = TRUE;
460 			} else {
461 				FLUSH_LASTLINE();
462 			}
463 		}
464 		if (flowed)
465 			FLUSH_LASTLINE();
466 		if (err == TRUE)
467 			g_warning("write error");
468 	}
469 
470 	claws_fclose(outfp);
471 	claws_fclose(infp);
472 
473 	account_sigsep_matchlist_delete();
474 
475 	if (err == TRUE) {
476 		return FALSE;
477 	}
478 
479 	if (g_stat(tmpfilename, &statbuf) < 0) {
480 		FILE_OP_ERROR(tmpfilename, "stat");
481 		return FALSE;
482 	}
483 
484 	if (mimeinfo->tmp)
485 		claws_unlink(mimeinfo->data.filename);
486 	g_free(mimeinfo->data.filename);
487 	mimeinfo->data.filename = tmpfilename;
488 	mimeinfo->tmp = TRUE;
489 	mimeinfo->offset = 0;
490 	mimeinfo->length = statbuf.st_size;
491 	mimeinfo->encoding_type = ENC_BINARY;
492 
493 	return TRUE;
494 }
495 
496 #define B64_LINE_SIZE		57
497 #define B64_BUFFSIZE		77
498 
procmime_encode_content(MimeInfo * mimeinfo,EncodingType encoding)499 gboolean procmime_encode_content(MimeInfo *mimeinfo, EncodingType encoding)
500 {
501 	FILE *infp = NULL, *outfp;
502 	gint len;
503 	gchar *tmpfilename;
504 	GStatBuf statbuf;
505 	gboolean err = FALSE;
506 
507 	if (mimeinfo->content == MIMECONTENT_EMPTY)
508 		return TRUE;
509 
510 	if (mimeinfo->encoding_type != ENC_UNKNOWN &&
511 	    mimeinfo->encoding_type != ENC_BINARY &&
512 	    mimeinfo->encoding_type != ENC_7BIT &&
513 	    mimeinfo->encoding_type != ENC_8BIT)
514 		if(!procmime_decode_content(mimeinfo))
515 			return FALSE;
516 
517 	outfp = get_tmpfile_in_dir(get_mime_tmp_dir(), &tmpfilename);
518 	if (!outfp) {
519 		perror("tmpfile");
520 		return FALSE;
521 	}
522 
523 	if (mimeinfo->content == MIMECONTENT_FILE && mimeinfo->data.filename) {
524 		if ((infp = claws_fopen(mimeinfo->data.filename, "rb")) == NULL) {
525 			g_warning("Can't open file %s", mimeinfo->data.filename);
526 			claws_fclose(outfp);
527 			return FALSE;
528 		}
529 	} else if (mimeinfo->content == MIMECONTENT_MEM) {
530 		infp = str_open_as_stream(mimeinfo->data.mem);
531 		if (infp == NULL) {
532 			claws_fclose(outfp);
533 			return FALSE;
534 		}
535 	} else {
536 		claws_fclose(outfp);
537 		g_warning("Unknown mimeinfo");
538 		return FALSE;
539 	}
540 
541 	if (encoding == ENC_BASE64) {
542 		gchar inbuf[B64_LINE_SIZE], *out;
543 		FILE *tmp_fp = infp;
544 		gchar *tmp_file = NULL;
545 
546 		if (mimeinfo->type == MIMETYPE_TEXT ||
547 		     mimeinfo->type == MIMETYPE_MESSAGE) {
548 		     	if (mimeinfo->content == MIMECONTENT_FILE) {
549 				tmp_file = get_tmp_file();
550 				if (canonicalize_file(mimeinfo->data.filename, tmp_file) < 0) {
551 					g_free(tmp_file);
552 					claws_fclose(infp);
553 					claws_fclose(outfp);
554 					return FALSE;
555 				}
556 				if ((tmp_fp = claws_fopen(tmp_file, "rb")) == NULL) {
557 					FILE_OP_ERROR(tmp_file, "claws_fopen");
558 					claws_unlink(tmp_file);
559 					g_free(tmp_file);
560 					claws_fclose(infp);
561 					claws_fclose(outfp);
562 					return FALSE;
563 				}
564 			} else {
565 				gchar *out = canonicalize_str(mimeinfo->data.mem);
566 				claws_fclose(infp);
567 				infp = str_open_as_stream(out);
568 				tmp_fp = infp;
569 				g_free(out);
570 				if (infp == NULL) {
571 					claws_fclose(outfp);
572 					return FALSE;
573 				}
574 			}
575 		}
576 
577 		while ((len = claws_fread(inbuf, sizeof(gchar),
578 				    B64_LINE_SIZE, tmp_fp))
579 		       == B64_LINE_SIZE) {
580 			out = g_base64_encode(inbuf, B64_LINE_SIZE);
581 			if (claws_fputs(out, outfp) == EOF)
582 				err = TRUE;
583 			g_free(out);
584 			if (claws_fputc('\n', outfp) == EOF)
585 				err = TRUE;
586 		}
587 		if (len > 0 && claws_feof(tmp_fp)) {
588 			out = g_base64_encode(inbuf, len);
589 			if (claws_fputs(out, outfp) == EOF)
590 				err = TRUE;
591 			g_free(out);
592 			if (claws_fputc('\n', outfp) == EOF)
593 				err = TRUE;
594 		}
595 
596 		if (tmp_file) {
597 			claws_fclose(tmp_fp);
598 			claws_unlink(tmp_file);
599 			g_free(tmp_file);
600 		}
601 	} else if (encoding == ENC_QUOTED_PRINTABLE) {
602 		gchar inbuf[BUFFSIZE], outbuf[BUFFSIZE * 4];
603 
604 		while (claws_fgets(inbuf, sizeof(inbuf), infp) != NULL) {
605 			qp_encode_line(outbuf, inbuf);
606 
607 			if (!strncmp("From ", outbuf, sizeof("From ")-1)) {
608 				gchar *tmpbuf = outbuf;
609 
610 				tmpbuf += sizeof("From ")-1;
611 
612 				if (claws_fputs("=46rom ", outfp) == EOF)
613 					err = TRUE;
614 				if (claws_fputs(tmpbuf, outfp) == EOF)
615 					err = TRUE;
616 			} else {
617 				if (claws_fputs(outbuf, outfp) == EOF)
618 					err = TRUE;
619 			}
620 		}
621 	} else {
622 		gchar buf[BUFFSIZE];
623 
624 		while (claws_fgets(buf, sizeof(buf), infp) != NULL) {
625 			strcrchomp(buf);
626 			if (claws_fputs(buf, outfp) == EOF)
627 				err = TRUE;
628 		}
629 	}
630 
631 	claws_fclose(outfp);
632 	claws_fclose(infp);
633 
634 	if (err == TRUE)
635 		return FALSE;
636 
637 	if (mimeinfo->content == MIMECONTENT_FILE) {
638 		if (mimeinfo->tmp && (mimeinfo->data.filename != NULL))
639 			claws_unlink(mimeinfo->data.filename);
640 		g_free(mimeinfo->data.filename);
641 	} else if (mimeinfo->content == MIMECONTENT_MEM) {
642 		if (mimeinfo->tmp && (mimeinfo->data.mem != NULL))
643 			g_free(mimeinfo->data.mem);
644 	}
645 
646 	if (g_stat(tmpfilename, &statbuf) < 0) {
647 		FILE_OP_ERROR(tmpfilename, "stat");
648 		return FALSE;
649 	}
650 	mimeinfo->content = MIMECONTENT_FILE;
651 	mimeinfo->data.filename = tmpfilename;
652 	mimeinfo->tmp = TRUE;
653 	mimeinfo->offset = 0;
654 	mimeinfo->length = statbuf.st_size;
655 	mimeinfo->encoding_type = encoding;
656 
657 	return TRUE;
658 }
659 
procmime_get_part_to_stream(FILE * outfp,MimeInfo * mimeinfo)660 static gint procmime_get_part_to_stream(FILE *outfp, MimeInfo *mimeinfo)
661 {
662 	FILE *infp;
663 	gchar buf[BUFFSIZE];
664 	gint restlength, readlength;
665 	gint saved_errno = 0;
666 
667 	cm_return_val_if_fail(outfp != NULL, -1);
668 	cm_return_val_if_fail(mimeinfo != NULL, -1);
669 
670 	if (mimeinfo->encoding_type != ENC_BINARY && !procmime_decode_content(mimeinfo))
671 		return -EINVAL;
672 
673 	if ((infp = claws_fopen(mimeinfo->data.filename, "rb")) == NULL) {
674 		saved_errno = errno;
675 		FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
676 		return -(saved_errno);
677 	}
678 	if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
679 		saved_errno = errno;
680 		FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
681 		claws_fclose(infp);
682 		return -(saved_errno);
683 	}
684 
685 	restlength = mimeinfo->length;
686 
687 	while ((restlength > 0) && ((readlength = claws_fread(buf, 1, restlength > BUFFSIZE ? BUFFSIZE : restlength, infp)) > 0)) {
688 		if (claws_fwrite(buf, 1, readlength, outfp) != readlength) {
689 			saved_errno = errno;
690 			claws_fclose(infp);
691 			return -(saved_errno);
692 		}
693 		restlength -= readlength;
694 	}
695 
696 	claws_fclose(infp);
697 	rewind(outfp);
698 
699 	return 0;
700 }
701 
procmime_get_part(const gchar * outfile,MimeInfo * mimeinfo)702 gint procmime_get_part(const gchar *outfile, MimeInfo *mimeinfo)
703 {
704 	FILE *outfp;
705 	gint result;
706 	gint saved_errno = 0;
707 
708 	cm_return_val_if_fail(outfile != NULL, -1);
709 
710 	if ((outfp = claws_fopen(outfile, "wb")) == NULL) {
711 		saved_errno = errno;
712 		FILE_OP_ERROR(outfile, "claws_fopen");
713 		return -(saved_errno);
714 	}
715 
716 	result = procmime_get_part_to_stream(outfp, mimeinfo);
717 
718 	if (claws_fclose(outfp) == EOF) {
719 		saved_errno = errno;
720 		FILE_OP_ERROR(outfile, "claws_fclose");
721 		claws_unlink(outfile);
722 		return -(saved_errno);
723 	}
724 
725 	return result;
726 }
727 
procmime_scan_text_content(MimeInfo * mimeinfo,gboolean (* scan_callback)(const gchar * str,gpointer cb_data),gpointer cb_data)728 gboolean procmime_scan_text_content(MimeInfo *mimeinfo,
729 		gboolean (*scan_callback)(const gchar *str, gpointer cb_data),
730 		gpointer cb_data)
731 {
732 	FILE *tmpfp;
733 	const gchar *src_codeset;
734 	gboolean conv_fail = FALSE;
735 	gchar buf[BUFFSIZE];
736 	gchar *str;
737 	gboolean scan_ret = FALSE;
738 	int r;
739 
740 	cm_return_val_if_fail(mimeinfo != NULL, TRUE);
741 	cm_return_val_if_fail(scan_callback != NULL, TRUE);
742 
743 	if (!procmime_decode_content(mimeinfo))
744 		return TRUE;
745 
746 	tmpfp = my_tmpfile();
747 
748 	if (tmpfp == NULL) {
749 		FILE_OP_ERROR("tmpfile", "open");
750 		return TRUE;
751 	}
752 
753 	if ((r = procmime_get_part_to_stream(tmpfp, mimeinfo)) < 0) {
754 		g_warning("procmime_get_part_to_stream error %d\n", r);
755 		return TRUE;
756 	}
757 
758 	src_codeset = forced_charset
759 		      ? forced_charset :
760 		      procmime_mimeinfo_get_parameter(mimeinfo, "charset");
761 
762 	/* use supersets transparently when possible */
763 	if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_ISO_8859_1))
764 		src_codeset = CS_WINDOWS_1252;
765 	else if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_X_GBK))
766 		src_codeset = CS_GB18030;
767 	else if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_GBK))
768 		src_codeset = CS_GB18030;
769 	else if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_GB2312))
770 		src_codeset = CS_GB18030;
771 	else if (!forced_charset && src_codeset && !strcasecmp(src_codeset, CS_X_VIET_VPS))
772 		src_codeset = CS_WINDOWS_874;
773 
774 	if (mimeinfo->type == MIMETYPE_TEXT && !g_ascii_strcasecmp(mimeinfo->subtype, "html")) {
775 		SC_HTMLParser *parser;
776 		CodeConverter *conv;
777 
778 		conv = conv_code_converter_new(src_codeset);
779 		parser = sc_html_parser_new(tmpfp, conv);
780 		while ((str = sc_html_parse(parser)) != NULL) {
781 			if ((scan_ret = scan_callback(str, cb_data)) == TRUE)
782 				break;
783 		}
784 		sc_html_parser_destroy(parser);
785 		conv_code_converter_destroy(conv);
786 	} else if (mimeinfo->type == MIMETYPE_TEXT && !g_ascii_strcasecmp(mimeinfo->subtype, "enriched")) {
787 		ERTFParser *parser;
788 		CodeConverter *conv;
789 
790 		conv = conv_code_converter_new(src_codeset);
791 		parser = ertf_parser_new(tmpfp, conv);
792 		while ((str = ertf_parse(parser)) != NULL) {
793 			if ((scan_ret = scan_callback(str, cb_data)) == TRUE)
794 				break;
795 		}
796 		ertf_parser_destroy(parser);
797 		conv_code_converter_destroy(conv);
798 	} else if (mimeinfo->type == MIMETYPE_TEXT && mimeinfo->disposition != DISPOSITIONTYPE_ATTACHMENT) {
799 		while (claws_fgets(buf, sizeof(buf), tmpfp) != NULL) {
800 			str = conv_codeset_strdup(buf, src_codeset, CS_UTF_8);
801 			if (str) {
802 				if ((scan_ret = scan_callback(str, cb_data)) == TRUE) {
803 					g_free(str);
804 					break;
805 				}
806 				g_free(str);
807 			} else {
808 				conv_fail = TRUE;
809 				if ((scan_ret = scan_callback(buf, cb_data)) == TRUE)
810 					break;
811 			}
812 		}
813 	}
814 
815 	if (conv_fail)
816 		g_warning("procmime_get_text_content(): Code conversion failed.");
817 
818 	claws_fclose(tmpfp);
819 
820 	return scan_ret;
821 }
822 
scan_fputs_cb(const gchar * str,gpointer fp)823 static gboolean scan_fputs_cb(const gchar *str, gpointer fp)
824 {
825 	if (claws_fputs(str, (FILE *)fp) == EOF)
826 		return TRUE;
827 
828 	return FALSE;
829 }
830 
procmime_get_text_content(MimeInfo * mimeinfo)831 FILE *procmime_get_text_content(MimeInfo *mimeinfo)
832 {
833 	FILE *outfp;
834 	gboolean err;
835 
836 	if ((outfp = my_tmpfile()) == NULL) {
837 		perror("my_tmpfile");
838 		return NULL;
839 	}
840 
841 	err = procmime_scan_text_content(mimeinfo, scan_fputs_cb, outfp);
842 
843 	rewind(outfp);
844 	if (err == TRUE) {
845 		claws_fclose(outfp);
846 		return NULL;
847 	}
848 	return outfp;
849 
850 }
851 
procmime_get_binary_content(MimeInfo * mimeinfo)852 FILE *procmime_get_binary_content(MimeInfo *mimeinfo)
853 {
854 	FILE *outfp;
855 
856 	cm_return_val_if_fail(mimeinfo != NULL, NULL);
857 
858 	if (!procmime_decode_content(mimeinfo))
859 		return NULL;
860 
861 	outfp = my_tmpfile();
862 
863 	if (procmime_get_part_to_stream(outfp, mimeinfo) < 0) {
864 		return NULL;
865 	}
866 
867 	return outfp;
868 }
869 
870 /* search the first text part of (multipart) MIME message,
871    decode, convert it and output to outfp. */
procmime_get_first_text_content(MsgInfo * msginfo)872 FILE *procmime_get_first_text_content(MsgInfo *msginfo)
873 {
874 	FILE *outfp = NULL;
875 	MimeInfo *mimeinfo, *partinfo;
876 	gboolean empty_ok = FALSE, short_scan = TRUE;
877 
878     	cm_return_val_if_fail(msginfo != NULL, NULL);
879 
880 	/* first we try to short-scan (for speed), refusing empty parts */
881 scan_again:
882 	if (short_scan)
883 		mimeinfo = procmime_scan_message_short(msginfo);
884 	else
885 		mimeinfo = procmime_scan_message(msginfo);
886 	if (!mimeinfo) return NULL;
887 
888 	partinfo = mimeinfo;
889 	while (partinfo && (partinfo->type != MIMETYPE_TEXT ||
890 	       (partinfo->length == 0 && !empty_ok))) {
891 		partinfo = procmime_mimeinfo_next(partinfo);
892 	}
893 	if (partinfo)
894 		outfp = procmime_get_text_content(partinfo);
895 	else if (!empty_ok && short_scan) {
896 		/* if short scan didn't find a non-empty part, rescan
897 		 * fully for non-empty parts
898 		 */
899 		short_scan = FALSE;
900 		procmime_mimeinfo_free_all(&mimeinfo);
901 		goto scan_again;
902 	} else if (!empty_ok && !short_scan) {
903 		/* if full scan didn't find a non-empty part, rescan
904 		 * accepting empty parts
905 		 */
906 		empty_ok = TRUE;
907 		procmime_mimeinfo_free_all(&mimeinfo);
908 		goto scan_again;
909 	}
910 	procmime_mimeinfo_free_all(&mimeinfo);
911 
912 	return outfp;
913 }
914 
915 
find_encrypted_func(GNode * node,gpointer data)916 static gboolean find_encrypted_func(GNode *node, gpointer data)
917 {
918 	MimeInfo *mimeinfo = (MimeInfo *) node->data;
919 	MimeInfo **encinfo = (MimeInfo **) data;
920 
921 	if (privacy_mimeinfo_is_encrypted(mimeinfo)) {
922 		*encinfo = mimeinfo;
923 		return TRUE;
924 	}
925 
926 	return FALSE;
927 }
928 
find_encrypted_part(MimeInfo * rootinfo)929 static MimeInfo *find_encrypted_part(MimeInfo *rootinfo)
930 {
931 	MimeInfo *encinfo = NULL;
932 
933 	g_node_traverse(rootinfo->node, G_IN_ORDER, G_TRAVERSE_ALL, -1,
934 		find_encrypted_func, &encinfo);
935 
936 	return encinfo;
937 }
938 
939 /* search the first encrypted text part of (multipart) MIME message,
940    decode, convert it and output to outfp. */
procmime_get_first_encrypted_text_content(MsgInfo * msginfo)941 FILE *procmime_get_first_encrypted_text_content(MsgInfo *msginfo)
942 {
943 	FILE *outfp = NULL;
944 	MimeInfo *mimeinfo, *partinfo, *encinfo;
945 
946 	cm_return_val_if_fail(msginfo != NULL, NULL);
947 
948 	mimeinfo = procmime_scan_message(msginfo);
949 	if (!mimeinfo) {
950 		return NULL;
951 	}
952 
953 	partinfo = mimeinfo;
954 	if ((encinfo = find_encrypted_part(partinfo)) != NULL) {
955 		debug_print("decrypting message part\n");
956 		if (privacy_mimeinfo_decrypt(encinfo) < 0) {
957 			alertpanel_error(_("Couldn't decrypt: %s"),
958 				privacy_get_error());
959 			return NULL;
960 		}
961 	}
962 	partinfo = mimeinfo;
963 	while (partinfo && partinfo->type != MIMETYPE_TEXT) {
964 		partinfo = procmime_mimeinfo_next(partinfo);
965 		if (privacy_mimeinfo_is_signed(partinfo))
966 			procmsg_msginfo_set_flags(msginfo, 0, MSG_SIGNED);
967 	}
968 
969 	if (partinfo)
970 		outfp = procmime_get_text_content(partinfo);
971 
972 	procmime_mimeinfo_free_all(&mimeinfo);
973 
974 	return outfp;
975 }
976 
procmime_msginfo_is_encrypted(MsgInfo * msginfo)977 gboolean procmime_msginfo_is_encrypted(MsgInfo *msginfo)
978 {
979 	MimeInfo *mimeinfo, *partinfo;
980 	gboolean result = FALSE;
981 
982 	cm_return_val_if_fail(msginfo != NULL, FALSE);
983 
984 	mimeinfo = procmime_scan_message(msginfo);
985 	if (!mimeinfo) {
986 		return FALSE;
987 	}
988 
989 	partinfo = mimeinfo;
990 	result = (find_encrypted_part(partinfo) != NULL);
991 	procmime_mimeinfo_free_all(&mimeinfo);
992 
993 	return result;
994 }
995 
procmime_get_tmp_file_name(MimeInfo * mimeinfo)996 gchar *procmime_get_tmp_file_name(MimeInfo *mimeinfo)
997 {
998 	static guint32 id = 0;
999 	gchar *base;
1000 	gchar *filename;
1001 	gchar f_prefix[10];
1002 
1003 	cm_return_val_if_fail(mimeinfo != NULL, NULL);
1004 
1005 	g_snprintf(f_prefix, sizeof(f_prefix), "%08x.", id++);
1006 
1007 	if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
1008 		base = g_strdup("mimetmp.html");
1009 	else {
1010 		const gchar *basetmp;
1011 
1012 		basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
1013 		if (basetmp == NULL)
1014 			basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
1015 		if (basetmp == NULL)
1016 			basetmp = "mimetmp";
1017 		basetmp = g_path_get_basename(basetmp);
1018 		if (*basetmp == '\0')
1019 			basetmp = g_strdup("mimetmp");
1020 		base = conv_filename_from_utf8(basetmp);
1021 		g_free((gchar*)basetmp);
1022 		subst_for_shellsafe_filename(base);
1023 	}
1024 
1025 	filename = g_strconcat(get_mime_tmp_dir(), G_DIR_SEPARATOR_S,
1026 			       f_prefix, base, NULL);
1027 
1028 	g_free(base);
1029 
1030 	return filename;
1031 }
1032 
1033 static GList *mime_type_list = NULL;
1034 
procmime_get_mime_type(const gchar * filename)1035 gchar *procmime_get_mime_type(const gchar *filename)
1036 {
1037 	const gchar *p;
1038 	gchar *ext = NULL;
1039 	gchar *base;
1040 #ifndef G_OS_WIN32
1041 	static GHashTable *mime_type_table = NULL;
1042 	MimeType *mime_type;
1043 
1044 	if (!mime_type_table) {
1045 		mime_type_table = procmime_get_mime_type_table();
1046 		if (!mime_type_table) return NULL;
1047 	}
1048 #endif
1049 
1050 	if (filename == NULL)
1051 		return NULL;
1052 
1053 	base = g_path_get_basename(filename);
1054 	if ((p = strrchr(base, '.')) != NULL)
1055 		ext = g_utf8_strdown(p + 1, -1);
1056 	else
1057 		ext = g_utf8_strdown(base, -1);
1058 	g_free(base);
1059 
1060 #ifndef G_OS_WIN32
1061 	mime_type = g_hash_table_lookup(mime_type_table, ext);
1062 
1063 	if (mime_type) {
1064 		gchar *str;
1065 		str = g_strconcat(mime_type->type, "/", mime_type->sub_type,
1066 				  NULL);
1067 		debug_print("got type %s for %s\n", str, ext);
1068 		g_free(ext);
1069 		return str;
1070 	}
1071 	g_free(ext);
1072 	return NULL;
1073 #else
1074 	gchar *str = get_content_type_from_registry_with_ext(ext);
1075 
1076 	g_free(ext);
1077 	return str;
1078 #endif
1079 }
1080 
procmime_str_hash(gconstpointer gptr)1081 static guint procmime_str_hash(gconstpointer gptr)
1082 {
1083 	guint hash_result = 0;
1084 	const char *str;
1085 
1086 	for (str = gptr; str && *str; str++) {
1087 		if (isupper(*str)) hash_result += (*str + ' ');
1088 		else hash_result += *str;
1089 	}
1090 
1091 	return hash_result;
1092 }
1093 
procmime_str_equal(gconstpointer gptr1,gconstpointer gptr2)1094 static gint procmime_str_equal(gconstpointer gptr1, gconstpointer gptr2)
1095 {
1096 	const char *str1 = gptr1;
1097 	const char *str2 = gptr2;
1098 
1099 	return !g_utf8_collate(str1, str2);
1100 }
1101 
procmime_get_mime_type_table(void)1102 static GHashTable *procmime_get_mime_type_table(void)
1103 {
1104 	GHashTable *table = NULL;
1105 	GList *cur;
1106 	MimeType *mime_type;
1107 	gchar **exts;
1108 
1109 	if (!mime_type_list) {
1110 		mime_type_list = procmime_get_mime_type_list();
1111 		if (!mime_type_list) return NULL;
1112 	}
1113 
1114 	table = g_hash_table_new(procmime_str_hash, procmime_str_equal);
1115 
1116 	for (cur = mime_type_list; cur != NULL; cur = cur->next) {
1117 		gint i;
1118 		gchar *key;
1119 
1120 		mime_type = (MimeType *)cur->data;
1121 
1122 		if (!mime_type->extension) continue;
1123 
1124 		exts = g_strsplit(mime_type->extension, " ", 16);
1125 		for (i = 0; exts[i] != NULL; i++) {
1126 			/* Don't overwrite previously inserted extension */
1127 			if (!g_hash_table_lookup(table, exts[i])) {
1128 				key = g_strdup(exts[i]);
1129 				g_hash_table_insert(table, key, mime_type);
1130 			}
1131 		}
1132 		g_strfreev(exts);
1133 	}
1134 
1135 	return table;
1136 }
1137 
procmime_get_mime_type_list(void)1138 GList *procmime_get_mime_type_list(void)
1139 {
1140 	GList *list = NULL;
1141 	FILE *fp;
1142 	gchar buf[BUFFSIZE];
1143 	gchar *p;
1144 	gchar *delim;
1145 	MimeType *mime_type;
1146 	gboolean fp_is_glob_file = TRUE;
1147 
1148 	if (mime_type_list)
1149 		return mime_type_list;
1150 
1151 #if defined(__NetBSD__) || defined(__OpenBSD__) || defined(__FreeBSD__)
1152 	if ((fp = claws_fopen(DATAROOTDIR "/mime/globs", "rb")) == NULL)
1153 #else
1154 	if ((fp = claws_fopen("/usr/share/mime/globs", "rb")) == NULL)
1155 #endif
1156 	{
1157 		fp_is_glob_file = FALSE;
1158 		if ((fp = claws_fopen("/etc/mime.types", "rb")) == NULL) {
1159 			if ((fp = claws_fopen(SYSCONFDIR "/mime.types", "rb"))
1160 				== NULL) {
1161 				FILE_OP_ERROR(SYSCONFDIR "/mime.types",
1162 					"claws_fopen");
1163 				return NULL;
1164 			}
1165 		}
1166 	}
1167 
1168 	while (claws_fgets(buf, sizeof(buf), fp) != NULL) {
1169 		p = strchr(buf, '#');
1170 		if (p) *p = '\0';
1171 		g_strstrip(buf);
1172 
1173 		p = buf;
1174 
1175 		if (fp_is_glob_file) {
1176 			while (*p && !g_ascii_isspace(*p) && (*p!=':')) p++;
1177 		} else {
1178 			while (*p && !g_ascii_isspace(*p)) p++;
1179 		}
1180 
1181 		if (*p) {
1182 			*p = '\0';
1183 			p++;
1184 		}
1185 		delim = strchr(buf, '/');
1186 		if (delim == NULL) continue;
1187 		*delim = '\0';
1188 
1189 		mime_type = g_new(MimeType, 1);
1190 		mime_type->type = g_strdup(buf);
1191 		mime_type->sub_type = g_strdup(delim + 1);
1192 
1193 		if (fp_is_glob_file) {
1194 			while (*p && (g_ascii_isspace(*p)||(*p=='*')||(*p=='.'))) p++;
1195 		} else {
1196 			while (*p && g_ascii_isspace(*p)) p++;
1197 		}
1198 
1199 		if (*p)
1200 			mime_type->extension = g_utf8_strdown(p, -1);
1201 		else
1202 			mime_type->extension = NULL;
1203 
1204 		list = g_list_append(list, mime_type);
1205 	}
1206 
1207 	claws_fclose(fp);
1208 
1209 	if (!list)
1210 		g_warning("Can't read mime.types");
1211 
1212 	return list;
1213 }
1214 
procmime_get_encoding_for_charset(const gchar * charset)1215 EncodingType procmime_get_encoding_for_charset(const gchar *charset)
1216 {
1217 	if (!charset)
1218 		return ENC_8BIT;
1219 	else if (!g_ascii_strncasecmp(charset, "ISO-2022-", 9) ||
1220 		 !g_ascii_strcasecmp(charset, "US-ASCII"))
1221 		return ENC_7BIT;
1222 	else if (!g_ascii_strcasecmp(charset, "ISO-8859-5") ||
1223 		 !g_ascii_strncasecmp(charset, "KOI8-", 5) ||
1224 		 !g_ascii_strcasecmp(charset, "X-MAC-CYRILLIC") ||
1225 		 !g_ascii_strcasecmp(charset, "MAC-CYRILLIC") ||
1226 		 !g_ascii_strcasecmp(charset, "Windows-1251"))
1227 		return ENC_8BIT;
1228 	else if (!g_ascii_strncasecmp(charset, "ISO-8859-", 9))
1229 		return ENC_QUOTED_PRINTABLE;
1230 	else if (!g_ascii_strncasecmp(charset, "UTF-8", 5))
1231 		return ENC_QUOTED_PRINTABLE;
1232 	else
1233 		return ENC_8BIT;
1234 }
1235 
procmime_get_encoding_for_text_file(const gchar * file,gboolean * has_binary)1236 EncodingType procmime_get_encoding_for_text_file(const gchar *file, gboolean *has_binary)
1237 {
1238 	FILE *fp;
1239 	guchar buf[BUFFSIZE];
1240 	size_t len;
1241 	size_t octet_chars = 0;
1242 	size_t total_len = 0;
1243 	gfloat octet_percentage;
1244 	gboolean force_b64 = FALSE;
1245 
1246 	if ((fp = claws_fopen(file, "rb")) == NULL) {
1247 		FILE_OP_ERROR(file, "claws_fopen");
1248 		return ENC_UNKNOWN;
1249 	}
1250 
1251 	while ((len = claws_fread(buf, sizeof(guchar), sizeof(buf), fp)) > 0) {
1252 		guchar *p;
1253 		gint i;
1254 
1255 		for (p = buf, i = 0; i < len; ++p, ++i) {
1256 			if (*p & 0x80)
1257 				++octet_chars;
1258 			if (*p == '\0') {
1259 				force_b64 = TRUE;
1260 				*has_binary = TRUE;
1261 			}
1262 		}
1263 		total_len += len;
1264 	}
1265 
1266 	claws_fclose(fp);
1267 
1268 	if (total_len > 0)
1269 		octet_percentage = (gfloat)octet_chars / (gfloat)total_len;
1270 	else
1271 		octet_percentage = 0.0;
1272 
1273 	debug_print("procmime_get_encoding_for_text_file(): "
1274 		    "8bit chars: %"G_GSIZE_FORMAT" / %"G_GSIZE_FORMAT" (%f%%)\n", octet_chars, total_len,
1275 		    100.0 * octet_percentage);
1276 
1277 	if (octet_percentage > 0.20 || force_b64) {
1278 		debug_print("using BASE64\n");
1279 		return ENC_BASE64;
1280 	} else if (octet_chars > 0) {
1281 		debug_print("using quoted-printable\n");
1282 		return ENC_QUOTED_PRINTABLE;
1283 	} else {
1284 		debug_print("using 7bit\n");
1285 		return ENC_7BIT;
1286 	}
1287 }
1288 
1289 struct EncodingTable
1290 {
1291 	gchar *str;
1292 	EncodingType enc_type;
1293 };
1294 
1295 struct EncodingTable encoding_table[] = {
1296 	{"7bit", ENC_7BIT},
1297 	{"8bit", ENC_8BIT},
1298 	{"binary", ENC_BINARY},
1299 	{"quoted-printable", ENC_QUOTED_PRINTABLE},
1300 	{"base64", ENC_BASE64},
1301 	{"x-uuencode", ENC_UNKNOWN},
1302 	{NULL, ENC_UNKNOWN},
1303 };
1304 
procmime_get_encoding_str(EncodingType encoding)1305 const gchar *procmime_get_encoding_str(EncodingType encoding)
1306 {
1307 	struct EncodingTable *enc_table;
1308 
1309 	for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1310 		if (enc_table->enc_type == encoding)
1311 			return enc_table->str;
1312 	}
1313 	return NULL;
1314 }
1315 
1316 /* --- NEW MIME STUFF --- */
1317 struct TypeTable
1318 {
1319 	gchar *str;
1320 	MimeMediaType type;
1321 };
1322 
1323 static struct TypeTable mime_type_table[] = {
1324 	{"text", MIMETYPE_TEXT},
1325 	{"image", MIMETYPE_IMAGE},
1326 	{"audio", MIMETYPE_AUDIO},
1327 	{"video", MIMETYPE_VIDEO},
1328 	{"model", MIMETYPE_MODEL},
1329 	{"application", MIMETYPE_APPLICATION},
1330 	{"message", MIMETYPE_MESSAGE},
1331 	{"multipart", MIMETYPE_MULTIPART},
1332 	{NULL, 0},
1333 };
1334 
procmime_get_media_type_str(MimeMediaType type)1335 const gchar *procmime_get_media_type_str(MimeMediaType type)
1336 {
1337 	struct TypeTable *type_table;
1338 
1339 	for (type_table = mime_type_table; type_table->str != NULL; type_table++) {
1340 		if (type_table->type == type)
1341 			return type_table->str;
1342 	}
1343 	return NULL;
1344 }
1345 
procmime_get_media_type(const gchar * str)1346 MimeMediaType procmime_get_media_type(const gchar *str)
1347 {
1348 	struct TypeTable *typetablearray;
1349 
1350 	for (typetablearray = mime_type_table; typetablearray->str != NULL; typetablearray++)
1351 		if (g_ascii_strncasecmp(str, typetablearray->str, strlen(typetablearray->str)) == 0)
1352 			return typetablearray->type;
1353 
1354 	return MIMETYPE_UNKNOWN;
1355 }
1356 
1357 /*!
1358  *\brief	Safe wrapper for content type string.
1359  *
1360  *\return	const gchar * Pointer to content type string.
1361  */
procmime_get_content_type_str(MimeMediaType type,const char * subtype)1362 gchar *procmime_get_content_type_str(MimeMediaType type,
1363 					   const char *subtype)
1364 {
1365 	const gchar *type_str = NULL;
1366 
1367 	if (subtype == NULL || !(type_str = procmime_get_media_type_str(type)))
1368 		return g_strdup("unknown");
1369 	return g_strdup_printf("%s/%s", type_str, subtype);
1370 }
1371 
1372 static int procmime_parse_mimepart(MimeInfo *parent,
1373 			     gchar *content_type,
1374 			     gchar *content_encoding,
1375 			     gchar *content_description,
1376 			     gchar *content_id,
1377 			     gchar *content_disposition,
1378 			     gchar *content_location,
1379 			     const gchar *original_msgid,
1380 			     const gchar *disposition_notification_hdr,
1381 			     const gchar *filename,
1382 			     guint offset,
1383 			     guint length,
1384 			     gboolean short_scan);
1385 
procmime_parse_message_rfc822(MimeInfo * mimeinfo,gboolean short_scan)1386 static void procmime_parse_message_rfc822(MimeInfo *mimeinfo, gboolean short_scan)
1387 {
1388 	HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1389 			        {"Content-Transfer-Encoding:",
1390 			  			   NULL, FALSE},
1391 				{"Content-Description:",
1392 						   NULL, TRUE},
1393 			        {"Content-ID:",
1394 						   NULL, TRUE},
1395 				{"Content-Disposition:",
1396 				                   NULL, TRUE},
1397 				{"Content-Location:",
1398 						   NULL, TRUE},
1399 				{"MIME-Version:",
1400 						   NULL, TRUE},
1401 				{"Original-Message-ID:",
1402 						   NULL, TRUE},
1403 				{"Disposition:",
1404 						   NULL, TRUE},
1405 				{NULL,		   NULL, FALSE}};
1406 	guint content_start, i;
1407 	FILE *fp;
1408         gchar *tmp;
1409 	gint len = 0;
1410 
1411 	procmime_decode_content(mimeinfo);
1412 
1413 	fp = claws_fopen(mimeinfo->data.filename, "rb");
1414 	if (fp == NULL) {
1415 		FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
1416 		return;
1417 	}
1418 	if (fseek(fp, mimeinfo->offset, SEEK_SET) < 0) {
1419 		FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
1420 		claws_fclose(fp);
1421 		return;
1422 	}
1423 	procheader_get_header_fields(fp, hentry);
1424 	if (hentry[0].body != NULL) {
1425 		tmp = conv_unmime_header(hentry[0].body, NULL, FALSE);
1426                 g_free(hentry[0].body);
1427                 hentry[0].body = tmp;
1428         }
1429 	if (hentry[2].body != NULL) {
1430 		tmp = conv_unmime_header(hentry[2].body, NULL, FALSE);
1431                 g_free(hentry[2].body);
1432                 hentry[2].body = tmp;
1433         }
1434 	if (hentry[4].body != NULL) {
1435 		tmp = conv_unmime_header(hentry[4].body, NULL, FALSE);
1436                 g_free(hentry[4].body);
1437                 hentry[4].body = tmp;
1438         }
1439 	if (hentry[5].body != NULL) {
1440 		tmp = conv_unmime_header(hentry[5].body, NULL, FALSE);
1441                 g_free(hentry[5].body);
1442                 hentry[5].body = tmp;
1443         }
1444 	if (hentry[7].body != NULL) {
1445 		tmp = conv_unmime_header(hentry[7].body, NULL, FALSE);
1446                 g_free(hentry[7].body);
1447                 hentry[7].body = tmp;
1448         }
1449 	if (hentry[8].body != NULL) {
1450 		tmp = conv_unmime_header(hentry[8].body, NULL, FALSE);
1451                 g_free(hentry[8].body);
1452                 hentry[8].body = tmp;
1453         }
1454 
1455 	content_start = ftell(fp);
1456 	claws_fclose(fp);
1457 
1458 	len = mimeinfo->length - (content_start - mimeinfo->offset);
1459 	if (len < 0)
1460 		len = 0;
1461 	procmime_parse_mimepart(mimeinfo,
1462 				hentry[0].body, hentry[1].body,
1463 				hentry[2].body, hentry[3].body,
1464 				hentry[4].body, hentry[5].body,
1465 				hentry[7].body, hentry[8].body,
1466 				mimeinfo->data.filename, content_start,
1467 				len, short_scan);
1468 
1469 	for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1470 		g_free(hentry[i].body);
1471 		hentry[i].body = NULL;
1472 	}
1473 }
1474 
procmime_parse_disposition_notification(MimeInfo * mimeinfo,const gchar * original_msgid,const gchar * disposition_notification_hdr,gboolean short_scan)1475 static void procmime_parse_disposition_notification(MimeInfo *mimeinfo,
1476 		const gchar *original_msgid, const gchar *disposition_notification_hdr,
1477 		gboolean short_scan)
1478 {
1479 	HeaderEntry hentry[] = {{"Original-Message-ID:",  NULL, TRUE},
1480 			        {"Disposition:",	  NULL, TRUE},
1481 				{NULL,			  NULL, FALSE}};
1482 	guint i;
1483 	FILE *fp;
1484 	gchar *orig_msg_id = NULL;
1485 	gchar *disp = NULL;
1486 
1487 	procmime_decode_content(mimeinfo);
1488 
1489 	debug_print("parse disposition notification\n");
1490 	fp = claws_fopen(mimeinfo->data.filename, "rb");
1491 	if (fp == NULL) {
1492 		FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
1493 		return;
1494 	}
1495 	if (fseek(fp, mimeinfo->offset, SEEK_SET) < 0) {
1496 		FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
1497 		claws_fclose(fp);
1498 		return;
1499 	}
1500 
1501 	if (original_msgid && disposition_notification_hdr) {
1502 		hentry[0].body = g_strdup(original_msgid);
1503 		hentry[1].body = g_strdup(disposition_notification_hdr);
1504 	} else {
1505 		procheader_get_header_fields(fp, hentry);
1506 	}
1507 
1508         claws_fclose(fp);
1509 
1510     	if (!hentry[0].body || !hentry[1].body) {
1511 		debug_print("MsgId %s, Disp %s\n",
1512 			hentry[0].body ? hentry[0].body:"(nil)",
1513 			hentry[1].body ? hentry[1].body:"(nil)");
1514 		goto bail;
1515 	}
1516 
1517 	orig_msg_id = g_strdup(hentry[0].body);
1518 	disp = g_strdup(hentry[1].body);
1519 
1520 	extract_parenthesis(orig_msg_id, '<', '>');
1521 	remove_space(orig_msg_id);
1522 
1523 	if (strstr(disp, "displayed")) {
1524 		/* find sent message, if possible */
1525 		MsgInfo *info = NULL;
1526 		GList *flist;
1527 		debug_print("%s has been displayed.\n", orig_msg_id);
1528 		for (flist = folder_get_list(); flist != NULL; flist = g_list_next(flist)) {
1529 			FolderItem *outbox = ((Folder *)(flist->data))->outbox;
1530 			if (!outbox) {
1531 				debug_print("skipping folder with no outbox...\n");
1532 				continue;
1533 			}
1534 			info = folder_item_get_msginfo_by_msgid(outbox, orig_msg_id);
1535 			debug_print("%s %s in %s\n", info?"found":"didn't find", orig_msg_id, outbox->path);
1536 			if (info) {
1537 				procmsg_msginfo_set_flags(info, MSG_RETRCPT_GOT, 0);
1538 				procmsg_msginfo_free(&info);
1539 			}
1540 		}
1541 	}
1542 	g_free(orig_msg_id);
1543 	g_free(disp);
1544 bail:
1545 	for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1546 		g_free(hentry[i].body);
1547 		hentry[i].body = NULL;
1548 	}
1549 }
1550 
1551 #define GET_HEADERS() {						\
1552 	procheader_get_header_fields(fp, hentry);		\
1553         if (hentry[0].body != NULL) {				\
1554 		tmp = conv_unmime_header(hentry[0].body, NULL, FALSE);	\
1555                 g_free(hentry[0].body);				\
1556                 hentry[0].body = tmp;				\
1557         }                					\
1558         if (hentry[2].body != NULL) {				\
1559 		tmp = conv_unmime_header(hentry[2].body, NULL, FALSE);	\
1560                 g_free(hentry[2].body);				\
1561                 hentry[2].body = tmp;				\
1562         }                					\
1563         if (hentry[4].body != NULL) {				\
1564 		tmp = conv_unmime_header(hentry[4].body, NULL, FALSE);	\
1565                 g_free(hentry[4].body);				\
1566                 hentry[4].body = tmp;				\
1567         }                					\
1568         if (hentry[5].body != NULL) {				\
1569 		tmp = conv_unmime_header(hentry[5].body, NULL, FALSE);	\
1570                 g_free(hentry[5].body);				\
1571                 hentry[5].body = tmp;				\
1572         }                					\
1573 	if (hentry[6].body != NULL) {				\
1574 		tmp = conv_unmime_header(hentry[6].body, NULL, FALSE);	\
1575                 g_free(hentry[6].body);				\
1576                 hentry[6].body = tmp;				\
1577         }                					\
1578 	if (hentry[7].body != NULL) {				\
1579 		tmp = conv_unmime_header(hentry[7].body, NULL, FALSE);	\
1580                 g_free(hentry[7].body);				\
1581                 hentry[7].body = tmp;				\
1582         }							\
1583 }
1584 
procmime_parse_multipart(MimeInfo * mimeinfo,gboolean short_scan)1585 static void procmime_parse_multipart(MimeInfo *mimeinfo, gboolean short_scan)
1586 {
1587 	HeaderEntry hentry[] = {{"Content-Type:",  NULL, TRUE},
1588 			        {"Content-Transfer-Encoding:",
1589 			  			   NULL, FALSE},
1590 				{"Content-Description:",
1591 						   NULL, TRUE},
1592 			        {"Content-ID:",
1593 						   NULL, TRUE},
1594 				{"Content-Disposition:",
1595 				                   NULL, TRUE},
1596 				{"Content-Location:",
1597 						   NULL, TRUE},
1598 				{"Original-Message-ID:",
1599 						   NULL, TRUE},
1600 				{"Disposition:",
1601 						   NULL, TRUE},
1602 				{NULL,		   NULL, FALSE}};
1603 	gchar *tmp;
1604 	gchar *boundary;
1605 	gint boundary_len = 0, lastoffset = -1, i;
1606 	gchar buf[BUFFSIZE];
1607 	FILE *fp;
1608 	int result = 0;
1609 	gboolean start_found = FALSE;
1610 	gboolean end_found = FALSE;
1611 
1612 	boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
1613 	if (!boundary)
1614 		return;
1615 	boundary_len = strlen(boundary);
1616 
1617 	procmime_decode_content(mimeinfo);
1618 
1619 	fp = claws_fopen(mimeinfo->data.filename, "rb");
1620 	if (fp == NULL) {
1621 		FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
1622 		return;
1623 	}
1624 
1625 	if (fseek(fp, mimeinfo->offset, SEEK_SET) < 0) {
1626 		FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
1627 		claws_fclose(fp);
1628 		return;
1629 	}
1630 
1631 	while (claws_fgets(buf, sizeof(buf), fp) != NULL && result == 0) {
1632 		if (ftell(fp) - 1 > (mimeinfo->offset + mimeinfo->length))
1633 			break;
1634 
1635 		if (IS_BOUNDARY(buf, boundary, boundary_len)) {
1636 			start_found = TRUE;
1637 
1638 			if (lastoffset != -1) {
1639 				gint len = (ftell(fp) - strlen(buf)) - lastoffset - 1;
1640 				if (len < 0)
1641 					len = 0;
1642 				result = procmime_parse_mimepart(mimeinfo,
1643 				                        hentry[0].body, hentry[1].body,
1644 							hentry[2].body, hentry[3].body,
1645 							hentry[4].body, hentry[5].body,
1646 							hentry[6].body, hentry[7].body,
1647 							mimeinfo->data.filename, lastoffset,
1648 							len, short_scan);
1649 				if (result == 1 && short_scan)
1650 					break;
1651 
1652 			}
1653 
1654 			if (buf[2 + boundary_len]     == '-' &&
1655 			    buf[2 + boundary_len + 1] == '-') {
1656 			    	end_found = TRUE;
1657 				break;
1658 			}
1659 			for (i = 0; i < (sizeof hentry / sizeof hentry[0]) ; i++) {
1660 				g_free(hentry[i].body);
1661 				hentry[i].body = NULL;
1662 			}
1663 			GET_HEADERS();
1664 			lastoffset = ftell(fp);
1665 		}
1666 	}
1667 
1668 	if (start_found && !end_found && lastoffset != -1) {
1669 		gint len = (ftell(fp) - strlen(buf)) - lastoffset - 1;
1670 
1671 		if (len >= 0) {
1672 			result = procmime_parse_mimepart(mimeinfo,
1673 				        hentry[0].body, hentry[1].body,
1674 					hentry[2].body, hentry[3].body,
1675 					hentry[4].body, hentry[5].body,
1676 					hentry[6].body, hentry[7].body,
1677 					mimeinfo->data.filename, lastoffset,
1678 					len, short_scan);
1679 		}
1680 		mimeinfo->broken = TRUE;
1681 	}
1682 
1683 	for (i = 0; i < (sizeof hentry / sizeof hentry[0]); i++) {
1684 		g_free(hentry[i].body);
1685 		hentry[i].body = NULL;
1686 	}
1687 	claws_fclose(fp);
1688 }
1689 
parse_parameters(const gchar * parameters,GHashTable * table)1690 static void parse_parameters(const gchar *parameters, GHashTable *table)
1691 {
1692 	gchar *params, *param, *next;
1693 	GSList *convlist = NULL, *concatlist = NULL, *cur;
1694 
1695 	params = g_strdup(parameters);
1696 	param = params;
1697 	next = params;
1698 	for (; next != NULL; param = next) {
1699 		gchar *attribute, *value, *tmp, *down_attr, *orig_down_attr;
1700 		gint len;
1701 		gboolean convert = FALSE;
1702 
1703 		next = strchr_with_skip_quote(param, '"', ';');
1704 		if (next != NULL) {
1705 			next[0] = '\0';
1706 			next++;
1707 		}
1708 
1709 		g_strstrip(param);
1710 
1711 		attribute = param;
1712 		value = strchr(attribute, '=');
1713 		if (value == NULL)
1714 			continue;
1715 
1716 		value[0] = '\0';
1717 		value++;
1718 		while (value[0] != '\0' && value[0] == ' ')
1719 			value++;
1720 
1721 		down_attr = g_utf8_strdown(attribute, -1);
1722 		orig_down_attr = down_attr;
1723 
1724 		len = down_attr ? strlen(down_attr):0;
1725 		if (len > 0 && down_attr[len - 1] == '*') {
1726 			gchar *srcpos, *dstpos, *endpos;
1727 
1728 			convert = TRUE;
1729 			down_attr[len - 1] = '\0';
1730 
1731 			srcpos = value;
1732 			dstpos = value;
1733 			endpos = value + strlen(value);
1734 			while (srcpos < endpos) {
1735 				if (*srcpos != '%')
1736 					*dstpos = *srcpos;
1737 				else {
1738 					guchar dstvalue;
1739 
1740 					if (!get_hex_value(&dstvalue, srcpos[1], srcpos[2]))
1741 						*dstpos = '?';
1742 					else
1743 						*dstpos = dstvalue;
1744 					srcpos += 2;
1745 				}
1746 				srcpos++;
1747 				dstpos++;
1748 			}
1749 			*dstpos = '\0';
1750 			if (value[0] == '"')
1751 				extract_quote(value, '"');
1752 		} else {
1753 			if (value[0] == '"')
1754 				extract_quote(value, '"');
1755 			else if ((tmp = strchr(value, ' ')) != NULL)
1756 				*tmp = '\0';
1757 		}
1758 
1759 		if (down_attr) {
1760 			while (down_attr[0] == ' ')
1761 				down_attr++;
1762 			while (down_attr[strlen(down_attr)-1] == ' ')
1763 				down_attr[strlen(down_attr)-1] = '\0';
1764 		}
1765 
1766 		while (value[0] != '\0' && value[0] == ' ')
1767 			value++;
1768 		while (value[strlen(value)-1] == ' ')
1769 			value[strlen(value)-1] = '\0';
1770 
1771 		if (down_attr && strrchr(down_attr, '*') != NULL) {
1772 			gchar *tmpattr;
1773 
1774 			tmpattr = g_strdup(down_attr);
1775 			tmp = strrchr(tmpattr, '*');
1776 			tmp[0] = '\0';
1777 
1778 			if ((tmp[1] == '0') && (tmp[2] == '\0') &&
1779 			    (g_slist_find_custom(concatlist, down_attr, (GCompareFunc)g_strcmp0) == NULL))
1780 				concatlist = g_slist_prepend(concatlist, g_strdup(tmpattr));
1781 
1782 			if (convert && (g_slist_find_custom(convlist, tmpattr, (GCompareFunc)g_strcmp0) == NULL))
1783 				convlist = g_slist_prepend(convlist, g_strdup(tmpattr));
1784 
1785 			g_free(tmpattr);
1786 		} else if (convert) {
1787 			if (g_slist_find_custom(convlist, down_attr, (GCompareFunc)g_strcmp0) == NULL)
1788 				convlist = g_slist_prepend(convlist, g_strdup(down_attr));
1789 		}
1790 
1791 		if (g_hash_table_lookup(table, down_attr) == NULL)
1792 			g_hash_table_insert(table, g_strdup(down_attr), g_strdup(value));
1793 		g_free(orig_down_attr);
1794 	}
1795 
1796 	for (cur = concatlist; cur != NULL; cur = g_slist_next(cur)) {
1797 		gchar *attribute, *attrwnum, *partvalue;
1798 		gint n = 0;
1799 		GString *value;
1800 
1801 		attribute = (gchar *) cur->data;
1802 		value = g_string_sized_new(64);
1803 
1804 		attrwnum = g_strdup_printf("%s*%d", attribute, n);
1805 		while ((partvalue = g_hash_table_lookup(table, attrwnum)) != NULL) {
1806 			g_string_append(value, partvalue);
1807 
1808 			g_hash_table_remove(table, attrwnum);
1809 			g_free(attrwnum);
1810 			n++;
1811 			attrwnum = g_strdup_printf("%s*%d", attribute, n);
1812 		}
1813 		g_free(attrwnum);
1814 
1815 		g_hash_table_insert(table, g_strdup(attribute), g_strdup(value->str));
1816 		g_string_free(value, TRUE);
1817 	}
1818 	slist_free_strings_full(concatlist);
1819 
1820 	for (cur = convlist; cur != NULL; cur = g_slist_next(cur)) {
1821 		gchar *attribute, *key, *value;
1822 		gchar *charset, *lang, *oldvalue, *newvalue;
1823 
1824 		attribute = (gchar *) cur->data;
1825 		if (!g_hash_table_lookup_extended(
1826 			table, attribute, (gpointer *)(gchar *) &key, (gpointer *)(gchar *) &value))
1827 			continue;
1828 
1829 		charset = value;
1830 		if (charset == NULL)
1831 			continue;
1832 		lang = strchr(charset, '\'');
1833 		if (lang == NULL)
1834 			continue;
1835 		lang[0] = '\0';
1836 		lang++;
1837 		oldvalue = strchr(lang, '\'');
1838 		if (oldvalue == NULL)
1839 			continue;
1840 		oldvalue[0] = '\0';
1841 		oldvalue++;
1842 
1843 		newvalue = conv_codeset_strdup(oldvalue, charset, CS_UTF_8);
1844 
1845 		g_hash_table_remove(table, attribute);
1846 		g_free(key);
1847 		g_free(value);
1848 
1849 		g_hash_table_insert(table, g_strdup(attribute), newvalue);
1850 	}
1851 	slist_free_strings_full(convlist);
1852 
1853 	g_free(params);
1854 }
1855 
procmime_parse_content_type(const gchar * content_type,MimeInfo * mimeinfo)1856 static void procmime_parse_content_type(const gchar *content_type, MimeInfo *mimeinfo)
1857 {
1858 	cm_return_if_fail(content_type != NULL);
1859 	cm_return_if_fail(mimeinfo != NULL);
1860 
1861 	/* RFC 2045, page 13 says that the mime subtype is MANDATORY;
1862 	 * if it's not available we use the default Content-Type */
1863 	if ((content_type[0] == '\0') || (strchr(content_type, '/') == NULL)) {
1864 		mimeinfo->type = MIMETYPE_TEXT;
1865 		mimeinfo->subtype = g_strdup("plain");
1866 		if (g_hash_table_lookup(mimeinfo->typeparameters,
1867 				       "charset") == NULL) {
1868 			g_hash_table_insert(mimeinfo->typeparameters,
1869 				    g_strdup("charset"),
1870 				    g_strdup(
1871 					conv_get_locale_charset_str_no_utf8()));
1872 		}
1873 	} else {
1874 		gchar *type, *subtype, *params;
1875 
1876 		type = g_strdup(content_type);
1877 		subtype = strchr(type, '/') + 1;
1878 		*(subtype - 1) = '\0';
1879 		if ((params = strchr(subtype, ';')) != NULL) {
1880 			params[0] = '\0';
1881 			params++;
1882 		}
1883 
1884 		mimeinfo->type = procmime_get_media_type(type);
1885 		mimeinfo->subtype = g_strstrip(g_strdup(subtype));
1886 
1887 		/* Get mimeinfo->typeparameters */
1888 		if (params != NULL)
1889 			parse_parameters(params, mimeinfo->typeparameters);
1890 
1891 		g_free(type);
1892 	}
1893 }
1894 
procmime_parse_content_disposition(const gchar * content_disposition,MimeInfo * mimeinfo)1895 static void procmime_parse_content_disposition(const gchar *content_disposition, MimeInfo *mimeinfo)
1896 {
1897 	gchar *tmp, *params;
1898 
1899 	cm_return_if_fail(content_disposition != NULL);
1900 	cm_return_if_fail(mimeinfo != NULL);
1901 
1902 	tmp = g_strdup(content_disposition);
1903 	if ((params = strchr(tmp, ';')) != NULL) {
1904 		params[0] = '\0';
1905 		params++;
1906 	}
1907 	g_strstrip(tmp);
1908 
1909 	if (!g_ascii_strcasecmp(tmp, "inline"))
1910 		mimeinfo->disposition = DISPOSITIONTYPE_INLINE;
1911 	else if (!g_ascii_strcasecmp(tmp, "attachment"))
1912 		mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1913 	else
1914 		mimeinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
1915 
1916 	if (params != NULL)
1917 		parse_parameters(params, mimeinfo->dispositionparameters);
1918 
1919 	g_free(tmp);
1920 }
1921 
1922 
procmime_parse_content_encoding(const gchar * content_encoding,MimeInfo * mimeinfo)1923 static void procmime_parse_content_encoding(const gchar *content_encoding, MimeInfo *mimeinfo)
1924 {
1925 	struct EncodingTable *enc_table;
1926 
1927 	for (enc_table = encoding_table; enc_table->str != NULL; enc_table++) {
1928 		if (g_ascii_strcasecmp(enc_table->str, content_encoding) == 0) {
1929 			mimeinfo->encoding_type = enc_table->enc_type;
1930 			return;
1931 		}
1932 	}
1933 	mimeinfo->encoding_type = ENC_UNKNOWN;
1934 	return;
1935 }
1936 
1937 static GSList *registered_parsers = NULL;
1938 
procmime_get_mimeparser_for_type(MimeMediaType type,const gchar * sub_type)1939 static MimeParser *procmime_get_mimeparser_for_type(MimeMediaType type, const gchar *sub_type)
1940 {
1941 	GSList *cur;
1942 	for (cur = registered_parsers; cur; cur = cur->next) {
1943 		MimeParser *parser = (MimeParser *)cur->data;
1944 		if (parser->type == type && !g_strcmp0(parser->sub_type, sub_type))
1945 			return parser;
1946 	}
1947 	return NULL;
1948 }
1949 
procmime_mimeparser_register(MimeParser * parser)1950 void procmime_mimeparser_register(MimeParser *parser)
1951 {
1952 	if (!procmime_get_mimeparser_for_type(parser->type, parser->sub_type))
1953 		registered_parsers = g_slist_append(registered_parsers, parser);
1954 }
1955 
1956 
procmime_mimeparser_unregister(MimeParser * parser)1957 void procmime_mimeparser_unregister(MimeParser *parser)
1958 {
1959 	registered_parsers = g_slist_remove(registered_parsers, parser);
1960 }
1961 
procmime_mimeparser_parse(MimeParser * parser,MimeInfo * mimeinfo)1962 static gboolean procmime_mimeparser_parse(MimeParser *parser, MimeInfo *mimeinfo)
1963 {
1964 	cm_return_val_if_fail(parser->parse != NULL, FALSE);
1965 	return parser->parse(parser, mimeinfo);
1966 }
1967 
procmime_parse_mimepart(MimeInfo * parent,gchar * content_type,gchar * content_encoding,gchar * content_description,gchar * content_id,gchar * content_disposition,gchar * content_location,const gchar * original_msgid,const gchar * disposition_notification_hdr,const gchar * filename,guint offset,guint length,gboolean short_scan)1968 static int procmime_parse_mimepart(MimeInfo *parent,
1969 			     gchar *content_type,
1970 			     gchar *content_encoding,
1971 			     gchar *content_description,
1972 			     gchar *content_id,
1973 			     gchar *content_disposition,
1974 			     gchar *content_location,
1975 			     const gchar *original_msgid,
1976 			     const gchar *disposition_notification_hdr,
1977 			     const gchar *filename,
1978 			     guint offset,
1979 			     guint length,
1980 			     gboolean short_scan)
1981 {
1982 	MimeInfo *mimeinfo;
1983 	MimeParser *parser = NULL;
1984 	gboolean parsed = FALSE;
1985 	int result = 0;
1986 
1987 	/* Create MimeInfo */
1988 	mimeinfo = procmime_mimeinfo_new();
1989 	mimeinfo->content = MIMECONTENT_FILE;
1990 
1991 	if (parent != NULL) {
1992 		if (g_node_depth(parent->node) > 32) {
1993 			/* 32 is an arbitrary value
1994 			 * this avoids DOSsing ourselves
1995 			 * with enormous messages
1996 			 */
1997 			procmime_mimeinfo_free_all(&mimeinfo);
1998 			return -1;
1999 		}
2000 		g_node_append(parent->node, mimeinfo->node);
2001 	}
2002 	mimeinfo->data.filename = g_strdup(filename);
2003 	mimeinfo->offset = offset;
2004 	mimeinfo->length = length;
2005 
2006 	if (content_type != NULL) {
2007 		g_strchomp(content_type);
2008 		procmime_parse_content_type(content_type, mimeinfo);
2009 	} else {
2010 		mimeinfo->type = MIMETYPE_TEXT;
2011 		mimeinfo->subtype = g_strdup("plain");
2012 		if (g_hash_table_lookup(mimeinfo->typeparameters,
2013 				       "charset") == NULL) {
2014 			g_hash_table_insert(mimeinfo->typeparameters,
2015 				    g_strdup("charset"),
2016 				    g_strdup(
2017 					conv_get_locale_charset_str_no_utf8()));
2018 		}
2019 	}
2020 
2021 	if (content_encoding != NULL) {
2022  		g_strchomp(content_encoding);
2023 		procmime_parse_content_encoding(content_encoding, mimeinfo);
2024 	} else {
2025 		mimeinfo->encoding_type = ENC_UNKNOWN;
2026 	}
2027 
2028 	if (content_description != NULL)
2029 		mimeinfo->description = g_strdup(content_description);
2030 	else
2031 		mimeinfo->description = NULL;
2032 
2033 	if (content_id != NULL)
2034 		mimeinfo->id = g_strdup(content_id);
2035 	else
2036 		mimeinfo->id = NULL;
2037 
2038 	if (content_location != NULL)
2039 		mimeinfo->location = g_strdup(content_location);
2040 	else
2041 		mimeinfo->location = NULL;
2042 
2043 	if (content_disposition != NULL) {
2044  		g_strchomp(content_disposition);
2045 		procmime_parse_content_disposition(content_disposition, mimeinfo);
2046 	} else
2047 		mimeinfo->disposition = DISPOSITIONTYPE_UNKNOWN;
2048 
2049 	/* Call parser for mime type */
2050 	if ((parser = procmime_get_mimeparser_for_type(mimeinfo->type, mimeinfo->subtype)) != NULL) {
2051 		parsed = procmime_mimeparser_parse(parser, mimeinfo);
2052 	}
2053 	if (!parsed) {
2054 		switch (mimeinfo->type) {
2055 		case MIMETYPE_TEXT:
2056 			if (g_ascii_strcasecmp(mimeinfo->subtype, "plain") == 0 && short_scan) {
2057 				return 1;
2058 			}
2059 			break;
2060 
2061 		case MIMETYPE_MESSAGE:
2062 			if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
2063 				procmime_parse_message_rfc822(mimeinfo, short_scan);
2064 			}
2065 			if (g_ascii_strcasecmp(mimeinfo->subtype, "disposition-notification") == 0) {
2066 				procmime_parse_disposition_notification(mimeinfo,
2067 					original_msgid, disposition_notification_hdr, short_scan);
2068 			}
2069 			break;
2070 
2071 		case MIMETYPE_MULTIPART:
2072 			procmime_parse_multipart(mimeinfo, short_scan);
2073 			break;
2074 
2075 		case MIMETYPE_APPLICATION:
2076 			if (g_ascii_strcasecmp(mimeinfo->subtype, "octet-stream") == 0
2077 			&& original_msgid && *original_msgid
2078 			&& disposition_notification_hdr && *disposition_notification_hdr) {
2079 				procmime_parse_disposition_notification(mimeinfo,
2080 					original_msgid, disposition_notification_hdr, short_scan);
2081 			}
2082 			break;
2083 		default:
2084 			break;
2085 		}
2086 	}
2087 
2088 	return result;
2089 }
2090 
2091 static gchar *typenames[] = {
2092     "text",
2093     "image",
2094     "audio",
2095     "video",
2096     "application",
2097     "message",
2098     "multipart",
2099     "model",
2100     "unknown",
2101 };
2102 
output_func(GNode * node,gpointer data)2103 static gboolean output_func(GNode *node, gpointer data)
2104 {
2105 	guint i, depth;
2106 	MimeInfo *mimeinfo = (MimeInfo *) node->data;
2107 
2108 	depth = g_node_depth(node);
2109 	for (i = 0; i < depth; i++)
2110 		g_print("    ");
2111 	g_print("%s/%s (offset:%d length:%d encoding: %d)\n",
2112 		(mimeinfo->type <= MIMETYPE_UNKNOWN)? typenames[mimeinfo->type] : "unknown",
2113 		mimeinfo->subtype, mimeinfo->offset, mimeinfo->length, mimeinfo->encoding_type);
2114 
2115 	return FALSE;
2116 }
2117 
output_mime_structure(MimeInfo * mimeinfo,int indent)2118 static void output_mime_structure(MimeInfo *mimeinfo, int indent)
2119 {
2120 	g_node_traverse(mimeinfo->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1, output_func, NULL);
2121 }
2122 
procmime_scan_file_with_offset(const gchar * filename,int offset,gboolean short_scan)2123 static MimeInfo *procmime_scan_file_with_offset(const gchar *filename, int offset, gboolean short_scan)
2124 {
2125 	MimeInfo *mimeinfo;
2126 	GStatBuf buf;
2127 
2128 	if (g_stat(filename, &buf) < 0) {
2129 		FILE_OP_ERROR(filename, "stat");
2130 		return NULL;
2131 	}
2132 
2133 	mimeinfo = procmime_mimeinfo_new();
2134 	mimeinfo->content = MIMECONTENT_FILE;
2135 	mimeinfo->encoding_type = ENC_UNKNOWN;
2136 	mimeinfo->type = MIMETYPE_MESSAGE;
2137 	mimeinfo->subtype = g_strdup("rfc822");
2138 	mimeinfo->data.filename = g_strdup(filename);
2139 	mimeinfo->offset = offset;
2140 	mimeinfo->length = buf.st_size - offset;
2141 
2142 	procmime_parse_message_rfc822(mimeinfo, short_scan);
2143 	if (debug_get_mode())
2144 		output_mime_structure(mimeinfo, 0);
2145 
2146 	return mimeinfo;
2147 }
2148 
procmime_scan_file_full(const gchar * filename,gboolean short_scan)2149 static MimeInfo *procmime_scan_file_full(const gchar *filename, gboolean short_scan)
2150 {
2151 	MimeInfo *mimeinfo;
2152 
2153 	cm_return_val_if_fail(filename != NULL, NULL);
2154 
2155 	mimeinfo = procmime_scan_file_with_offset(filename, 0, short_scan);
2156 
2157 	return mimeinfo;
2158 }
2159 
procmime_scan_file(const gchar * filename)2160 MimeInfo *procmime_scan_file(const gchar *filename)
2161 {
2162 	return procmime_scan_file_full(filename, FALSE);
2163 }
2164 
procmime_scan_file_short(const gchar * filename)2165 static MimeInfo *procmime_scan_file_short(const gchar *filename)
2166 {
2167 	return procmime_scan_file_full(filename, TRUE);
2168 }
2169 
procmime_scan_queue_file_full(const gchar * filename,gboolean short_scan)2170 static MimeInfo *procmime_scan_queue_file_full(const gchar *filename, gboolean short_scan)
2171 {
2172 	FILE *fp;
2173 	MimeInfo *mimeinfo;
2174 	gchar buf[BUFFSIZE];
2175 	gint offset = 0;
2176 
2177 	cm_return_val_if_fail(filename != NULL, NULL);
2178 
2179 	/* Open file */
2180 	if ((fp = claws_fopen(filename, "rb")) == NULL)
2181 		return NULL;
2182 	/* Skip queue header */
2183 	while (claws_fgets(buf, sizeof(buf), fp) != NULL) {
2184 		/* new way */
2185 		if ((!strncmp(buf, "X-Claws-End-Special-Headers: 1",
2186 			strlen("X-Claws-End-Special-Headers:"))) ||
2187 		   (!strncmp(buf, "X-Sylpheed-End-Special-Headers: 1",
2188 			strlen("X-Sylpheed-End-Special-Headers:"))))
2189 			break;
2190 		/* old way */
2191 		if (buf[0] == '\r' || buf[0] == '\n') break;
2192 		/* from other mailers */
2193 		if (!strncmp(buf, "Date: ", 6)
2194 		||  !strncmp(buf, "To: ", 4)
2195 		||  !strncmp(buf, "From: ", 6)
2196 		||  !strncmp(buf, "Subject: ", 9)) {
2197 			rewind(fp);
2198 			break;
2199 		}
2200 	}
2201 	offset = ftell(fp);
2202 	claws_fclose(fp);
2203 
2204 	mimeinfo = procmime_scan_file_with_offset(filename, offset, short_scan);
2205 
2206 	return mimeinfo;
2207 }
2208 
procmime_scan_queue_file(const gchar * filename)2209 MimeInfo *procmime_scan_queue_file(const gchar *filename)
2210 {
2211 	return procmime_scan_queue_file_full(filename, FALSE);
2212 }
2213 
procmime_scan_queue_file_short(const gchar * filename)2214 static MimeInfo *procmime_scan_queue_file_short(const gchar *filename)
2215 {
2216 	return procmime_scan_queue_file_full(filename, TRUE);
2217 }
2218 
2219 typedef enum {
2220     ENC_AS_TOKEN,
2221     ENC_AS_QUOTED_STRING,
2222     ENC_AS_EXTENDED,
2223     ENC_AS_ENCWORD
2224 } EncodeAs;
2225 
2226 typedef struct _ParametersData {
2227 	FILE *fp;
2228 	guint len;
2229 	gint error;
2230 } ParametersData;
2231 
write_parameters(gpointer key,gpointer value,gpointer user_data)2232 static void write_parameters(gpointer key, gpointer value, gpointer user_data)
2233 {
2234 	gchar *param = key;
2235 	gchar *val = value, *valpos, *tmp;
2236 	ParametersData *pdata = (ParametersData *)user_data;
2237 	GString *buf = g_string_new("");
2238 	gint len;
2239 
2240 	EncodeAs encas = ENC_AS_TOKEN;
2241 
2242 	for (valpos = val; *valpos != 0; valpos++) {
2243 		if (!IS_ASCII(*valpos)) {
2244 			encas = ENC_AS_ENCWORD;
2245 			break;
2246 		}
2247 
2248 		/* CTLs */
2249 		if (((*valpos >= 0) && (*valpos < 037)) || (*valpos == 0177)) {
2250 			encas = ENC_AS_QUOTED_STRING;
2251 			continue;
2252 		}
2253 
2254 		/* tspecials + SPACE */
2255 		switch (*valpos) {
2256 		case ' ':
2257 		case '(':
2258 		case ')':
2259 		case '<':
2260 		case '>':
2261 		case '@':
2262         	case ',':
2263 		case ';':
2264 		case ':':
2265 		case '\\':
2266 		case '"':
2267         	case '/':
2268 		case '[':
2269 		case ']':
2270 		case '?':
2271 		case '=':
2272 			encas = ENC_AS_QUOTED_STRING;
2273 			continue;
2274 		}
2275 	}
2276 
2277 	switch (encas) {
2278 	case ENC_AS_TOKEN:
2279 		g_string_append_printf(buf, "%s=%s", param, val);
2280 		break;
2281 
2282 	case ENC_AS_QUOTED_STRING:
2283 		g_string_append_printf(buf, "%s=\"%s\"", param, val);
2284 		break;
2285 
2286 #if 0 /* we don't use that for now */
2287 	case ENC_AS_EXTENDED:
2288 		if (!g_utf8_validate(val, -1, NULL))
2289 			g_string_append_printf(buf, "%s*=%s''", param,
2290 				conv_get_locale_charset_str());
2291 		else
2292 			g_string_append_printf(buf, "%s*=%s''", param,
2293 				CS_INTERNAL);
2294 		for (valpos = val; *valpos != '\0'; valpos++) {
2295 			if (IS_ASCII(*valpos) && isalnum(*valpos)) {
2296 				g_string_append_printf(buf, "%c", *valpos);
2297 			} else {
2298 				gchar hexstr[3] = "XX";
2299 				get_hex_str(hexstr, *valpos);
2300 				g_string_append_printf(buf, "%%%s", hexstr);
2301 			}
2302 		}
2303 		break;
2304 #else
2305 	case ENC_AS_EXTENDED:
2306 		debug_print("Unhandled ENC_AS_EXTENDED.\n");
2307 		break;
2308 #endif
2309 	case ENC_AS_ENCWORD:
2310 		len = MAX(strlen(val)*6, 512);
2311 		tmp = g_malloc(len+1);
2312 		codeconv_set_strict(TRUE);
2313 		conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2314 			prefs_common.outgoing_charset);
2315 		codeconv_set_strict(FALSE);
2316 		if (!tmp || !*tmp) {
2317 			codeconv_set_strict(TRUE);
2318 			conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2319 				conv_get_outgoing_charset_str());
2320 			codeconv_set_strict(FALSE);
2321 		}
2322 		if (!tmp || !*tmp) {
2323 			codeconv_set_strict(TRUE);
2324 			conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2325 				CS_UTF_8);
2326 			codeconv_set_strict(FALSE);
2327 		}
2328 		if (!tmp || !*tmp) {
2329 			conv_encode_header_full(tmp, len, val, pdata->len + strlen(param) + 4 , FALSE,
2330 				CS_UTF_8);
2331 		}
2332 		g_string_append_printf(buf, "%s=\"%s\"", param, tmp);
2333 		g_free(tmp);
2334 		break;
2335 
2336 	}
2337 
2338 	if (buf->str && strlen(buf->str)) {
2339 		tmp = strstr(buf->str, "\n");
2340 		if (tmp)
2341 			len = (tmp - buf->str);
2342 		else
2343 			len = strlen(buf->str);
2344 		if (pdata->len + len > 76) {
2345 			if (fprintf(pdata->fp, ";\n %s", buf->str) < 0)
2346 				pdata->error = TRUE;
2347 			pdata->len = strlen(buf->str) + 1;
2348 		} else {
2349 			if (fprintf(pdata->fp, "; %s", buf->str) < 0)
2350 				pdata->error = TRUE;
2351 			pdata->len += strlen(buf->str) + 2;
2352 		}
2353 	}
2354 	g_string_free(buf, TRUE);
2355 }
2356 
2357 #define TRY(func) { \
2358 	if (!(func)) { \
2359 		return -1; \
2360 	} \
2361 }
2362 
procmime_write_mime_header(MimeInfo * mimeinfo,FILE * fp)2363 int procmime_write_mime_header(MimeInfo *mimeinfo, FILE *fp)
2364 {
2365 	struct TypeTable *type_table;
2366 	ParametersData *pdata = g_new0(ParametersData, 1);
2367 	debug_print("procmime_write_mime_header\n");
2368 
2369 	pdata->fp = fp;
2370 	pdata->error = FALSE;
2371 	for (type_table = mime_type_table; type_table->str != NULL; type_table++)
2372 		if (mimeinfo->type == type_table->type) {
2373 			gchar *buf = g_strdup_printf(
2374 				"Content-Type: %s/%s", type_table->str, mimeinfo->subtype);
2375 			if (fprintf(fp, "%s", buf) < 0) {
2376 				g_free(buf);
2377 				g_free(pdata);
2378 				return -1;
2379 			}
2380 			pdata->len = strlen(buf);
2381 			g_free(buf);
2382 			break;
2383 		}
2384 	g_hash_table_foreach(mimeinfo->typeparameters, write_parameters, pdata);
2385 	if (pdata->error == TRUE) {
2386 		g_free(pdata);
2387 		return -1;
2388 	}
2389 	g_free(pdata);
2390 
2391 	TRY(fprintf(fp, "\n") >= 0);
2392 
2393 	if (mimeinfo->encoding_type != ENC_UNKNOWN)
2394 		TRY(fprintf(fp, "Content-Transfer-Encoding: %s\n", procmime_get_encoding_str(mimeinfo->encoding_type)) >= 0);
2395 
2396 	if (mimeinfo->description != NULL)
2397 		TRY(fprintf(fp, "Content-Description: %s\n", mimeinfo->description) >= 0);
2398 
2399 	if (mimeinfo->id != NULL)
2400 		TRY(fprintf(fp, "Content-ID: %s\n", mimeinfo->id) >= 0);
2401 
2402 	if (mimeinfo->location != NULL)
2403 		TRY(fprintf(fp, "Content-Location: %s\n", mimeinfo->location) >= 0);
2404 
2405 	if (mimeinfo->disposition != DISPOSITIONTYPE_UNKNOWN) {
2406 		ParametersData *pdata = g_new0(ParametersData, 1);
2407 		gchar *buf = NULL;
2408 		if (mimeinfo->disposition == DISPOSITIONTYPE_INLINE)
2409 			buf = g_strdup("Content-Disposition: inline");
2410 		else if (mimeinfo->disposition == DISPOSITIONTYPE_ATTACHMENT)
2411 			buf = g_strdup("Content-Disposition: attachment");
2412 		else
2413 			buf = g_strdup("Content-Disposition: unknown");
2414 
2415 		if (fprintf(fp, "%s", buf) < 0) {
2416 			g_free(buf);
2417 			g_free(pdata);
2418 			return -1;
2419 		}
2420 		pdata->len = strlen(buf);
2421 		g_free(buf);
2422 
2423 		pdata->fp = fp;
2424 		pdata->error = FALSE;
2425 		g_hash_table_foreach(mimeinfo->dispositionparameters, write_parameters, pdata);
2426 		if (pdata->error == TRUE) {
2427 			g_free(pdata);
2428 			return -1;
2429 		}
2430 		g_free(pdata);
2431 		TRY(fprintf(fp, "\n") >= 0);
2432 	}
2433 
2434 	TRY(fprintf(fp, "\n") >= 0);
2435 
2436 	return 0;
2437 }
2438 
procmime_write_message_rfc822(MimeInfo * mimeinfo,FILE * fp)2439 static gint procmime_write_message_rfc822(MimeInfo *mimeinfo, FILE *fp)
2440 {
2441 	FILE *infp;
2442 	GNode *childnode;
2443 	MimeInfo *child;
2444 	gchar buf[BUFFSIZE];
2445 	gboolean skip = FALSE;;
2446 	size_t len;
2447 
2448 	debug_print("procmime_write_message_rfc822\n");
2449 
2450 	/* write header */
2451 	switch (mimeinfo->content) {
2452 	case MIMECONTENT_FILE:
2453 		if ((infp = claws_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2454 			FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
2455 			return -1;
2456 		}
2457 		if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
2458 			FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
2459 			claws_fclose(infp);
2460 			return -1;
2461 		}
2462 		while (claws_fgets(buf, sizeof(buf), infp) == buf) {
2463 			strcrchomp(buf);
2464 			if (buf[0] == '\n' && buf[1] == '\0')
2465 				break;
2466 			if (skip && (buf[0] == ' ' || buf[0] == '\t'))
2467 				continue;
2468 			if (g_ascii_strncasecmp(buf, "MIME-Version:", 13) == 0 ||
2469 			    g_ascii_strncasecmp(buf, "Content-Type:", 13) == 0 ||
2470 			    g_ascii_strncasecmp(buf, "Content-Transfer-Encoding:", 26) == 0 ||
2471 			    g_ascii_strncasecmp(buf, "Content-Description:", 20) == 0 ||
2472 			    g_ascii_strncasecmp(buf, "Content-ID:", 11) == 0 ||
2473 			    g_ascii_strncasecmp(buf, "Content-Location:", 17) == 0 ||
2474 			    g_ascii_strncasecmp(buf, "Content-Disposition:", 20) == 0) {
2475 				skip = TRUE;
2476 				continue;
2477 			}
2478 			len = strlen(buf);
2479 			if (claws_fwrite(buf, sizeof(gchar), len, fp) < len) {
2480 				g_warning("failed to dump %"G_GSIZE_FORMAT" bytes from file", len);
2481 				claws_fclose(infp);
2482 				return -1;
2483 			}
2484 			skip = FALSE;
2485 		}
2486 		claws_fclose(infp);
2487 		break;
2488 
2489 	case MIMECONTENT_MEM:
2490 		len = strlen(mimeinfo->data.mem);
2491 		if (claws_fwrite(mimeinfo->data.mem, sizeof(gchar), len, fp) < len) {
2492 			g_warning("failed to dump %"G_GSIZE_FORMAT" bytes from mem", len);
2493 			return -1;
2494 		}
2495 		break;
2496 
2497 	default:
2498 		break;
2499 	}
2500 
2501 	childnode = mimeinfo->node->children;
2502 	if (childnode == NULL)
2503 		return -1;
2504 
2505 	child = (MimeInfo *) childnode->data;
2506 	if (fprintf(fp, "MIME-Version: 1.0\n") < 0) {
2507 		g_warning("failed to write mime version");
2508 		return -1;
2509 	}
2510 	if (procmime_write_mime_header(child, fp) < 0)
2511 		return -1;
2512 	return procmime_write_mimeinfo(child, fp);
2513 }
2514 
procmime_write_multipart(MimeInfo * mimeinfo,FILE * fp)2515 static gint procmime_write_multipart(MimeInfo *mimeinfo, FILE *fp)
2516 {
2517 	FILE *infp;
2518 	GNode *childnode;
2519 	gchar *boundary, *str, *str2;
2520 	gchar buf[BUFFSIZE];
2521 	gboolean firstboundary;
2522 	size_t len;
2523 
2524 	debug_print("procmime_write_multipart\n");
2525 
2526 	boundary = g_hash_table_lookup(mimeinfo->typeparameters, "boundary");
2527 
2528 	switch (mimeinfo->content) {
2529 	case MIMECONTENT_FILE:
2530 		if ((infp = claws_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2531 			FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
2532 			return -1;
2533 		}
2534 		if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
2535 			FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
2536 			claws_fclose(infp);
2537 			return -1;
2538 		}
2539 		while (claws_fgets(buf, sizeof(buf), infp) == buf) {
2540 			if (IS_BOUNDARY(buf, boundary, strlen(boundary)))
2541 				break;
2542 			len = strlen(buf);
2543 			if (claws_fwrite(buf, sizeof(gchar), len, fp) < len) {
2544 				g_warning("failed to write %"G_GSIZE_FORMAT, len);
2545 				claws_fclose(infp);
2546 				return -1;
2547 			}
2548 		}
2549 		claws_fclose(infp);
2550 		break;
2551 
2552 	case MIMECONTENT_MEM:
2553 		str = g_strdup(mimeinfo->data.mem);
2554 		if (((str2 = strstr(str, boundary)) != NULL) && ((str2 - str) >= 2) &&
2555 		    (*(str2 - 1) == '-') && (*(str2 - 2) == '-'))
2556 			*(str2 - 2) = '\0';
2557 		len = strlen(str);
2558 		if (claws_fwrite(str, sizeof(gchar), len, fp) < len) {
2559 			g_warning("failed to write %"G_GSIZE_FORMAT" from mem", len);
2560 			g_free(str);
2561 			return -1;
2562 		}
2563 		g_free(str);
2564 		break;
2565 
2566 	default:
2567 		break;
2568 	}
2569 
2570 	childnode = mimeinfo->node->children;
2571 	firstboundary = TRUE;
2572 	while (childnode != NULL) {
2573 		MimeInfo *child = childnode->data;
2574 
2575 		if (firstboundary)
2576 			firstboundary = FALSE;
2577 		else
2578 			TRY(fprintf(fp, "\n") >= 0);
2579 
2580 		TRY(fprintf(fp, "--%s\n", boundary) >= 0);
2581 
2582 		if (procmime_write_mime_header(child, fp) < 0)
2583 			return -1;
2584 		if (procmime_write_mimeinfo(child, fp) < 0)
2585 			return -1;
2586 
2587 		childnode = g_node_next_sibling(childnode);
2588 	}
2589 	TRY(fprintf(fp, "\n--%s--\n", boundary) >= 0);
2590 
2591 	return 0;
2592 }
2593 
procmime_write_mimeinfo(MimeInfo * mimeinfo,FILE * fp)2594 gint procmime_write_mimeinfo(MimeInfo *mimeinfo, FILE *fp)
2595 {
2596 	FILE *infp;
2597 	size_t len;
2598 	debug_print("procmime_write_mimeinfo\n");
2599 
2600 	if (G_NODE_IS_LEAF(mimeinfo->node)) {
2601 		switch (mimeinfo->content) {
2602 		case MIMECONTENT_FILE:
2603 			if ((infp = claws_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2604 				FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
2605 				return -1;
2606 			}
2607 			copy_file_part_to_fp(infp, mimeinfo->offset, mimeinfo->length, fp);
2608 			claws_fclose(infp);
2609 			return 0;
2610 
2611 		case MIMECONTENT_MEM:
2612 			len = strlen(mimeinfo->data.mem);
2613 			if (claws_fwrite(mimeinfo->data.mem, sizeof(gchar), len, fp) < len)
2614 				return -1;
2615 			return 0;
2616 
2617 		default:
2618 			return 0;
2619 		}
2620 	} else {
2621 		/* Call writer for mime type */
2622 		switch (mimeinfo->type) {
2623 		case MIMETYPE_MESSAGE:
2624 			if (g_ascii_strcasecmp(mimeinfo->subtype, "rfc822") == 0) {
2625 				return procmime_write_message_rfc822(mimeinfo, fp);
2626 			}
2627 			break;
2628 
2629 		case MIMETYPE_MULTIPART:
2630 			return procmime_write_multipart(mimeinfo, fp);
2631 
2632 		default:
2633 			break;
2634 		}
2635 
2636 		return -1;
2637 	}
2638 
2639 	return 0;
2640 }
2641 
procmime_get_part_file_name(MimeInfo * mimeinfo)2642 gchar *procmime_get_part_file_name(MimeInfo *mimeinfo)
2643 {
2644 	gchar *base;
2645 
2646 	if ((mimeinfo->type == MIMETYPE_TEXT) && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
2647 		base = g_strdup("mimetmp.html");
2648 	else {
2649 		const gchar *basetmp;
2650 		gchar *basename;
2651 
2652 		basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
2653 		if (basetmp == NULL)
2654 			basetmp = procmime_mimeinfo_get_parameter(mimeinfo, "name");
2655 		if (basetmp == NULL)
2656 			basetmp = "mimetmp";
2657 		basename = g_path_get_basename(basetmp);
2658 		if (*basename == '\0') {
2659 			g_free(basename);
2660 			basename = g_strdup("mimetmp");
2661 		}
2662 		base = conv_filename_from_utf8(basename);
2663 		g_free(basename);
2664 		subst_for_shellsafe_filename(base);
2665 	}
2666 
2667 	return base;
2668 }
2669 
procmime_get_part_as_string(MimeInfo * mimeinfo,gboolean null_terminate)2670 void *procmime_get_part_as_string(MimeInfo *mimeinfo,
2671 		gboolean null_terminate)
2672 {
2673 	FILE *infp;
2674 	gchar *data;
2675 	gint length, readlength;
2676 
2677 	cm_return_val_if_fail(mimeinfo != NULL, NULL);
2678 
2679 	if (mimeinfo->encoding_type != ENC_BINARY &&
2680 			!procmime_decode_content(mimeinfo))
2681 		return NULL;
2682 
2683 	if (mimeinfo->content == MIMECONTENT_MEM)
2684 		return g_strdup(mimeinfo->data.mem);
2685 
2686 	if ((infp = claws_fopen(mimeinfo->data.filename, "rb")) == NULL) {
2687 		FILE_OP_ERROR(mimeinfo->data.filename, "claws_fopen");
2688 		return NULL;
2689 	}
2690 
2691 	if (fseek(infp, mimeinfo->offset, SEEK_SET) < 0) {
2692 		FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
2693 		claws_fclose(infp);
2694 		return NULL;
2695 	}
2696 
2697 	length = mimeinfo->length;
2698 
2699 	data = g_malloc(null_terminate ? length + 1 : length);
2700 	if (data == NULL) {
2701 		g_warning("Could not allocate %d bytes for procmime_get_part_as_string.\n",
2702 				(null_terminate ? length + 1 : length));
2703 		claws_fclose(infp);
2704 		return NULL;
2705 	}
2706 
2707 	readlength = claws_fread(data, length, 1, infp);
2708 	if (readlength <= 0) {
2709 		FILE_OP_ERROR(mimeinfo->data.filename, "fread");
2710 		g_free(data);
2711 		claws_fclose(infp);
2712 		return NULL;
2713 	}
2714 
2715 	claws_fclose(infp);
2716 
2717 	if (null_terminate)
2718 		data[length] = '\0';
2719 
2720 	return data;
2721 }
2722 
2723 /* Returns an open GInputStream. The caller should just
2724  * read mimeinfo->length bytes from it and then release it. */
procmime_get_part_as_inputstream(MimeInfo * mimeinfo)2725 GInputStream *procmime_get_part_as_inputstream(MimeInfo *mimeinfo)
2726 {
2727 	cm_return_val_if_fail(mimeinfo != NULL, NULL);
2728 
2729 	if (mimeinfo->encoding_type != ENC_BINARY &&
2730 			!procmime_decode_content(mimeinfo)) {
2731 		g_warning("could not decode part");
2732 		return NULL;
2733 	}
2734 	if (mimeinfo->content == MIMECONTENT_MEM) {
2735 		/* NULL for destroy func, since we're not copying
2736 		 * the data for the stream. */
2737 		return g_memory_input_stream_new_from_data(
2738 				mimeinfo->data.mem,
2739 				mimeinfo->length, NULL);
2740 	} else {
2741 		return g_memory_input_stream_new_from_data(
2742 				procmime_get_part_as_string(mimeinfo, FALSE),
2743 				mimeinfo->length, g_free);
2744 	}
2745 }
2746 
procmime_get_part_as_pixbuf(MimeInfo * mimeinfo,GError ** error)2747 GdkPixbuf *procmime_get_part_as_pixbuf(MimeInfo *mimeinfo, GError **error)
2748 {
2749 	GdkPixbuf *pixbuf;
2750 	GInputStream *stream;
2751 
2752 	if (error)
2753 		*error = NULL;
2754 
2755 	stream = procmime_get_part_as_inputstream(mimeinfo);
2756 	if (stream == NULL) {
2757 		if (error)
2758 			*error = g_error_new_literal(G_FILE_ERROR, -1, _("Could not decode part"));
2759 		return NULL;
2760 	}
2761 
2762 	pixbuf = gdk_pixbuf_new_from_stream(stream, NULL, error);
2763 	g_object_unref(stream);
2764 
2765 	if (error && *error != NULL)
2766 		return NULL;
2767 
2768 	return pixbuf;
2769 }
2770 
2771