clamav-devel/libclamav/mbox.c
e3aaff8e
 /*
b025d30e
  *  Copyright (C) 2002-2006 Nigel Horne <njh@bandsman.co.uk>
e3aaff8e
  *
  *  This program is free software; you can redistribute it and/or modify
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
  *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
  *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
48b7b4a7
  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  *  MA 02110-1301, USA.
e3aaff8e
  */
48b7b4a7
 static	char	const	rcsid[] = "$Id: mbox.c,v 1.285 2006/04/09 19:59:27 kojm Exp $";
6d6e8271
 
 #if HAVE_CONFIG_H
 #include "clamav-config.h"
 #endif
e3aaff8e
 
 #ifndef	CL_DEBUG
548a5f96
 #define	NDEBUG	/* map CLAMAV debug onto standard */
e3aaff8e
 #endif
 
 #ifdef CL_THREAD_SAFE
98cb5cba
 #ifndef	_REENTRANT
e3aaff8e
 #define	_REENTRANT	/* for Solaris 2.8 */
 #endif
98cb5cba
 #endif
e3aaff8e
 
 #include <stdio.h>
 #include <stdlib.h>
 #include <errno.h>
 #include <assert.h>
 #include <string.h>
 #include <strings.h>
 #include <ctype.h>
 #include <time.h>
 #include <fcntl.h>
d4d14218
 #include <sys/param.h>
e3aaff8e
 #include <clamav.h>
f10460ed
 #include <dirent.h>
a0b21816
 #include <limits.h>
e3aaff8e
 
242bfde8
 #if defined(HAVE_READDIR_R_3) || defined(HAVE_READDIR_R_2)
 #include <stddef.h>
 #endif
 
e2875303
 #ifdef	CL_THREAD_SAFE
 #include <pthread.h>
 #endif
 
e3aaff8e
 #include "table.h"
 #include "mbox.h"
 #include "blob.h"
b2223aad
 #include "line.h"
e3aaff8e
 #include "text.h"
 #include "message.h"
 #include "others.h"
 #include "defaults.h"
7e577f26
 #include "str.h"
6fd711b2
 #include "filetypes.h"
3953039b
 #include "uuencode.h"
e3aaff8e
 
02927896
 #ifdef	CL_DEBUG
 #if __GLIBC__ == 2 && __GLIBC_MINOR__ >= 1
 #define HAVE_BACKTRACE
 #endif
3f3f9085
 #endif
02927896
 
 #ifdef HAVE_BACKTRACE
 #include <execinfo.h>
 #include <signal.h>
 #include <syslog.h>
 
 static	void	sigsegv(int sig);
 static	void	print_trace(int use_syslog);
 #endif
 
c2b2d8af
 #if	defined(NO_STRTOK_R) || !defined(CL_THREAD_SAFE)
e3aaff8e
 #undef strtok_r
 #undef __strtok_r
 #define strtok_r(a,b,c)	strtok(a,b)
 #endif
 
 /* required for AIX and Tru64 */
 #ifdef TRUE
 #undef TRUE
 #endif
 #ifdef FALSE
 #undef FALSE
 #endif
 
87c9313e
 typedef enum	{ FALSE = 0, TRUE = 1 } bool;
 
9f2024cc
 #ifndef isblank
 #define isblank(c)	(((c) == ' ') || ((c) == '\t'))
 #endif
 
9b4bb8b7
 #define	SAVE_TO_DISC	/* multipart/message are saved in a temporary file */
393a6d67
 
f017fbdd
 /*
  * Code does exist to run FOLLORURLS on systems without libcurl, however that
  * is not recommended so it is not compiled by default
6b3fb261
  *
b25bfd58
  * On Solaris, when using the GNU C compiler, the clamAV build system uses the
  * Sun supplied ld instead of the GNU ld causing an error. Therefore you cannot
  * use WITH_CURL on Solaris with gcc, you must configure with
  * "--without-libcurl". I don't know if it works with Sun's own compiler
  *
6b3fb261
  * Fails to link on Solaris 10 with this error:
a9ecf619
  *      Undefined			first referenced
  *  symbol				in file
  *  __floatdidf				/opt/sfw/lib/libcurl.s
f017fbdd
  */
b25bfd58
 #if	C_SOLARIS && __GNUC__
6b3fb261
 #undef	WITH_CURL
 #endif
 
f017fbdd
 #ifdef	WITH_CURL
ad091acf
 #define	FOLLOWURLS	5	/*
 				 * Maximum number of URLs scanned in a message
43639aca
 				 * part. Helps to find Dialer.gen-45. If
ad091acf
 				 * not defined, don't check any URLs
 				 */
f017fbdd
 #endif
9b4bb8b7
 
55a3f03b
 #ifdef	FOLLOWURLS
65684cec
 
15021325
 #include "htmlnorm.h"
 
65684cec
 #ifdef	WITH_CURL	/* Set in configure */
 /*
  * To build with WITH_CURL:
  * LDFLAGS=`curl-config --libs` ./configure ...
  */
9558d802
 #include <curl/curl.h>
1d3d7dd9
 
 /*
e5014a87
  * Needs curl >= 7.11 (I've heard that 7.9 can cause crashes and I have seen
  *	7.10 segfault, later versions can be flakey as well)
1d3d7dd9
  * untested)
  */
e5014a87
 #if     (LIBCURL_VERSION_NUM < 0x070B00)
1d3d7dd9
 #undef	WITH_CURL	/* also undef FOLLOWURLS? */
 #endif
 
 #endif	/*WITH_CURL*/
 
55a3f03b
 #else	/*!FOLLOWURLS*/
 #undef	WITH_CURL
1d3d7dd9
 #endif	/*FOLLOWURLS*/
9558d802
 
f10460ed
 /*
6e84cebb
  * Define this to handle messages covered by section 7.3.2 of RFC1341.
f10460ed
  *	This is experimental code so it is up to YOU to (1) ensure it's secure
cf569541
  * (2) periodically trim the directory of old files
  *
  * If you use the load balancing feature of clamav-milter to run clamd on
fb79b576
  * more than one machine you must make sure that .../partial is on a shared
cf569541
  * network filesystem
f10460ed
  */
fb79b576
 #define	PARTIAL_DIR
f10460ed
 
2008841e
 /*#define	NEW_WORLD*/
d72749e0
 
f24bf390
 static	int	cli_parse_mbox(const char *dir, int desc, unsigned int options);
ae5c693a
 static	message	*parseEmailFile(FILE *fin, const table_t *rfc821Table, const char *firstLine, const char *dir);
b2223aad
 static	message	*parseEmailHeaders(const message *m, const table_t *rfc821Table);
4c60b74f
 static	int	parseEmailHeader(message *m, const char *line, const table_t *rfc821Table);
b0b860f1
 static	int	parseEmailBody(message *messageIn, text *textIn, const char *dir, const table_t *rfc821Table, const table_t *subtypeTable, unsigned int options);
e3aaff8e
 static	int	boundaryStart(const char *line, const char *boundary);
 static	int	endOfMessage(const char *line, const char *boundary);
 static	int	initialiseTables(table_t **rfc821Table, table_t **subtypeTable);
 static	int	getTextPart(message *const messages[], size_t size);
 static	size_t	strip(char *buf, int len);
 static	bool	continuationMarker(const char *line);
 static	int	parseMimeHeader(message *m, const char *cmd, const table_t *rfc821Table, const char *arg);
cca4efe4
 static	void	saveTextPart(message *m, const char *dir);
50df4118
 static	char	*rfc2047(const char *in);
d72749e0
 static	char	*rfc822comments(const char *in, char *out);
f10460ed
 #ifdef	PARTIAL_DIR
 static	int	rfc1341(message *m, const char *dir);
 #endif
ddea752e
 static	bool	usefulHeader(int commandNumber, const char *cmd);
d8142abc
 static	char	*getline_from_mbox(char *buffer, size_t len, FILE *fin);
9b4bb8b7
 
71ba1dcd
 static	void	checkURLs(message *m, const char *dir);
65684cec
 #ifdef	WITH_CURL
f121cb96
 struct arg {
2c7d1edd
 	const char *url;
 	const char *dir;
f121cb96
 	char *filename;
 };
 #ifdef	CL_THREAD_SAFE
 static	void	*getURL(void *a);
 #else
 static	void	*getURL(struct arg *arg);
 #endif
9b4bb8b7
 #endif
 
e3aaff8e
 /* Maximum line length according to RFC821 */
85bb253e
 #define	RFC2821LENGTH	1000
e3aaff8e
 
 /* Hashcodes for our hash tables */
 #define	CONTENT_TYPE			1
 #define	CONTENT_TRANSFER_ENCODING	2
 #define	CONTENT_DISPOSITION		3
 
 /* Mime sub types */
 #define	PLAIN		1
 #define	ENRICHED	2
 #define	HTML		3
 #define	RICHTEXT	4
 #define	MIXED		5
 #define	ALTERNATIVE	6
 #define	DIGEST		7
 #define	SIGNED		8
 #define	PARALLEL	9
 #define	RELATED		10	/* RFC2387 */
 #define	REPORT		11	/* RFC1892 */
c9b8f252
 #define	APPLEDOUBLE	12	/* Handling of this in only noddy for now */
393a6d67
 #define	FAX		MIXED	/*
 				 * RFC3458
 				 * Drafts stated to treat is as mixed if it is
 				 * not known.  This disappeared in the final
 				 * version (except when talking about
 				 * voice-message), but it is good enough for us
 				 * since we do no validation of coversheet
 				 * presence etc. (which also has disappeared
 				 * in the final version)
 				 */
9a729c80
 #define	ENCRYPTED	13	/*
 				 * e.g. RFC2015
 				 * Content-Type: multipart/encrypted;
 				 * boundary="nextPart1383049.XCRrrar2yq";
 				 * protocol="application/pgp-encrypted"
 				 */
6e5d95eb
 #define	X_BFILE		RELATED	/*
 				 * BeOS, expert two parts: the file and it's
 				 * attributes. The attributes part comes as
 				 *	Content-Type: application/x-be_attribute
 				 *		name="foo"
 				 * I can't find where it is defined, any
 				 * pointers would be appreciated. For now
 				 * we treat it as multipart/related
 				 */
c79a2273
 #define	KNOWBOT		14	/* Unknown and undocumented format? */
e3aaff8e
 
 static	const	struct tableinit {
 	const	char	*key;
 	int	value;
 } rfc821headers[] = {
303f9be9
 	/* TODO: make these regular expressions */
5c1150ac
 	{	"Content-Type",			CONTENT_TYPE		},
a9f386ed
 	{	"Content-Transfer-Encoding",	CONTENT_TRANSFER_ENCODING	},
 	{	"Content-Disposition",		CONTENT_DISPOSITION	},
e3aaff8e
 	{	NULL,				0			}
15033cb6
 }, mimeSubtypes[] = {	/* see RFC2045 */
e3aaff8e
 		/* subtypes of Text */
 	{	"plain",	PLAIN		},
 	{	"enriched",	ENRICHED	},
 	{	"html",		HTML		},
 	{	"richtext",	RICHTEXT	},
 		/* subtypes of Multipart */
 	{	"mixed",	MIXED		},
 	{	"alternative",	ALTERNATIVE	},
 	{	"digest",	DIGEST		},
 	{	"signed",	SIGNED		},
 	{	"parallel",	PARALLEL	},
 	{	"related",	RELATED		},
 	{	"report",	REPORT		},
c9b8f252
 	{	"appledouble",	APPLEDOUBLE	},
393a6d67
 	{	"fax-message",	FAX		},
9a729c80
 	{	"encrypted",	ENCRYPTED	},
6e5d95eb
 	{	"x-bfile",	X_BFILE		},	/* BeOS */
c79a2273
 	{	"knowbot",		KNOWBOT		},	/* ??? */
 	{	"knowbot-metadata",	KNOWBOT		},	/* ??? */
 	{	"knowbot-code",		KNOWBOT		},	/* ??? */
 	{	"knowbot-state",	KNOWBOT		},	/* ??? */
e3aaff8e
 	{	NULL,		0		}
 };
e2875303
 
 #ifdef	CL_THREAD_SAFE
 static	pthread_mutex_t	tables_mutex = PTHREAD_MUTEX_INITIALIZER;
 #endif
e3aaff8e
 
bac883ff
 #ifndef	O_BINARY
 #define	O_BINARY	0
 #endif
 
d72749e0
 #ifdef	NEW_WORLD
f24bf390
 
c6023c3f
 #undef	PARTIAL_DIR
 
f24bf390
 #if HAVE_MMAP
 #if HAVE_SYS_MMAN_H
 #include <sys/mman.h>
 #else /* HAVE_SYS_MMAN_H */
 #undef HAVE_MMAP
 #endif
0c8e0638
 #else	/*HAVE_MMAP*/
 #undef	NEW_WORLD
 #endif
f24bf390
 #endif
 
0c8e0638
 #ifdef	NEW_WORLD
ceabee13
 /*
  * Files larger than this are scanned with the old method, should be
  *	StreamMaxLength, I guess
  * If NW_MAX_FILE_SIZE is not defined, all files go through the
  *	new method. This definition is for machines very tight on RAM, or
  *	with large StreamMaxLength values
  */
 #define	MAX_ALLOCATION	134217728	/* see libclamav/others.c */
 #define	NW_MAX_FILE_SIZE	MAX_ALLOCATION
 
d72749e0
 struct scanlist {
ceabee13
 	const	char	*start;
 	size_t	size;
 	encoding_type	decoder;	/* only BASE64 and QUOTEDPRINTABLE for now */
 	struct	scanlist *next;
d72749e0
 };
 
ceabee13
 static struct map {
 	const	char	*offset;	/* sorted */
 	const	char	*word;
 	struct	map	*next;
 } *map, *tail;
 
 static	void	create_map(const char *begin, const char *end);
 static	void	add_to_map(const char *offset, const char *word);
 static	const	char	*find_in_map(const char *offset, const char *word);
 static	void	free_map(void);
 
f24bf390
 /*
  * This could be the future. Instead of parsing and decoding it just decodes.
d72749e0
  *
f24bf390
  * USE IT AT YOUR PERIL, a large number of viruses are not detected with this
  * method, possibly because the decoded files must be exact and not have
  * extra data at the start or end, which this code will produce.
f003b79e
  *
d72749e0
  * Currently only supports base64 and quoted-printable
  *
  * You may also see a lot of warnings. For the moment it falls back to old
  *	world mode if it doesn't know what to do - that'll be removed.
  * The code is untidy...
  *
  * FIXME: Some mailbox scans are slower with this method. I suspect that it's
  * because the scan can proceed to the end of the file rather than the end
  * of the attachment which can mean than later emails are scanned many times
0b28fbb8
  *
bc0fc102
  * FIXME: quoted printable doesn't know when to stop, so size related virus
  *	matching breaks
  *
ceabee13
  * TODO: Fall through to cli_parse_mbox() too often
c6023c3f
  *
0c8e0638
  * TODO: Add support for systems without mmap()
c6023c3f
  *
  * TODO: partial_dir fall through
f24bf390
  */
 int
 cli_mbox(const char *dir, int desc, unsigned int options)
 {
0c8e0638
 	char *start, *ptr, *line;
 	const char *last, *p, *q;
6b1cf491
 	size_t size;
f24bf390
 	struct stat statb;
 	message *m;
 	fileblob *fb;
f003b79e
 	int ret = 0;
af7dfe53
 	int wasAlloced;
d72749e0
 	struct scanlist *scanlist, *scanelem;
f24bf390
 
7c56033f
 	if(dir == NULL) {
 		cli_warnmsg("cli_mbox called with NULL dir\n");
 		return CL_ENULLARG;
 	}
f24bf390
 	if(fstat(desc, &statb) < 0)
 		return CL_EOPEN;
 
 	size = statb.st_size;
 
 	if(size == 0)
 		return CL_CLEAN;
 
ceabee13
 #ifdef	NW_MAX_FILE_SIZE
 	if(size > NW_MAX_FILE_SIZE)
 		return cli_parse_mbox(dir, desc, options);
 #endif
f24bf390
 
c6023c3f
 	/*cli_warnmsg("NEW_WORLD is new code - use at your own risk.\n");*/
bc0fc102
 #ifdef	PARTIAL_DIR
 	cli_warnmsg("PARTIAL_DIR doesn't work in the NEW_WORLD yet\n");
 #endif
6862efc7
 
d72749e0
 	start = mmap(NULL, size, PROT_READ, MAP_PRIVATE, desc, 0);
 	if(start == MAP_FAILED)
f24bf390
 		return CL_EMEM;
 
 	cli_dbgmsg("mmap'ed mbox\n");
 
d72749e0
 	ptr = cli_malloc(size);
 	if(ptr) {
 		memcpy(ptr, start, size);
af7dfe53
 		munmap(start, size);
d72749e0
 		start = ptr;
ceabee13
 		wasAlloced = 1;
af7dfe53
 	} else
 		wasAlloced = 0;
 
ceabee13
 	/* last points to the last *valid* address in the array */
 	last = &start[size - 1];
 
 	create_map(start, last);
 
d72749e0
 	scanelem = scanlist = NULL;
 	q = start;
ceabee13
 	/*
 	 * FIXME: mismatch of const char * and char * here and in later calls
 	 *	to find_in_map()
 	 */
 	while((p = find_in_map(q, "base64")) != NULL) {
d72749e0
 		cli_dbgmsg("Found base64\n");
 		if(scanelem) {
 			scanelem->next = cli_malloc(sizeof(struct scanlist));
 			scanelem = scanelem->next;
 		} else
 			scanlist = scanelem = cli_malloc(sizeof(struct scanlist));
 		scanelem->next = NULL;
 		scanelem->decoder = BASE64;
 		q = scanelem->start = &p[6];
ceabee13
 		if(((p = find_in_map(q, "\nFrom ")) != NULL) ||
 		   ((p = find_in_map(q, "base64")) != NULL) ||
 		   ((p = find_in_map(q, "quoted-printable")) != NULL)) {
5198de85
 			scanelem->size = (size_t)(p - q);
d72749e0
 			q = p;
0b28fbb8
 		} else {
 			scanelem->size = (size_t)(last - scanelem->start) + 1;
 			break;
 		}
6b1cf491
 		cli_dbgmsg("base64: last %u q %u\n", (unsigned int)last, (unsigned int)q);
d72749e0
 		assert(scanelem->size <= size);
f24bf390
 	}
c6023c3f
 
d72749e0
 	q = start;
ceabee13
 	while((p = find_in_map(q, "quoted-printable")) != NULL) {
0b28fbb8
 		if(p != q)
 			switch(p[-1]) {
 				case ' ':
 				case ':':
 				case '=':	/* wrong but allow it */
 					break;
 				default:
 					q = &p[16];
 					cli_dbgmsg("Ignore quoted-printable false positive\n");
 					continue;	/* false positive */
 			}
72cf1461
 
d72749e0
 		cli_dbgmsg("Found quoted-printable\n");
c6023c3f
 #ifdef	notdef
 		/*
 		 * The problem with quoted printable is recognising when to stop
 		 * parsing
 		 */
d72749e0
 		if(scanelem) {
 			scanelem->next = cli_malloc(sizeof(struct scanlist));
 			scanelem = scanelem->next;
 		} else
 			scanlist = scanelem = cli_malloc(sizeof(struct scanlist));
 		scanelem->next = NULL;
 		scanelem->decoder = QUOTEDPRINTABLE;
 		q = scanelem->start = &p[16];
6b1cf491
 		cli_dbgmsg("qp: last %u q %u\n", (unsigned int)last, (unsigned int)q);
ceabee13
 		if(((p = find_in_map(q, "\nFrom ")) != NULL) ||
 		   ((p = find_in_map(q, "quoted-printable")) != NULL) ||
 		   ((p = find_in_map(q, "base64")) != NULL)) {
5198de85
 			scanelem->size = (size_t)(p - q);
d72749e0
 			q = p;
0b28fbb8
 			cli_dbgmsg("qp: scanelem->size = %u\n", scanelem->size);
 		} else {
 			scanelem->size = (size_t)(last - scanelem->start) + 1;
 			break;
 		}
d72749e0
 		assert(scanelem->size <= size);
c6023c3f
 #else
 		if(wasAlloced)
 			free(start);
 		else
 			munmap(start, size);
 
ceabee13
 		free_map();
c6023c3f
 		return cli_parse_mbox(dir, desc, options);
 #endif
f24bf390
 	}
 
d72749e0
 	if(scanlist == NULL) {
 		const struct tableinit *tableinit;
 		bool anyHeadersFound = FALSE;
0b28fbb8
 		bool hasuuencode = FALSE;
c6023c3f
 		cli_file_t type;
d72749e0
 
 		/* FIXME: message: There could of course be no decoder needed... */
 		for(tableinit = rfc821headers; tableinit->key; tableinit++)
ceabee13
 			if(find_in_map(start, tableinit->key)) {
d72749e0
 				anyHeadersFound = TRUE;
 				break;
 			}
 
ceabee13
 		if((!anyHeadersFound) && find_in_map(start, "\nbegin "))
0b28fbb8
 			/* uuencoded part */
 			hasuuencode = TRUE;
 
ceabee13
 		free_map();
 
c6023c3f
 		type = cli_filetype(start, size);
 
 		if((type == CL_TYPE_UNKNOWN_TEXT) &&
 		   (strncmp(start, "Microsoft Mail Internet Headers", 31) == 0))
ceabee13
 			type = CL_TYPE_MAIL;
c6023c3f
 
af7dfe53
 		if(wasAlloced)
 			free(start);
 		else
 			munmap(start, size);
f24bf390
 
0b28fbb8
 		if(anyHeadersFound || hasuuencode) {
 			/* TODO: reduce the number of falls through here */
c6023c3f
 			if(hasuuencode)
 				cli_dbgmsg("New world - fall back to old uudecoder, type %d\n", type);
 			else
 				cli_dbgmsg("cli_mbox: unknown encoder, type %d\n", type);
 			if(type == CL_TYPE_MAIL)
 				return cli_parse_mbox(dir, desc, options);
 			cli_dbgmsg("Unknown filetype %d, return CLEAN\n", type);
 			return CL_CLEAN;
f003b79e
 		}
0b28fbb8
 
a43dd3cd
 		/* The message could be a plain text phish */
 		if((type == CL_TYPE_MAIL) && (!(options&CL_DB_NOPHISHING)))
ceabee13
 			return cli_parse_mbox(dir, desc, options);
c6023c3f
 		cli_dbgmsg("cli_mbox: I believe it's plain text which must be clean\n");
d72749e0
 		return CL_CLEAN;
 	}
ceabee13
 	free_map();
 
 #if	0
 	if(wasAlloced) {
 		const char *max = NULL;
 
 		for(scanelem = scanlist; scanelem; scanelem = scanelem->next) {
 			const char *end = &scanelem->start[scanelem->size];
 
 			if(end > max)
 				max = end;
 		}
 
 		if(max < last)
 			printf("could free %d bytes\n", (int)(last - max));
 	}
 #endif
d72749e0
 
 	for(scanelem = scanlist; scanelem; scanelem = scanelem->next) {
 		if(scanelem->decoder == BASE64) {
ceabee13
 			const char *b64start = scanelem->start;
 			size_t b64size = scanelem->size;
d72749e0
 
 			cli_dbgmsg("b64size = %lu\n", b64size);
012682d0
 			while((*b64start != '\n') && (*b64start != '\r')) {
f003b79e
 				b64start++;
 				b64size--;
d72749e0
 			}
 			/*
 			 * Look for the end of the headers
 			 */
 			while(b64start < last) {
 				if(*b64start == ';') {
f003b79e
 					b64start++;
 					b64size--;
012682d0
 				} else if((memcmp(b64start, "\n\n", 2) == 0) ||
 					  (memcmp(b64start, "\r\r", 2) == 0)) {
 					b64start += 2;
 					b64size -= 2;
 					break;
 				} else if(memcmp(b64start, "\r\n\r\n", 4) == 0) {
 					b64start += 4;
 					b64size -= 4;
 					break;
c6023c3f
 				} else if(memcmp(b64start, "\n \n", 3) == 0) {
 					/*
 					 * Some viruses are broken and have
 					 * one space character at the end of
 					 * the headers
 					 */
 					b64start += 3;
 					b64size -= 3;
 					break;
 				} else if(memcmp(b64start, "\r\n \r\n", 5) == 0) {
 					/*
 					 * Some viruses are broken and have
 					 * one space character at the end of
 					 * the headers
 					 */
 					b64start += 5;
 					b64size -= 5;
 					break;
f003b79e
 				}
5b76248c
 				b64start++;
d72749e0
 				b64size--;
5b76248c
 			}
f003b79e
 
d72749e0
 			if(b64size > 0L)
0b28fbb8
 				while((!isalnum(*b64start)) && (*b64start != '/')) {
d72749e0
 					if(b64size-- == 0L)
 						break;
 					b64start++;
 				}
 
 			if(b64size > 0L) {
a9ecf619
 				int lastline, tmpfd;
 				char *tmpfilename;
 				unsigned char *uptr;
 
d72749e0
 				cli_dbgmsg("cli_mbox: decoding %ld base64 bytes\n", b64size);
f003b79e
 
a9ecf619
 				tmpfilename = cli_gentemp(dir);
 				if(tmpfilename == 0) {
 					if(wasAlloced)
 						free(start);
 					else
 						munmap(start, size);
 
 					return CL_EMEM;
 				}
 
 #ifdef	O_TEXT
 				tmpfd = open(tmpfilename, O_WRONLY|O_CREAT|O_EXCL|O_TRUNC|O_TEXT, 0600);
 #else
 				tmpfd = open(tmpfilename, O_WRONLY|O_CREAT|O_EXCL|O_TRUNC, 0600);
 #endif
 				if(tmpfd < 0) {
 					cli_errmsg("Can't make %s\n", tmpfilename);
 					free(tmpfilename);
 					if(wasAlloced)
 						free(start);
 					else
 						munmap(start, size);
 
 					return CL_ETMPFILE;
 				}
 
d72749e0
 				line = NULL;
f003b79e
 
d72749e0
 				m = messageCreate();
c6023c3f
 				if(m == NULL) {
 					if(wasAlloced)
 						free(start);
 					else
 						munmap(start, size);
a9ecf619
 					close(tmpfd);
 					unlink(tmpfilename);
 					free(tmpfilename);
c6023c3f
 
d72749e0
 					return CL_EMEM;
c6023c3f
 				}
d72749e0
 				messageSetEncoding(m, "base64");
a9ecf619
 				free(tmpfilename);
f003b79e
 
012682d0
 				lastline = 0;
 
0b28fbb8
 				do {
a9ecf619
 					int length = 0, datalen;
012682d0
 					char *newline, *equal;
a9ecf619
 					unsigned char *bigbuf, *data;
 					unsigned char smallbuf[1024];
f003b79e
 
d72749e0
 					/*printf("%ld: ", b64size); fflush(stdout);*/
f003b79e
 
d72749e0
 					for(ptr = b64start; b64size && (*ptr != '\n') && (*ptr != '\r'); ptr++) {
 						length++;
 						--b64size;
 					}
f003b79e
 
d72749e0
 					/*printf("%d: ", length); fflush(stdout);*/
f003b79e
 
468c0f21
 					newline = cli_realloc(line, length + 1);
 					if(newline == NULL)
 						break;
 					line = newline;
f003b79e
 
d72749e0
 					memcpy(line, b64start, length);
 					line[length] = '\0';
f003b79e
 
012682d0
 					equal = strchr(line, '=');
 					if(equal) {
 						lastline++;
 						*equal = '\0';
 					}
d72749e0
 					/*puts(line);*/
f003b79e
 
a9ecf619
 #if	0
d72749e0
 					if(messageAddStr(m, line) < 0)
 						break;
a9ecf619
 #endif
 					if(length >= sizeof(smallbuf)) {
 						datalen = length + 2;
 						data = bigbuf = cli_malloc(datalen);
 						if(data == NULL)
 							break;
 					} else {
 						bigbuf = NULL;
 						data = smallbuf;
 						datalen = sizeof(data) - 1;
 					}
 					uptr = decodeLine(m, BASE64, line, data, datalen);
 
 					if(uptr == NULL) {
 						if(bigbuf)
 							free(bigbuf);
 						break;
 					}
 					/*cli_dbgmsg("base64: write %u bytes\n", (size_t)(uptr - data));*/
 					cli_writen(tmpfd, data, (size_t)(uptr - data));
 					if(bigbuf)
 						free(bigbuf);
f003b79e
 
d72749e0
 					if((b64size > 0) && (*ptr == '\r')) {
012682d0
 						b64start = ++ptr;
 						--b64size;
 					}
 					if((b64size > 0) && (*ptr == '\n')) {
 						b64start = ++ptr;
d72749e0
 						--b64size;
 					}
012682d0
 					if(lastline)
d72749e0
 						break;
0b28fbb8
 				} while(b64size > 0L);
 
a9ecf619
 #if	0
d72749e0
 				free(line);
 				fb = messageToFileblob(m, dir);
 				messageDestroy(m);
 
 				if(fb)
 					fileblobDestroy(fb);
 				else
 					ret = -1;
a9ecf619
 #else
 				if(m->base64chars) {
 					unsigned char data[4];
 
 					uptr = base64Flush(m, data);
 					if(uptr) {
 						/*cli_dbgmsg("base64: flush %u bytes\n", (size_t)(uptr - data));*/
 						cli_writen(tmpfd, data, (size_t)(uptr - data));
 					}
 				}
 
 				messageDestroy(m);
 				free(line);
 				close(tmpfd);
 #endif
f24bf390
 			}
d72749e0
 		} else if(scanelem->decoder == QUOTEDPRINTABLE) {
ceabee13
 			const char *quotedstart = scanelem->start;
 			size_t quotedsize = scanelem->size;
f003b79e
 
d72749e0
 			cli_dbgmsg("quotedsize = %lu\n", quotedsize);
 			while(*quotedstart != '\n') {
f003b79e
 				quotedstart++;
 				quotedsize--;
d72749e0
 			}
 			/*
 			 * Look for the end of the headers
 			 */
 			while(quotedstart < last) {
 				if(*quotedstart == ';') {
f003b79e
 					quotedstart++;
 					quotedsize--;
012682d0
 				} else if((*quotedstart == '\n') || (*quotedstart == '\r')) {
d72749e0
 					quotedstart++;
 					quotedsize--;
 					if((*quotedstart == '\n') || (*quotedstart == '\r')) {
 						quotedstart++;
 						quotedsize--;
 						break;
 					}
f003b79e
 				}
d72749e0
 				quotedstart++;
 				quotedsize--;
f003b79e
 			}
f24bf390
 
d72749e0
 			while(!isalnum(*quotedstart)) {
 				quotedstart++;
 				quotedsize--;
 			}
f24bf390
 
d72749e0
 			if(quotedsize > 0L) {
 				cli_dbgmsg("cli_mbox: decoding %ld quoted-printable bytes\n", quotedsize);
f24bf390
 
d72749e0
 				m = messageCreate();
c6023c3f
 				if(m == NULL) {
 					if(wasAlloced)
 						free(start);
 					else
 						munmap(start, size);
 
d72749e0
 					return CL_EMEM;
c6023c3f
 				}
d72749e0
 				messageSetEncoding(m, "quoted-printable");
f24bf390
 
d72749e0
 				line = NULL;
f24bf390
 
0b28fbb8
 				do {
d72749e0
 					int length = 0;
468c0f21
 					char *newline;
f24bf390
 
d72749e0
 					/*printf("%ld: ", quotedsize); fflush(stdout);*/
f24bf390
 
d72749e0
 					for(ptr = quotedstart; quotedsize && (*ptr != '\n') && (*ptr != '\r'); ptr++) {
 						length++;
 						--quotedsize;
 					}
f24bf390
 
d72749e0
 					/*printf("%d: ", length); fflush(stdout);*/
f24bf390
 
468c0f21
 					newline = cli_realloc(line, length + 1);
 					if(newline == NULL)
 						break;
 					line = newline;
f24bf390
 
d72749e0
 					memcpy(line, quotedstart, length);
 					line[length] = '\0';
f24bf390
 
d72749e0
 					/*puts(line);*/
f24bf390
 
d72749e0
 					if(messageAddStr(m, line) < 0)
 						break;
f003b79e
 
d72749e0
 					if((quotedsize > 0) && (*ptr == '\r')) {
012682d0
 						quotedstart = ++ptr;
 						--quotedsize;
 					}
 					if((quotedsize > 0) && (*ptr == '\n')) {
 						quotedstart = ++ptr;
d72749e0
 						--quotedsize;
 					}
0b28fbb8
 				} while(quotedsize > 0L);
 
d72749e0
 				free(line);
 				fb = messageToFileblob(m, dir);
 				messageDestroy(m);
f003b79e
 
d72749e0
 				if(fb)
 					fileblobDestroy(fb);
 				else
 					ret = -1;
 			}
f24bf390
 		}
 	}
d72749e0
 	scanelem = scanlist;
 
 	while(scanelem) {
 		struct scanlist *n = scanelem->next;
 
 		free(scanelem);
 		scanelem = n;
 	}
f24bf390
 
af7dfe53
 	if(wasAlloced)
 		free(start);
 	else
 		munmap(start, size);
f24bf390
 
af7dfe53
 	/*
 	 * FIXME: Need to run cl_scandir() here and return that value
 	 */
a9ecf619
 	cli_dbgmsg("cli_mbox: ret = %d\n", ret);
f003b79e
 	if(ret == 0)
f24bf390
 		return CL_CLEAN;	/* a lie - but it gets things going */
f003b79e
 
c6023c3f
 	cli_dbgmsg("New world - don't know what to do - fall back to old world\n");
d72749e0
 	/* Fall back for now */
0b28fbb8
 	lseek(desc, 0L, SEEK_SET);
f24bf390
 	return cli_parse_mbox(dir, desc, options);
 }
ceabee13
 
 static void
 create_map(const char *begin, const char *end)
 {
 	const struct wordlist {
 		const char *word;
 		int len;
 	} wordlist[] = {
 		{	"base64",		6	},
 		{	"quoted-printable",	16	},
 		{	"\nbegin ",		7	},
 		{	"\nFrom ",		7	},
 		{	NULL,			0	}
 	};
 
 	if(map) {
 		cli_warnmsg("create_map called without free_map\n");
 		free_map();
 	}
 	while(begin < end) {
 		const struct wordlist *word;
 
 		for(word = wordlist; word->word; word++) {
 			if((end - begin) < word->len)
 				continue;
 			if(strncasecmp(begin, word->word, word->len) == 0) {
 				add_to_map(begin, word->word);
 				break;
 			}
 		}
 		begin++;
 	}
 }
 
 /* To sort map, assume 'offset' is presented in sorted order */
 static void
 add_to_map(const char *offset, const char *word)
 {
 	if(map) {
 		tail->next = cli_malloc(sizeof(struct map));	/* FIXME: verify */
 		tail = tail->next;
 	} else
 		map = tail = cli_malloc(sizeof(struct map));	/* FIXME: verify */
 
 	tail->offset = offset;
 	tail->word = word;
 	tail->next = NULL;
 }
 
 static const char *
 find_in_map(const char *offset, const char *word)
 {
 	const struct map *item;
 
 	for(item = map; item; item = item->next)
 		if(item->offset >= offset)
 			if(strcasecmp(word, item->word) == 0)
 				return item->offset;
 
 	return NULL;
 }
 
 static void
 free_map(void)
 {
 	while(map) {
 		struct map *next = map->next;
 
 		free(map);
 		map = next;
 	}
 	map = NULL;
 }
 
 #else	/*!NEW_WORLD*/
f24bf390
 int
 cli_mbox(const char *dir, int desc, unsigned int options)
 {
7c56033f
 	if(dir == NULL) {
 		cli_warnmsg("cli_mbox called with NULL dir\n");
 		return CL_ENULLARG;
 	}
f24bf390
 	return cli_parse_mbox(dir, desc, options);
 }
 #endif
 
e3aaff8e
 /*
  * TODO: when signal handling is added, need to remove temp files when a
ef822cfc
  *	signal is received
e3aaff8e
  * TODO: add option to scan in memory not via temp files, perhaps with a
1bfbedd4
  * named pipe or memory mapped file, though this won't work on big e-mails
  * containing many levels of encapsulated messages - it'd just take too much
  * RAM
049a18b9
  * TODO: parse .msg format files
c9b8f252
  * TODO: fully handle AppleDouble format, see
ef822cfc
  *	http://www.lazerware.com/formats/Specs/AppleSingle_AppleDouble.pdf
89670d69
  * TODO: ensure parseEmailHeaders is always called before parseEmailBody
  * TODO: create parseEmail which calls parseEmailHeaders then parseEmailBody
9f2024cc
  * TODO: Handle unepected NUL bytes in header lines which stop strcmp()s:
  *	e.g. \0Content-Type: application/binary;
e3aaff8e
  */
f24bf390
 static int
 cli_parse_mbox(const char *dir, int desc, unsigned int options)
e3aaff8e
 {
049a18b9
 	int retcode, i;
ddea752e
 	message *body;
e3aaff8e
 	FILE *fd;
85bb253e
 	char buffer[RFC2821LENGTH + 1];
c7b69776
 #ifdef HAVE_BACKTRACE
02927896
 	void (*segv)(int);
 #endif
393a6d67
 	static table_t *rfc821, *subtype;
5cdb01fc
 #ifdef	CL_DEBUG
 	char tmpfilename[16];
 	int tmpfd;
 #endif
e3aaff8e
 
4c586bc8
 #ifdef	NEW_WORLD
 	cli_dbgmsg("fall back to old world\n");
 #else
e3aaff8e
 	cli_dbgmsg("in mbox()\n");
4c586bc8
 #endif
e3aaff8e
 
049a18b9
 	i = dup(desc);
 	if((fd = fdopen(i, "rb")) == NULL) {
 		cli_errmsg("Can't open descriptor %d\n", desc);
 		close(i);
ef822cfc
 		return CL_EOPEN;
049a18b9
 	}
5cdb01fc
 #ifdef	CL_DEBUG
 	/*
 	 * Copy the incoming mail for debugging, so that if it falls over
 	 * we have a copy of the offending email. This is debugging code
 	 * that you shouldn't of course install in a live environment. I am
 	 * not interested in hearing about security issues with this section
 	 * of the parser.
 	 */
 	strcpy(tmpfilename, "/tmp/mboxXXXXXX");
 	tmpfd = mkstemp(tmpfilename);
 	if(tmpfd < 0) {
 		perror(tmpfilename);
 		cli_errmsg("Can't make debugging file\n");
 	} else {
 		FILE *tmpfp = fdopen(tmpfd, "w");
 
 		if(tmpfp) {
 			while(fgets(buffer, sizeof(buffer) - 1, fd) != NULL)
 				fputs(buffer, tmpfp);
 			fclose(tmpfp);
 			rewind(fd);
 		} else
 			cli_errmsg("Can't fdopen debugging file\n");
 	}
 #endif
4b187745
 	if(fgets(buffer, sizeof(buffer) - 1, fd) == NULL) {
049a18b9
 		/* empty message */
 		fclose(fd);
5cdb01fc
 #ifdef	CL_DEBUG
 		unlink(tmpfilename);
 #endif
ef822cfc
 		return CL_CLEAN;
049a18b9
 	}
e2875303
 #ifdef	CL_THREAD_SAFE
 	pthread_mutex_lock(&tables_mutex);
 #endif
393a6d67
 	if(rfc821 == NULL) {
 		assert(subtype == NULL);
51fc2aa8
 
393a6d67
 		if(initialiseTables(&rfc821, &subtype) < 0) {
 			rfc821 = NULL;
 			subtype = NULL;
e2875303
 #ifdef	CL_THREAD_SAFE
 			pthread_mutex_unlock(&tables_mutex);
 #endif
51fc2aa8
 			fclose(fd);
5cdb01fc
 #ifdef	CL_DEBUG
 			unlink(tmpfilename);
 #endif
ef822cfc
 			return CL_EMEM;
51fc2aa8
 		}
e3aaff8e
 	}
e2875303
 #ifdef	CL_THREAD_SAFE
 	pthread_mutex_unlock(&tables_mutex);
 #endif
e3aaff8e
 
3f3f9085
 #ifdef HAVE_BACKTRACE
02927896
 	segv = signal(SIGSEGV, sigsegv);
 #endif
 
89670d69
 	/*
45dc1456
 	 * Is it a UNIX style mbox with more than one
89670d69
 	 * mail message, or just a single mail message?
45dc1456
 	 *
 	 * TODO: It would be better if we called cli_scandir here rather than
 	 * in cli_scanmail. Then we could improve the way mailboxes with more
 	 * than one message is handled, e.g. stopping parsing when an infected
 	 * message is stopped, and giving a better indication of which message
 	 * within the mailbox is infected
89670d69
 	 */
16e6bdcb
 	if((strncmp(buffer, "From ", 5) == 0) && isalnum(buffer[5])) {
e3aaff8e
 		/*
049a18b9
 		 * Have been asked to check a UNIX style mbox file, which
 		 * may contain more than one e-mail message to decode
f003b79e
 		 *
 		 * It would be far better for scanners.c to do this splitting
 		 * and do this
 		 *	FOR EACH mail in the mailbox
 		 *	DO
 		 *		pass this mail to cli_mbox --
 		 *		scan this file
 		 *		IF this file has a virus quit
 		 *		THEN
 		 *			return CL_VIRUS
 		 *		FI
 		 *	END
 		 * This would remove a problem with this code that it can
 		 * fill up the tmp directory before it starts scanning
e3aaff8e
 		 */
ddea752e
 		bool lastLineWasEmpty;
 		int messagenumber;
 		message *m = messageCreate();
 
 		if(m == NULL) {
 			fclose(fd);
 #ifdef HAVE_BACKTRACE
 			signal(SIGSEGV, segv);
 #endif
5cdb01fc
 #ifdef	CL_DEBUG
 			unlink(tmpfilename);
 #endif
ddea752e
 			return CL_EMEM;
 		}
 
 		lastLineWasEmpty = FALSE;
 		messagenumber = 1;
e3aaff8e
 
049a18b9
 		do {
89670d69
 			cli_chomp(buffer);
16e6bdcb
 			if(lastLineWasEmpty && (strncmp(buffer, "From ", 5) == 0) && isalnum(buffer[5])) {
f35bc674
 				cli_dbgmsg("Deal with email number %d\n", messagenumber++);
e3aaff8e
 				/*
89670d69
 				 * End of a message in the mail box
e3aaff8e
 				 */
b2223aad
 				body = parseEmailHeaders(m, rfc821);
4f1d0bfc
 				if(body == NULL) {
 					messageReset(m);
 					continue;
 				}
89670d69
 				messageDestroy(m);
 				if(messageGetBody(body))
b0b860f1
 					if(!parseEmailBody(body, NULL, dir, rfc821, subtype, options)) {
e17491b2
 						messageReset(body);
 						m = body;
 						continue;
 					}
e3aaff8e
 				/*
89670d69
 				 * Starting a new message, throw away all the
f24bf390
 				 * information about the old one. It would
 				 * be best to be able to scan this message
 				 * now, but cli_scanfile needs arguments
 				 * that haven't been passed here so it can't be
 				 * called
e3aaff8e
 				 */
89670d69
 				m = body;
 				messageReset(body);
e3aaff8e
 
049a18b9
 				cli_dbgmsg("Finished processing message\n");
89670d69
 			} else
547b89de
 				lastLineWasEmpty = (bool)(buffer[0] == '\0');
4945127a
 
fa5661be
 			if(isuuencodebegin(buffer)) {
5198de85
 				/*
4945127a
 				 * Fast track visa to uudecode.
 				 * TODO: binhex, yenc
 				 */
3953039b
 				if(uudecodeFile(m, buffer, dir, fd) < 0)
fa5661be
 					if(messageAddStr(m, buffer) < 0)
 						break;
 			} else
4945127a
 				if(messageAddStr(m, buffer) < 0)
 					break;
4b187745
 		} while(fgets(buffer, sizeof(buffer) - 1, fd) != NULL);
f35bc674
 
ddea752e
 		fclose(fd);
 
f24bf390
 		cli_dbgmsg("Extract attachments from email %d\n", messagenumber);
ddea752e
 		body = parseEmailHeaders(m, rfc821);
 		messageDestroy(m);
4f1d0bfc
 	} else {
7e577f26
 		/*
 		 * It's a single message, parse the headers then the body
4f1d0bfc
 		 */
69543a9d
 		if(strncmp(buffer, "P I ", 4) == 0)
 			/*
 			 * CommuniGate Pro format: ignore headers until
 			 * blank line
 			 */
4b187745
 			while((fgets(buffer, sizeof(buffer) - 1, fd) != NULL) &&
69543a9d
 				(strchr("\r\n", buffer[0]) == NULL))
 					;
 		/*
 		 * Ignore any blank lines at the top of the message
 		 */
4f1d0bfc
 		while(strchr("\r\n", buffer[0]) &&
d8142abc
 		     (getline_from_mbox(buffer, sizeof(buffer) - 1, fd) != NULL))
87c9313e
 			;
 
9ed148a8
 		buffer[sizeof(buffer) - 1] = '\0';
4b187745
 
ae5c693a
 		body = parseEmailFile(fd, rfc821, buffer, dir);
ddea752e
 		fclose(fd);
4f1d0bfc
 	}
7e577f26
 
ef822cfc
 	/*
 	 * This is not necessarily true, but since the only options are
 	 * CL_CLEAN and CL_VIRUS this is the better choice. It would be
 	 * nice to have CL_CONTINUESCANNING or something like that
 	 */
 	retcode = CL_CLEAN;
049a18b9
 
4f1d0bfc
 	if(body) {
 		/*
 		 * Write out the last entry in the mailbox
 		 */
 		if(messageGetBody(body))
b0b860f1
 			if(!parseEmailBody(body, NULL, dir, rfc821, subtype, options))
b143af46
 				retcode = CL_EFORMAT;
e3aaff8e
 
4f1d0bfc
 		/*
 		 * Tidy up and quit
 		 */
 		messageDestroy(body);
 	}
e3aaff8e
 
 	cli_dbgmsg("cli_mbox returning %d\n", retcode);
 
3f3f9085
 #ifdef HAVE_BACKTRACE
02927896
 	signal(SIGSEGV, segv);
 #endif
 
5cdb01fc
 #ifdef	CL_DEBUG
 	unlink(tmpfilename);
 #endif
e3aaff8e
 	return retcode;
 }
 
 /*
ddea752e
  * Read in an email message from fin, parse it, and return the message
7e577f26
  *
ddea752e
  * FIXME: files full of new lines and nothing else are
  * handled ungracefully...
  */
 static message *
ae5c693a
 parseEmailFile(FILE *fin, const table_t *rfc821, const char *firstLine, const char *dir)
ddea752e
 {
 	bool inHeader = TRUE;
 	bool contMarker = FALSE;
06466233
 	bool lastWasBlank = FALSE, lastBodyLineWasBlank = FALSE;
ddea752e
 	message *ret;
 	bool anyHeadersFound = FALSE;
 	int commandNumber = -1;
41b7a56b
 	char *fullline = NULL, *boundary = NULL;
ddea752e
 	size_t fulllinelength = 0;
85bb253e
 	char buffer[RFC2821LENGTH + 1];
ddea752e
 
 	cli_dbgmsg("parseEmailFile\n");
 
 	ret = messageCreate();
 	if(ret == NULL)
 		return NULL;
 
 	strcpy(buffer, firstLine);
 	do {
72cf1461
 		char *line;
ddea752e
 
 		(void)cli_chomp(buffer);
 
72cf1461
 		line = buffer;
 
 		if(line[0] == '\0')
 			line = NULL;
ddea752e
 
 		/*
 		 * Don't blank lines which are only spaces from headers,
 		 * otherwise they'll be treated as the end of header marker
 		 */
41b7a56b
 		if(lastWasBlank) {
 			lastWasBlank = FALSE;
 			if(boundaryStart(buffer, boundary)) {
 				cli_dbgmsg("Found a header line with space that should be blank\n");
 				inHeader = FALSE;
 			}
 		}
 		if(boundary) {
 			free(boundary);
 			boundary = NULL;
 		}
ddea752e
 		if(inHeader) {
ceabee13
 			cli_dbgmsg("parseEmailFile: check '%s' contMarker %d fullline %p\n",
41b7a56b
 				buffer ? buffer : "", (int)contMarker, fullline);
72cf1461
 			if(line && isspace(line[0])) {
41b7a56b
 				char copy[sizeof(buffer)];
 
 				strcpy(copy, buffer);
 				strstrip(copy);
 				if(copy[0] == '\0') {
 					/*
4d4166a9
 					 * The header line contains only white
 					 * space. This is not the end of the
 					 * headers according to RFC2822, but
 					 * some MUAs will handle it as though
 					 * it were, and virus writers exploit
 					 * this bug. We can't just break from
 					 * the loop here since that would allow
 					 * other exploits such as inserting a
 					 * white space line before the
 					 * content-type line. So we just have
 					 * to make a best guess. Sigh.
41b7a56b
 					 */
 					if(fullline) {
 						if(parseEmailHeader(ret, fullline, rfc821) < 0)
 							continue;
 
 						free(fullline);
 						fullline = NULL;
 					}
4d4166a9
 					if((boundary = (char *)messageFindArgument(ret, "boundary")) != NULL) {
41b7a56b
 						lastWasBlank = TRUE;
 						continue;
 					}
 				}
 			}
72cf1461
 			if((line == NULL) && (fullline == NULL)) {	/* empty line */
ddea752e
 				if(!contMarker) {
 					/*
 					 * A blank line signifies the end of
 					 * the header and the start of the text
 					 */
5860ae08
 					if(!anyHeadersFound)
 						/* Ignore the junk at the top */
 						continue;
 
ddea752e
 					cli_dbgmsg("End of header information\n");
 					inHeader = FALSE;
 				} else
 					contMarker = FALSE;
 			} else {
 				char *ptr;
 				const char *qptr;
d6d5763c
 				int lookahead;
ddea752e
 
 				if(fullline == NULL) {
85bb253e
 					char cmd[RFC2821LENGTH + 1], out[RFC2821LENGTH + 1];
ddea752e
 
 					/*
 					 * Continuation of line we're ignoring?
 					 */
9f2024cc
 					if(isblank(line[0])) {
72cf1461
 						contMarker = continuationMarker(line);
ddea752e
 						continue;
 					}
 
 					/*
 					 * Is this a header we're interested in?
 					 */
72cf1461
 					if((strchr(line, ':') == NULL) ||
 					   (cli_strtokbuf(line, 0, ":", cmd) == NULL)) {
 						if(strncmp(line, "From ", 5) == 0)
ddea752e
 							anyHeadersFound = TRUE;
 						continue;
 					}
 
d72749e0
 					ptr = rfc822comments(cmd, out);
ddea752e
 					commandNumber = tableFind(rfc821, ptr ? ptr : cmd);
 
 					switch(commandNumber) {
 						case CONTENT_TRANSFER_ENCODING:
 						case CONTENT_DISPOSITION:
 						case CONTENT_TYPE:
 							anyHeadersFound = TRUE;
 							break;
 						default:
 							if(!anyHeadersFound)
 								anyHeadersFound = usefulHeader(commandNumber, cmd);
 							continue;
 					}
72cf1461
 					fullline = strdup(line);
 					fulllinelength = strlen(line) + 1;
 				} else if(line != NULL) {
 					fulllinelength += strlen(line);
468c0f21
 					ptr = cli_realloc(fullline, fulllinelength);
 					if(ptr == NULL)
 						continue;
 					fullline = ptr;
72cf1461
 					strcat(fullline, line);
ddea752e
 				}
 
72cf1461
 				if(line) {
 					contMarker = continuationMarker(line);
ddea752e
 
d6d5763c
 					if(contMarker)
 						continue;
 				} else
 					contMarker = FALSE;
ddea752e
 
 				assert(fullline != NULL);
 
 				lookahead = getc(fin);
 				if(lookahead != EOF) {
 					ungetc(lookahead, fin);
 
 					/*
 					 * Section B.2 of RFC822 says TAB or
 					 * SPACE means a continuation of the
 					 * previous entry.
 					 *
 					 * Add all the arguments on the line
 					 */
9f2024cc
 					if(isblank(lookahead))
ddea752e
 						continue;
 				}
 
72cf1461
 				if(line) {
d6d5763c
 					int quotes = 0;
 					for(qptr = fullline; *qptr; qptr++)
 						if(*qptr == '\"')
 							quotes++;
ddea752e
 
d6d5763c
 					if(quotes & 1)
 						continue;
 				}
ddea752e
 
d72749e0
 				ptr = rfc822comments(fullline, NULL);
ddea752e
 				if(ptr) {
 					free(fullline);
 					fullline = ptr;
 				}
 
 				if(parseEmailHeader(ret, fullline, rfc821) < 0)
 					continue;
 
 				free(fullline);
 				fullline = NULL;
 			}
fa5661be
 		} else if(line && isuuencodebegin(line)) {
ae5c693a
 			/*
 			 * Fast track visa to uudecode.
 			 * TODO: binhex, yenc
 			 */
3953039b
 			if(uudecodeFile(ret, line, dir, fin) < 0)
fa5661be
 				if(messageAddStr(ret, line) < 0)
 					break;
06466233
 		} else {
 			if(line == NULL) {
 				if(lastBodyLineWasBlank) {
 					cli_dbgmsg("Ignoring consecutive blank lines in the body\n");
 					continue;
 				}
 				lastBodyLineWasBlank = TRUE;
 			} else
 				lastBodyLineWasBlank = FALSE;
 
72cf1461
 			if(messageAddStr(ret, line) < 0)
ddea752e
 				break;
06466233
 		}
d8142abc
 	} while(getline_from_mbox(buffer, sizeof(buffer) - 1, fin) != NULL);
ddea752e
 
 	if(fullline) {
 		if(*fullline) switch(commandNumber) {
 			case CONTENT_TRANSFER_ENCODING:
 			case CONTENT_DISPOSITION:
 			case CONTENT_TYPE:
aaaae842
 				cli_dbgmsg("parseEmailHeaders: Fullline unparsed '%s'\n", fullline);
ddea752e
 		}
 		free(fullline);
 	}
 
 	if(!anyHeadersFound) {
 		/*
 		 * False positive in believing we have an e-mail when we don't
 		 */
 		messageDestroy(ret);
 		cli_dbgmsg("parseEmailFile: no headers found, assuming it isn't an email\n");
 		return NULL;
 	}
 
 	messageClean(ret);
 
 	cli_dbgmsg("parseEmailFile: return\n");
 
 	return ret;
 }
 
 /*
  * The given message contains a raw e-mail.
e06d34dc
  *
  * Returns the message's body with the correct arguments set
f73920a4
  *
  * The downside of this approach is that for a short time we have two copies
  * of the message in memory, the upside is that it makes for easier parsing
  * of encapsulated messages, and in the long run uses less memory in those
  * scenarios
ddea752e
  *
  * TODO: remove the duplication with parseEmailFile
7e577f26
  */
e06d34dc
 static message *
b2223aad
 parseEmailHeaders(const message *m, const table_t *rfc821)
7e577f26
 {
e06d34dc
 	bool inHeader = TRUE;
b2223aad
 	const text *t;
89670d69
 	message *ret;
4f1d0bfc
 	bool anyHeadersFound = FALSE;
15033cb6
 	int commandNumber = -1;
efb5f16c
 	char *fullline = NULL;
2ad0c86e
 	size_t fulllinelength = 0;
89670d69
 
02927896
 	cli_dbgmsg("parseEmailHeaders\n");
 
89670d69
 	if(m == NULL)
 		return NULL;
 
 	ret = messageCreate();
7e577f26
 
b2223aad
 	for(t = messageGetBody(m); t; t = t->t_next) {
 		const char *buffer;
7e577f26
 
b2223aad
 		if(t->t_line)
 			buffer = lineGetData(t->t_line);
 		else
02927896
 			buffer = NULL;
7e577f26
 
28010d29
 		if(inHeader) {
4e75d9b6
 			cli_dbgmsg("parseEmailHeaders: check '%s'\n",
 				buffer ? buffer : "");
ddea752e
 			if(buffer == NULL) {
4e75d9b6
 				/*
 				 * A blank line signifies the end of
 				 * the header and the start of the text
 				 */
 				cli_dbgmsg("End of header information\n");
 				inHeader = FALSE;
ad091acf
 				if(!anyHeadersFound) {
 					cli_dbgmsg("Nothing interesting in the header\n");
 					break;
 				}
2ad0c86e
 			} else {
b116962d
 				char *ptr;
2ad0c86e
 				const char *qptr;
 				int quotes;
b116962d
 
2ad0c86e
 				if(fullline == NULL) {
85bb253e
 					char cmd[RFC2821LENGTH + 1];
45aba293
 
 					/*
 					 * Continuation of line we're ignoring?
 					 */
9f2024cc
 					if(isblank(buffer[0]))
45aba293
 						continue;
 
 					/*
 					 * Is this a header we're interested in?
 					 */
b116962d
 					if((strchr(buffer, ':') == NULL) ||
 					   (cli_strtokbuf(buffer, 0, ":", cmd) == NULL)) {
 						if(strncmp(buffer, "From ", 5) == 0)
 							anyHeadersFound = TRUE;
45aba293
 						continue;
b116962d
 					}
45aba293
 
d72749e0
 					ptr = rfc822comments(cmd, NULL);
59921c02
 					commandNumber = tableFind(rfc821, ptr ? ptr : cmd);
 					if(ptr)
 						free(ptr);
45aba293
 
 					switch(commandNumber) {
 						case CONTENT_TRANSFER_ENCODING:
 						case CONTENT_DISPOSITION:
 						case CONTENT_TYPE:
b116962d
 							anyHeadersFound = TRUE;
45aba293
 							break;
 						default:
ddea752e
 							if(!anyHeadersFound)
 								anyHeadersFound = usefulHeader(commandNumber, cmd);
45aba293
 							continue;
 					}
 					fullline = strdup(buffer);
 					fulllinelength = strlen(buffer) + 1;
 				} else if(buffer) {
 					fulllinelength += strlen(buffer);
468c0f21
 					ptr = cli_realloc(fullline, fulllinelength);
 					if(ptr == NULL)
 						continue;
 					fullline = ptr;
45aba293
 					strcat(fullline, buffer);
2ad0c86e
 				}
13462674
 
ddea752e
 				assert(fullline != NULL);
2ad0c86e
 
ddea752e
 				if(t->t_next && (t->t_next->t_line != NULL))
2ad0c86e
 					/*
b116962d
 					 * Section B.2 of RFC822 says TAB or
 					 * SPACE means a continuation of the
 					 * previous entry.
2ad0c86e
 					 *
 					 * Add all the arguments on the line
 					 */
9f2024cc
 					if(isblank(lineGetData(t->t_next->t_line)[0]))
 						continue;
2ad0c86e
 
 				quotes = 0;
d6d5763c
 				for(qptr = fullline; *qptr; qptr++)
2ad0c86e
 					if(*qptr == '\"')
 						quotes++;
 
45aba293
 				if(quotes & 1)
2ad0c86e
 					continue;
 
d72749e0
 				ptr = rfc822comments(fullline, NULL);
2ad0c86e
 				if(ptr) {
 					free(fullline);
 					fullline = ptr;
 				}
c77c8809
 
ddea752e
 				if(parseEmailHeader(ret, fullline, rfc821) < 0)
 					continue;
28010d29
 
ddea752e
 				free(fullline);
 				fullline = NULL;
f12d2498
 			}
45aba293
 		} else
e17491b2
 			/*cli_dbgmsg("Add line to body '%s'\n", buffer);*/
b2223aad
 			if(messageAddLine(ret, t->t_line) < 0)
0e4e16d4
 				break;
d879a7b0
 	}
e06d34dc
 
efb5f16c
 	if(fullline) {
2ad0c86e
 		if(*fullline) switch(commandNumber) {
 			case CONTENT_TRANSFER_ENCODING:
 			case CONTENT_DISPOSITION:
 			case CONTENT_TYPE:
aaaae842
 				cli_dbgmsg("parseEmailHeaders: Fullline unparsed '%s'\n", fullline);
2ad0c86e
 		}
efb5f16c
 		free(fullline);
 	}
 
4f1d0bfc
 	if(!anyHeadersFound) {
 		/*
 		 * False positive in believing we have an e-mail when we don't
 		 */
 		messageDestroy(ret);
 		cli_dbgmsg("parseEmailHeaders: no headers found, assuming it isn't an email\n");
 		return NULL;
 	}
 
93d41ee4
 	messageClean(ret);
 
e17491b2
 	cli_dbgmsg("parseEmailHeaders: return\n");
 
e06d34dc
 	return ret;
7e577f26
 }
 
 /*
4c60b74f
  * Handle a header line of an email message
  */
 static int
393a6d67
 parseEmailHeader(message *m, const char *line, const table_t *rfc821)
4c60b74f
 {
0960ff5e
 	char *cmd;
4c60b74f
 	int ret = -1;
 #ifdef CL_THREAD_SAFE
 	char *strptr;
 #endif
97867f21
 	const char *separater;
50df4118
 	char *copy, tokenseparater[2];
4c60b74f
 
20d3dde9
 	cli_dbgmsg("parseEmailHeader '%s'\n", line);
 
97867f21
 	/*
 	 * In RFC822 the separater between the key a value is a colon,
 	 * e.g.	Content-Transfer-Encoding: base64
 	 * However some MUA's are lapse about this and virus writers exploit
 	 * this hole, so we need to check all known possiblities
 	 */
 	for(separater = ":= "; *separater; separater++)
 		if(strchr(line, *separater) != NULL)
 			break;
 
 	if(*separater == '\0')
1bfbedd4
 		return -1;
 
50df4118
 	copy = rfc2047(line);
 	if(copy == NULL)
8ebe8dbc
 		/* an RFC checker would return -1 here */
 		copy = strdup(line);
f2f25418
 
97867f21
 	tokenseparater[0] = *separater;
 	tokenseparater[1] = '\0';
 
548a5f96
 #ifdef	CL_THREAD_SAFE
97867f21
 	cmd = strtok_r(copy, tokenseparater, &strptr);
548a5f96
 #else
 	cmd = strtok(copy, tokenseparater);
 #endif
4c60b74f
 
3499d81e
 	if(cmd && (strstrip(cmd) > 0)) {
548a5f96
 #ifdef	CL_THREAD_SAFE
4c60b74f
 		char *arg = strtok_r(NULL, "", &strptr);
548a5f96
 #else
 		char *arg = strtok(NULL, "");
 #endif
4c60b74f
 
 		if(arg)
 			/*
 			 * Found a header such as
 			 * Content-Type: multipart/mixed;
 			 * set arg to be
 			 * "multipart/mixed" and cmd to
a9f386ed
 			 * be "Content-Type"
4c60b74f
 			 */
393a6d67
 			ret = parseMimeHeader(m, cmd, rfc821, arg);
4c60b74f
 	}
50df4118
 	free(copy);
4c60b74f
 	return ret;
 }
 
 /*
e3aaff8e
  * This is a recursive routine.
45dc1456
  * FIXME: We are not passed &mrec so we can't check against MAX_MAIL_RECURSION
e3aaff8e
  *
7e577f26
  * This function parses the body of mainMessage and saves its attachments in dir
  *
e06d34dc
  * mainMessage is the buffer to be parsed, it contains an e-mail's body, without
f12d2498
  * any headers. First time of calling it'll be
  * the whole message. Later it'll be parts of a multipart message
e3aaff8e
  * textIn is the plain text message being built up so far
  *
d4d14218
  * Returns:
e3aaff8e
  *	0 for fail
d110fe1c
  *	1 for success, attachments saved
  *	2 for success, attachments not saved
e3aaff8e
  */
 static int	/* success or fail */
b0b860f1
 parseEmailBody(message *messageIn, text *textIn, const char *dir, const table_t *rfc821Table, const table_t *subtypeTable, unsigned int options)
e3aaff8e
 {
b726511f
 	message **messages;	/* parts of a multipart message */
391f7bb3
 	int inMimeHead, i, rc = 1, htmltextPart, multiparts = 0;
e3aaff8e
 	text *aText;
 	const char *cptr;
ad9c6836
 	message *mainMessage;
b0b860f1
 	fileblob *fb;
e3aaff8e
 
b0b860f1
 	cli_dbgmsg("in parseEmailBody\n");
e3aaff8e
 
 	aText = textIn;
b726511f
 	messages = NULL;
ad9c6836
 	mainMessage = messageIn;
e3aaff8e
 
 	/* Anything left to be parsed? */
d4d14218
 	if(mainMessage && (messageGetBody(mainMessage) != NULL)) {
e3aaff8e
 		mime_type mimeType;
391f7bb3
 		int subtype, inhead;
9a729c80
 		const char *mimeSubtype, *boundary;
 		char *protocol;
e3aaff8e
 		const text *t_line;
98cb5cba
 		/*bool isAlternative;*/
e3aaff8e
 		message *aMessage;
 
049a18b9
 		cli_dbgmsg("Parsing mail file\n");
 
e3aaff8e
 		mimeType = messageGetMimeType(mainMessage);
 		mimeSubtype = messageGetMimeSubtype(mainMessage);
 
528c8a2d
 		/* pre-process */
8a892c3b
 		subtype = tableFind(subtypeTable, mimeSubtype);
7c5a7a47
 		if((mimeType == TEXT) && (subtype == PLAIN)) {
e3aaff8e
 			/*
 			 * This is effectively no encoding, notice that we
 			 * don't check that charset is us-ascii
 			 */
 			cli_dbgmsg("assume no encoding\n");
 			mimeType = NOMIME;
ae5c693a
 			messageSetMimeSubtype(mainMessage, "");
528c8a2d
 		} else if((mimeType == MESSAGE) &&
 			  (strcasecmp(mimeSubtype, "rfc822-headers") == 0)) {
 			/*
 			 * RFC1892/RFC3462: section 2 text/rfc822-headers
 			 * incorrectly sent as message/rfc822-headers
46d375fe
 			 *
 			 * Parse as text/plain, i.e. no mime
528c8a2d
 			 */
 			cli_dbgmsg("Changing message/rfc822-headers to text/rfc822-headers\n");
46d375fe
 			mimeType = NOMIME;
ae5c693a
 			messageSetMimeSubtype(mainMessage, "");
e3aaff8e
 		}
 
049a18b9
 		cli_dbgmsg("mimeType = %d\n", mimeType);
 
e3aaff8e
 		switch(mimeType) {
 		case NOMIME:
6fd711b2
 			cli_dbgmsg("Not a mime encoded message\n");
e3aaff8e
 			aText = textAddMessage(aText, mainMessage);
 			break;
 		case TEXT:
8a892c3b
 			/* text/plain has been preprocessed as no encoding */
 			if((options&CL_SCAN_MAILURL) && (subtype == HTML))
7c5a7a47
 				checkURLs(mainMessage, dir);
e3aaff8e
 			break;
 		case MULTIPART:
c8a7cef0
 			cli_dbgmsg("Content-type 'multipart' handler\n");
e3aaff8e
 			boundary = messageFindArgument(mainMessage, "boundary");
 
 			if(boundary == NULL) {
 				cli_warnmsg("Multipart MIME message contains no boundaries\n");
e2e7ebf5
 				/* Broken e-mail message */
 				mimeType = NOMIME;
 				/*
 				 * The break means that we will still
 				 * check if the file contains a uuencoded file
 				 */
 				break;
e3aaff8e
 			}
 
c79a2273
 			/* Perhaps it should assume mixed? */
cb5a87e0
 			if(mimeSubtype[0] == '\0') {
 				cli_warnmsg("Multipart has no subtype assuming alternative\n");
 				mimeSubtype = "alternative";
 				messageSetMimeSubtype(mainMessage, "alternative");
 			}
 
e3aaff8e
 			/*
 			 * Get to the start of the first message
 			 */
20d3dde9
 			t_line = messageGetBody(mainMessage);
 
 			if(t_line == NULL) {
 				cli_warnmsg("Multipart MIME message has no body\n");
 				free((char *)boundary);
 				mimeType = NOMIME;
 				break;
 			}
 
 			do
bae9c53f
 				if(t_line->t_line) {
 					if(boundaryStart(lineGetData(t_line->t_line), boundary))
 						break;
 					/*
182bbcc8
 					 * Found a binhex file before
ebe57840
 					 *	the first multipart
b116962d
 					 * TODO: check yEnc
bae9c53f
 					 */
182bbcc8
 					if(binhexBegin(mainMessage) == t_line) {
b116962d
 						if(messageGetEncoding(mainMessage) == NOENCODING) {
 							messageSetEncoding(mainMessage, "x-binhex");
 							fb = messageToFileblob(mainMessage, dir);
 
 							if(fb)
 								fileblobDestroy(fb);
 						}
99c2299d
 					} else if(encodingLine(mainMessage) == t_line->t_next) {
 						/*
 						 * We look for the next line
 						 * since later on we'll skip
 						 * over the important line when
 						 * we think it's a blank line
 						 * at the top of the message -
 						 * which it would have been in
 						 * an RFC compliant world
 						 */
 						cli_dbgmsg("Found MIME attachment before the first MIME section\n");
 						if(messageGetEncoding(mainMessage) == NOENCODING)
 							break;
b116962d
 					}
bae9c53f
 				}
20d3dde9
 			while((t_line = t_line->t_next) != NULL);
e3aaff8e
 
 			if(t_line == NULL) {
28010d29
 				cli_dbgmsg("Multipart MIME message contains no boundary lines\n");
5a642650
 				/*
 				 * Free added by Thomas Lamy
 				 * <Thomas.Lamy@in-online.net>
 				 */
 				free((char *)boundary);
e2e7ebf5
 				mimeType = NOMIME;
 				/*
 				 * The break means that we will still
182bbcc8
 				 * check if the file contains a yEnc/binhex file
e2e7ebf5
 				 */
 				break;
e3aaff8e
 			}
 			/*
 			 * Build up a table of all of the parts of this
 			 * multipart message. Remember, each part may itself
 			 * be a multipart message.
 			 */
 			inhead = 1;
 			inMimeHead = 0;
 
e06d34dc
 			/*
9a729c80
 			 * Parse the mainMessage object and create an array
 			 * of objects called messages, one for each of the
 			 * multiparts that mainMessage contains
 			 *
e06d34dc
 			 * This looks like parseEmailHeaders() - maybe there's
 			 * some duplication of code to be cleaned up
 			 */
b726511f
 			for(multiparts = 0; t_line; multiparts++) {
56ae62e2
 				int lines = 0;
1a74d4df
 				message **m;
56ae62e2
 
1a74d4df
 				m = cli_realloc(messages, ((multiparts + 1) * sizeof(message *)));
f12d2498
 				if(m == NULL)
1a74d4df
 					break;
 				messages = m;
b726511f
 
e3aaff8e
 				aMessage = messages[multiparts] = messageCreate();
3f3f9085
 				if(aMessage == NULL) {
 					multiparts--;
 					continue;
 				}
e3aaff8e
 
 				cli_dbgmsg("Now read in part %d\n", multiparts);
 
8ba634a9
 				/*
 				 * Ignore blank lines. There shouldn't be ANY
 				 * but some viruses insert them
 				 */
02927896
 				while((t_line = t_line->t_next) != NULL)
b2223aad
 					if(t_line->t_line &&
 					   /*(cli_chomp(t_line->t_text) > 0))*/
 					   (strlen(lineGetData(t_line->t_line)) > 0))
d79597e3
 						break;
8ba634a9
 
 				if(t_line == NULL) {
 					cli_dbgmsg("Empty part\n");
b9ce9639
 					/*
 					 * Remove this part unless there's
182bbcc8
 					 * a binhex portion somewhere in
b9ce9639
 					 * the complete message that we may
 					 * throw away by mistake if the MIME
 					 * encoding information is incorrect
 					 */
182bbcc8
 					if(binhexBegin(mainMessage) == NULL) {
b9ce9639
 						messageDestroy(aMessage);
 						--multiparts;
 					}
8ba634a9
 					continue;
 				}
 
 				do {
b2223aad
 					const char *line = lineGetData(t_line->t_line);
e3aaff8e
 
fa5661be
 					/*cli_dbgmsg("multipart %d: inMimeHead %d inhead %d boundary '%s' line '%s' next '%s'\n",
 						multiparts, inMimeHead, inhead, boundary, line,
391f7bb3
 						t_line->t_next && t_line->t_next->t_line ? lineGetData(t_line->t_next->t_line) : "(null)");*/
e3aaff8e
 
f1c1300c
 					if(inMimeHead) {	/* continuation line */
02927896
 						if(line == NULL) {
59b99810
 							/*inhead =*/ inMimeHead = 0;
02927896
 							continue;
 						}
3a978f7d
 						/*
 						 * Handle continuation lines
 						 * because the previous line
1eec55a6
 						 * ended with a ; or this line
 						 * starts with a white space
3a978f7d
 						 */
1eec55a6
 						cli_dbgmsg("Multipart %d: About to add mime Argument '%s'\n",
 							multiparts, line);
3a978f7d
 						/*
 						 * Handle the case when it
 						 * isn't really a continuation
 						 * line:
 						 * Content-Type: application/octet-stream;
 						 * Content-Transfer-Encoding: base64
 						 */
 						parseEmailHeader(aMessage, line, rfc821Table);
 
e3aaff8e
 						while(isspace((int)*line))
 							line++;
 
 						if(*line == '\0') {
 							inhead = inMimeHead = 0;
 							continue;
 						}
 						/*
 						 * This may cause a trailing ';'
 						 * to be added if this test
 						 * fails - TODO: verify this
 						 */
 						inMimeHead = continuationMarker(line);
 						messageAddArgument(aMessage, line);
f1c1300c
 					} else if(inhead) {	/* handling normal headers */
c8a7cef0
 						int quotes;
 						char *fullline, *ptr;
 						const char *qptr;
 						const text *next;
2ad0c86e
 
02927896
 						if(line == NULL) {
7e67e382
 							/*
 							 * empty line, should the end of the headers,
 							 * but some base64 decoders, e.g. uudeview, are broken
 							 * and will handle this type of entry, decoding the
 							 * base64 content...
 							 * Content-Type: application/octet-stream; name=text.zip
 							 * Content-Transfer-Encoding: base64
 							 * Content-Disposition: attachment; filename="text.zip"
5198de85
 							 *
7e67e382
 							 * Content-Disposition: attachment;
 							 *	filename=text.zip
 							 * Content-Type: application/octet-stream;
 							 *	name=text.zip
 							 * Content-Transfer-Encoding: base64
5198de85
 							 *
7e67e382
 							 * UEsDBAoAAAAAAACgPjJ2RHw676gAAO+oAABEAAAAbWFpbF90ZXh0LWluZm8udHh0ICAgICAgICAg
 							 */
 							next = t_line->t_next;
 							if(next && next->t_line) {
 								const char *data = lineGetData(next->t_line);
5b76248c
 
 								if((messageGetEncoding(aMessage) == NOENCODING) &&
 								   (messageGetMimeType(aMessage) == APPLICATION))
d72749e0
 									/*
 									 * Handle this nightmare (note the blank
 									 * line in the header and the incorrect
 									 * content-transfer-encoding header)
 									 *
 									 * Content-Type: application/octet-stream; name="zipped_files.EXEX-Spanska: Yes
 									 *
 									 * r-Encoding: base64
 									 * Content-Disposition: attachment; filename="zipped_files.EXE"
 									 */
 									if(strstr(data, "base64")) {
5b76248c
 										messageSetEncoding(aMessage, "base64");
 										cli_dbgmsg("Ignoring fake end of headers\n");
 										continue;
 									}
5cdb01fc
 								if((strncmp(data, "Content", 7) == 0) ||
 								   (strncmp(data, "filename=", 9) == 0)) {
7e67e382
 									cli_dbgmsg("Ignoring fake end of headers\n");
 									continue;
 								}
 							}
59b99810
 							cli_dbgmsg("Multipart %d: End of header information\n",
 								multiparts);
e3aaff8e
 							inhead = 0;
 							continue;
 						}
c76810dc
 						if(isspace((int)*line)) {
 							/*
 							 * The first line is
 							 * continuation line.
 							 * This is tricky
 							 * to handle, but
 							 * all we can do is our
 							 * best
 							 */
 							cli_dbgmsg("Part %d starts with a continuation line\n",
 								multiparts);
 							messageAddArgument(aMessage, line);
 							/*
 							 * Give it a default
 							 * MIME type since
 							 * that may be the
 							 * missing line
 							 *
 							 * Choose application to
 							 * force a save
 							 */
 							if(messageGetMimeType(aMessage) == NOMIME)
 								messageSetMimeType(aMessage, "application");
 							continue;
 						}
 
c8a7cef0
 						inMimeHead = FALSE;
b2223aad
 
85bb253e
 						assert(strlen(line) <= RFC2821LENGTH);
f1c1300c
 
d72749e0
 						fullline = rfc822comments(line, NULL);
c8a7cef0
 						if(fullline == NULL)
 							fullline = strdup(line);
2ad0c86e
 
c8a7cef0
 						quotes = 0;
 						for(qptr = fullline; *qptr; qptr++)
 							if(*qptr == '\"')
 								quotes++;
f1c1300c
 
c8a7cef0
 						/*
 						 * Fold next lines to the end of this
 						 * if they start with a white space
 						 * or if this line has an odd number of quotes:
 						 * Content-Type: application/octet-stream; name="foo
 						 * "
 						 */
 						next = t_line->t_next;
 						while(next && next->t_line) {
 							const char *data = lineGetData(next->t_line);
1eec55a6
 
04c39f39
 							/*if((!isspace(data[0])) &&
c8a7cef0
 							   ((quotes & 1) == 0))
04c39f39
 								break;*/
 							if(!isspace(data[0]))
c8a7cef0
 								break;
f1c1300c
 
f1d57230
 							if(data[1] == '\0') {
 								/*
 								 * Broken message: the
 								 * blank line at the end
 								 * of the headers isn't blank -
 								 * it contains a space
 								 */
 								cli_dbgmsg("Multipart %d: headers not terminated by blank line\n",
 									multiparts);
 								inhead = FALSE;
 								break;
 							}
 
c8a7cef0
 							ptr = cli_realloc(fullline,
 								strlen(fullline) + strlen(data) + 1);
303f9be9
 
c8a7cef0
 							if(ptr == NULL)
 								break;
1eec55a6
 
c8a7cef0
 							fullline = ptr;
 							strcat(fullline, data);
2ad0c86e
 
04c39f39
 							/*for(qptr = data; *qptr; qptr++)
c8a7cef0
 								if(*qptr == '\"')
04c39f39
 									quotes++;*/
2ad0c86e
 
c8a7cef0
 							t_line = next;
 							next = next->t_next;
1eec55a6
 						}
c8a7cef0
 						cli_dbgmsg("Multipart %d: About to parse folded header '%s'\n",
 							multiparts, fullline);
 
 						parseEmailHeader(aMessage, fullline, rfc821Table);
 						free(fullline);
e3aaff8e
 					} else if(endOfMessage(line, boundary)) {
 						/*
 						 * Some viruses put information
 						 * *after* the end of message,
 						 * which presumably some broken
 						 * mail clients find, so we
 						 * can't assume that this
 						 * is the end of the message
 						 */
 						/* t_line = NULL;*/
 						break;
391f7bb3
 					} else if(boundaryStart(line, boundary)) {
 						inhead = 1;
 						break;
56ae62e2
 					} else {
b2223aad
 						if(messageAddLine(aMessage, t_line->t_line) < 0)
1a74d4df
 							break;
56ae62e2
 						lines++;
 					}
8ba634a9
 				} while((t_line = t_line->t_next) != NULL);
 
e3aaff8e
 				messageClean(aMessage);
56ae62e2
 
 				cli_dbgmsg("Part %d has %d lines\n",
 					multiparts, lines);
e3aaff8e
 			}
 
 			free((char *)boundary);
 
7c1eb3bf
 			/*
c79a2273
 			 * Preprocess. Anything special to be done before
 			 * we handle the multiparts?
9a729c80
 			 */
c79a2273
 			switch(tableFind(subtypeTable, mimeSubtype)) {
 				case KNOWBOT:
 					/* TODO */
 					cli_dbgmsg("multipart/knowbot parsed as multipart/mixed for now\n");
 					mimeSubtype = "mixed";
 					break;
5d8100cb
 				case -1:
 					/*
 					 * According to section 7.2.6 of
 					 * RFC1521, unrecognised multiparts
 					 * should be treated as multipart/mixed.
 					 */
38d07186
 					cli_dbgmsg("Unsupported multipart format `%s', parsed as mixed\n", mimeSubtype);
5d8100cb
 					mimeSubtype = "mixed";
 					break;
c79a2273
 			}
9a729c80
 
 			/*
7c1eb3bf
 			 * We've finished message we're parsing
 			 */
 			if(mainMessage && (mainMessage != messageIn)) {
 				messageDestroy(mainMessage);
 				mainMessage = NULL;
ad9c6836
 			}
e3aaff8e
 
b726511f
 			if(multiparts == 0) {
 				if(messages)
 					free(messages);
7c1eb3bf
 				return 2;	/* Nothing to do */
b726511f
 			}
7c1eb3bf
 
e3aaff8e
 			cli_dbgmsg("The message has %d parts\n", multiparts);
393a6d67
 			cli_dbgmsg("Find out the multipart type (%s)\n", mimeSubtype);
e3aaff8e
 
9a729c80
 			/*
 			 * We now have all the parts of the multipart message
 			 * in the messages array:
 			 *	message *messages[multiparts]
 			 * Let's decide what to do with them all
 			 */
e3aaff8e
 			switch(tableFind(subtypeTable, mimeSubtype)) {
 			case RELATED:
e06d34dc
 				cli_dbgmsg("Multipart related handler\n");
e3aaff8e
 				/*
294d0774
 				 * Have a look to see if there's HTML code
 				 * which will need scanning
e3aaff8e
 				 */
 				aMessage = NULL;
 				assert(multiparts > 0);
 
d4d14218
 				htmltextPart = getTextPart(messages, multiparts);
e3aaff8e
 
d4d14218
 				if(htmltextPart >= 0)
 					aText = textAddMessage(aText, messages[htmltextPart]);
e3aaff8e
 				else
 					/*
294d0774
 					 * There isn't an HTML bit. If there's a
 					 * multipart bit, it'll may be in there
 					 * somewhere
e3aaff8e
 					 */
 					for(i = 0; i < multiparts; i++)
 						if(messageGetMimeType(messages[i]) == MULTIPART) {
 							aMessage = messages[i];
d4d14218
 							htmltextPart = i;
e3aaff8e
 							break;
 						}
 
59da5a4f
 				if(htmltextPart == -1)
294d0774
 					cli_dbgmsg("No HTML code found to be scanned");
59da5a4f
 				else {
b0b860f1
 					rc = parseEmailBody(aMessage, aText, dir, rfc821Table, subtypeTable, options);
59da5a4f
 					if(rc == 1) {
 						assert(aMessage == messages[htmltextPart]);
 						messageDestroy(aMessage);
 						messages[htmltextPart] = NULL;
 					}
 				}
e3aaff8e
 
 				/*
 				 * Fixed based on an idea from Stephen White <stephen@earth.li>
 				 * The message is confused about the difference
 				 * between alternative and related. Badtrans.B
 				 * suffers from this problem.
 				 *
 				 * Fall through in this case:
 				 * Content-Type: multipart/related;
 				 *	type="multipart/alternative"
 				 */
98cb5cba
 				/*
 				 * Changed to always fall through based on
 				 * an idea from Michael Dankov <misha@btrc.ru>
 				 * that some viruses are completely confused
 				 * about the difference between related
 				 * and mixed
 				 */
 				/*cptr = messageFindArgument(mainMessage, "type");
e3aaff8e
 				if(cptr == NULL)
 					break;
 				isAlternative = (bool)(strcasecmp(cptr, "multipart/alternative") == 0);
 				free((char *)cptr);
 				if(!isAlternative)
98cb5cba
 					break;*/
ba867aed
 			case DIGEST:
 				/*
 				 * According to section 5.1.5 RFC2046, the
 				 * default mime type of multipart/digest parts
 				 * is message/rfc822
 				 *
 				 * We consider them as alternative, wrong in
 				 * the strictest sense since they aren't
 				 * alternatives - all parts a valid - but it's
 				 * OK for our needs since it means each part
 				 * will be scanned
 				 */
e3aaff8e
 			case ALTERNATIVE:
 				cli_dbgmsg("Multipart alternative handler\n");
 
 				/*
 				 * Fall through - some clients are broken and
 				 * say alternative instead of mixed. The Klez
5d8100cb
 				 * virus is broken that way, and anyway we
 				 * wish to scan all of the alternatives
e3aaff8e
 				 */
 			case REPORT:
 				/*
 				 * According to section 1 of RFC1892, the
 				 * syntax of multipart/report is the same
 				 * as multipart/mixed. There are some required
 				 * parameters, but there's no need for us to
 				 * verify that they exist
 				 */
 			case MIXED:
c9b8f252
 			case APPLEDOUBLE:	/* not really supported */
e3aaff8e
 				/*
 				 * Look for attachments
 				 *
 				 * Not all formats are supported. If an
 				 * unsupported format turns out to be
 				 * common enough to implement, it is a simple
 				 * matter to add it
 				 */
ad9c6836
 				if(aText) {
 					if(mainMessage && (mainMessage != messageIn))
 						messageDestroy(mainMessage);
e3aaff8e
 					mainMessage = NULL;
ad9c6836
 				}
e3aaff8e
 
 				cli_dbgmsg("Mixed message with %d parts\n", multiparts);
 				for(i = 0; i < multiparts; i++) {
 					bool addToText = FALSE;
 					const char *dtype;
b0b860f1
 #ifndef	SAVE_TO_DISC
89670d69
 					message *body;
f12d2498
 #endif
e3aaff8e
 
 					aMessage = messages[i];
 
59da5a4f
 					if(aMessage == NULL)
 						continue;
e3aaff8e
 
 					cli_dbgmsg("Mixed message part %d is of type %d\n",
 						i, messageGetMimeType(aMessage));
 
 					switch(messageGetMimeType(aMessage)) {
 					case APPLICATION:
72cf1461
 					case AUDIO:
 					case IMAGE:
 					case VIDEO:
e3aaff8e
 						break;
 					case NOMIME:
6e84cebb
 						cli_dbgmsg("No mime headers found in multipart part %d\n", i);
51fc2aa8
 						if(mainMessage) {
182bbcc8
 							if(binhexBegin(aMessage)) {
 								cli_dbgmsg("Found binhex message in multipart/mixed mainMessage\n");
 								messageSetEncoding(mainMessage, "x-bunhex");
0e5a0129
 								fb = messageToFileblob(mainMessage, dir);
51fc2aa8
 
0e5a0129
 								if(fb)
 									fileblobDestroy(fb);
51fc2aa8
 							}
 							if(mainMessage != messageIn)
 								messageDestroy(mainMessage);
 							mainMessage = NULL;
391f7bb3
 						} else if(aMessage) {
182bbcc8
 							if(binhexBegin(aMessage)) {
c29f01c5
 								cli_dbgmsg("Found binhex message in multipart/mixed non mime part\n");
 								messageSetEncoding(aMessage, "x-binhex");
 								fb = messageToFileblob(aMessage, dir);
 
 								if(fb)
 									fileblobDestroy(fb);
 								assert(aMessage == messages[i]);
 								messageReset(messages[i]);
391f7bb3
 							}
51fc2aa8
 						}
e3aaff8e
 						addToText = TRUE;
 						if(messageGetBody(aMessage) == NULL)
 							/*
 							 * No plain text version
 							 */
db72c9d4
 							cli_dbgmsg("No plain text alternative");
e3aaff8e
 						break;
 					case TEXT:
0e523db2
 						dtype = messageGetDispositionType(aMessage);
d110fe1c
 						cli_dbgmsg("Mixed message text part disposition \"%s\"\n",
 							dtype);
e3aaff8e
 						if(strcasecmp(dtype, "attachment") == 0)
4ab382c3
 							break;
 						if((*dtype == '\0') || (strcasecmp(dtype, "inline") == 0)) {
ad9c6836
 							if(mainMessage && (mainMessage != messageIn))
 								messageDestroy(mainMessage);
e3aaff8e
 							mainMessage = NULL;
0e523db2
 							cptr = messageGetMimeSubtype(aMessage);
78e302e1
 							cli_dbgmsg("Mime subtype \"%s\"\n", cptr);
182bbcc8
 							if((tableFind(subtypeTable, cptr) == PLAIN) &&
c8a7cef0
 								  (messageGetEncoding(aMessage) == NOENCODING)) {
aeca3893
 								char *filename;
d110fe1c
 								/*
 								 * Strictly speaking
ab3107bc
 								 * a text/plain part is
d110fe1c
 								 * not an attachment. We
 								 * pretend it is so that
 								 * we can decode and
 								 * scan it
 								 */
aeca3893
 								filename = (char *)messageFindArgument(aMessage, "filename");
 								if(filename == NULL)
 									filename = (char *)messageFindArgument(aMessage, "name");
 
 								if(filename == NULL) {
 									cli_dbgmsg("Adding part to main message\n");
 									addToText = TRUE;
 								} else {
 									cli_dbgmsg("Treating %s as attachment\n",
 										filename);
 									free(filename);
 								}
d110fe1c
 							} else {
3805ebcb
 								if(options&CL_SCAN_MAILURL)
ab3107bc
 									if(tableFind(subtypeTable, cptr) == HTML)
 										checkURLs(aMessage, dir);
ad091acf
 								messageAddArgument(aMessage, "filename=mixedtextportion");
e3aaff8e
 							}
 						} else {
28010d29
 							cli_dbgmsg("Text type %s is not supported\n", dtype);
e3aaff8e
 							continue;
 						}
 						break;
 					case MESSAGE:
2f4737ed
 						/* Content-Type: message/rfc822 */
3b6739a6
 						cli_dbgmsg("Found message inside multipart (encoding type %d)\n",
 							messageGetEncoding(aMessage));
b9a141ea
 						switch(messageGetEncoding(aMessage)) {
 							case NOENCODING:
 							case EIGHTBIT:
 							case BINARY:
 								if(encodingLine(aMessage) == NULL) {
 									/*
 									 * This means that the message has no attachments
 									 * The test for messageGetEncoding is needed since
 									 * encodingLine won't have been set if the message
 									 * itself has been encoded
 									 */
 									cli_dbgmsg("No encoding line found in the multipart/message\n");
 									assert(aMessage == messages[i]);
 									messageDestroy(messages[i]);
 									messages[i] = NULL;
 									continue;
 								}
d879a7b0
 						}
b9a141ea
 #if	0
b2223aad
 						messageAddStrAtTop(aMessage,
b116962d
 							"Received: by clamd (message/rfc822)");
3b6739a6
 #endif
93d41ee4
 #ifdef	SAVE_TO_DISC
 						/*
 						 * Save this embedded message
 						 * to a temporary file
 						 */
 						saveTextPart(aMessage, dir);
 						assert(aMessage == messages[i]);
 						messageDestroy(messages[i]);
 						messages[i] = NULL;
 #else
 						/*
 						 * Scan in memory, faster but
 						 * is open to DoS attacks when
 						 * many nested levels are
 						 * involved.
 						 */
f73920a4
 						body = parseEmailHeaders(aMessage, rfc821Table, TRUE);
c693116d
 						/*
 						 * We've fininished with the
 						 * original copy of the message,
 						 * so throw that away and
 						 * deal with the encapsulated
 						 * message as a message.
 						 * This can save a lot of memory
 						 */
 						assert(aMessage == messages[i]);
 						messageDestroy(messages[i]);
 						messages[i] = NULL;
89670d69
 						if(body) {
b0b860f1
 							rc = parseEmailBody(body, NULL, dir, rfc821Table, subtypeTable, options);
89670d69
 							messageDestroy(body);
 						}
93d41ee4
 #endif
e3aaff8e
 						continue;
 					case MULTIPART:
 						/*
 						 * It's a multi part within a multi part
 						 * Run the message parser on this bit, it won't
 						 * be an attachment
 						 */
 						cli_dbgmsg("Found multipart inside multipart\n");
f12d2498
 						if(aMessage) {
 							/*
 							 * The headers were parsed when reading in the
 							 * whole multipart section
 							 */
b0b860f1
 							rc = parseEmailBody(aMessage, aText, dir, rfc821Table, subtypeTable, options);
f12d2498
 							cli_dbgmsg("Finished recursion\n");
 							assert(aMessage == messages[i]);
 							messageDestroy(messages[i]);
 							messages[i] = NULL;
89670d69
 						} else {
b0b860f1
 							rc = parseEmailBody(NULL, NULL, dir, rfc821Table, subtypeTable, options);
ad9c6836
 							if(mainMessage && (mainMessage != messageIn))
 								messageDestroy(mainMessage);
89670d69
 							mainMessage = NULL;
 						}
e3aaff8e
 						continue;
 					default:
8ef734d4
 						cli_warnmsg("Only text and application attachments are supported, type = %d\n",
e3aaff8e
 							messageGetMimeType(aMessage));
 						continue;
 					}
 
6e84cebb
 					if(addToText) {
 						cli_dbgmsg("Adding to non mime-part\n");
e3aaff8e
 						aText = textAdd(aText, messageGetBody(aMessage));
6e84cebb
 					} else {
b0b860f1
 						fb = messageToFileblob(aMessage, dir);
e3aaff8e
 
0e5a0129
 						if(fb)
 							fileblobDestroy(fb);
e3aaff8e
 					}
7c1eb3bf
 					assert(aMessage == messages[i]);
 					messageDestroy(messages[i]);
 					messages[i] = NULL;
e3aaff8e
 				}
 
b0b860f1
 				/* rc = parseEmailBody(NULL, NULL, dir, rfc821Table, subtypeTable, options); */
e3aaff8e
 				break;
 			case SIGNED:
 			case PARALLEL:
 				/*
 				 * If we're here it could be because we have a
 				 * multipart/mixed message, consisting of a
 				 * message followed by an attachment. That
 				 * message itself is a multipart/alternative
 				 * message and we need to dig out the plain
 				 * text part of that alternative
 				 */
d4d14218
 				htmltextPart = getTextPart(messages, multiparts);
 				if(htmltextPart == -1)
 					htmltextPart = 0;
e3aaff8e
 
b0b860f1
 				rc = parseEmailBody(messages[htmltextPart], aText, dir, rfc821Table, subtypeTable, options);
e3aaff8e
 				break;
9a729c80
 			case ENCRYPTED:
 				rc = 0;
c79a2273
 				protocol = (char *)messageFindArgument(mainMessage, "protocol");
9a729c80
 				if(protocol) {
 					if(strcasecmp(protocol, "application/pgp-encrypted") == 0) {
 						/* RFC2015 */
 						cli_warnmsg("PGP encoded attachment not scanned\n");
 						rc = 2;
 					} else
6fcf5624
 						cli_warnmsg("Unknown encryption protocol '%s' - if you believe this file contains a virus, submit it to www.clamav.net\n", protocol);
9a729c80
 					free(protocol);
 				} else
4ab382c3
 					cli_dbgmsg("Encryption method missing protocol name\n");
9a729c80
 
 				break;
e3aaff8e
 			default:
5d8100cb
 				assert(0);
e3aaff8e
 			}
 
ad9c6836
 			if(mainMessage && (mainMessage != messageIn))
 				messageDestroy(mainMessage);
 
6e84cebb
 			if(aText && (textIn == NULL)) {
 				if((fb = fileblobCreate()) != NULL) {
c8a7cef0
 					cli_dbgmsg("Save non mime and/or text/plain part\n");
6e84cebb
 					fileblobSetFilename(fb, dir, "textpart");
e097c0dd
 					/*fileblobAddData(fb, "Received: by clamd (textpart)\n", 30);*/
04c39f39
 					(void)textToFileblob(aText, fb);
6e84cebb
 
 					fileblobDestroy(fb);
 				}
049a18b9
 				textDestroy(aText);
6e84cebb
 			}
049a18b9
 
b116962d
 			for(i = 0; i < multiparts; i++)
 				if(messages[i])
 					messageDestroy(messages[i]);
 
b726511f
 			if(messages)
 				free(messages);
 
e3aaff8e
 			return rc;
 
 		case MESSAGE:
 			/*
 			 * Check for forbidden encodings
 			 */
 			switch(messageGetEncoding(mainMessage)) {
 				case NOENCODING:
 				case EIGHTBIT:
 				case BINARY:
 					break;
 				default:
049a18b9
 					cli_warnmsg("MIME type 'message' cannot be decoded\n");
e3aaff8e
 					break;
 			}
f10460ed
 			rc = 0;
049a18b9
 			if((strcasecmp(mimeSubtype, "rfc822") == 0) ||
 			   (strcasecmp(mimeSubtype, "delivery-status") == 0)) {
b2223aad
 				message *m = parseEmailHeaders(mainMessage, rfc821Table);
c693116d
 				if(m) {
 					cli_dbgmsg("Decode rfc822");
 
93d41ee4
 					if(mainMessage && (mainMessage != messageIn)) {
 						messageDestroy(mainMessage);
 						mainMessage = NULL;
59da5a4f
 					} else
 						messageReset(mainMessage);
c693116d
 					if(messageGetBody(m))
b0b860f1
 						rc = parseEmailBody(m, NULL, dir, rfc821Table, subtypeTable, options);
c693116d
 
 					messageDestroy(m);
 				}
e3aaff8e
 				break;
5a15955b
 			} else if(strcasecmp(mimeSubtype, "disposition-notification") == 0) {
12f3689d
 				/* RFC 2298 - handle like a normal email */
5a15955b
 				rc = 1;
12f3689d
 				break;
5a15955b
 			} else if(strcasecmp(mimeSubtype, "partial") == 0) {
f10460ed
 #ifdef	PARTIAL_DIR
 				/* RFC1341 message split over many emails */
 				if(rfc1341(mainMessage, dir) >= 0)
 					rc = 1;
 #else
22080fa5
 				cli_warnmsg("Partial message received from MUA/MTA - message cannot be scanned\n");
f10460ed
 				rc = 0;
 #endif
 			} else if(strcasecmp(mimeSubtype, "external-body") == 0)
22080fa5
 				/* TODO */
e3aaff8e
 				cli_warnmsg("Attempt to send Content-type message/external-body trapped");
5a642650
 			else
6fcf5624
 				cli_warnmsg("Unsupported message format `%s' - if you believe this file contains a virus, submit it to www.clamav.net\n", mimeSubtype);
e3aaff8e
 
f10460ed
 
ad9c6836
 			if(mainMessage && (mainMessage != messageIn))
 				messageDestroy(mainMessage);
b726511f
 			if(messages)
 				free(messages);
f10460ed
 			return rc;
e3aaff8e
 
 		case APPLICATION:
4ab382c3
 			/*cptr = messageGetMimeSubtype(mainMessage);
d4d14218
 
4ab382c3
 			if((strcasecmp(cptr, "octet-stream") == 0) ||
aa0210b6
 			   (strcasecmp(cptr, "x-msdownload") == 0)) {*/
 			{
b0b860f1
 				fb = messageToFileblob(mainMessage, dir);
e3aaff8e
 
0e5a0129
 				if(fb) {
 					cli_dbgmsg("Saving main message as attachment\n");
 					fileblobDestroy(fb);
fbb7262e
 					if(mainMessage != messageIn) {
 						messageDestroy(mainMessage);
 						mainMessage = NULL;
 					} else
 						messageReset(mainMessage);
e3aaff8e
 				}
aa0210b6
 			} /*else
 				cli_warnmsg("Discarded application not sent as attachment\n");*/
e3aaff8e
 			break;
 
 		case AUDIO:
 		case VIDEO:
 		case IMAGE:
 			break;
 
 		default:
 			cli_warnmsg("Message received with unknown mime encoding");
 			break;
 		}
 	}
 
f12d2498
 	if(aText && (textIn == NULL)) {
6fd711b2
 		/* Look for a bounce in the text (non mime encoded) portion */
 		const text *t;
b116962d
 
6fd711b2
 		for(t = aText; t; t = t->t_next) {
 			const line_t *l = t->t_line;
ebe57840
 			const text *lookahead, *topofbounce;
6fd711b2
 			const char *s;
ebe57840
 			bool inheader;
b116962d
 
6fd711b2
 			if(l == NULL)
 				continue;
 
 			s = lineGetData(l);
 
 			if(cli_filetype(s, strlen(s)) != CL_TYPE_MAIL)
 				continue;
 
 			/*
 			 * We've found what looks like the start of a bounce
 			 * message. Only bother saving if it really is a bounce
 			 * message, this helps to speed up scanning of ping-pong
 			 * messages that have lots of bounces within bounces in
 			 * them
 			 */
 			for(lookahead = t->t_next; lookahead; lookahead = lookahead->t_next) {
 				l = lookahead->t_line;
 
 				if(l == NULL)
 					break;
 				s = lineGetData(l);
 				if(strncasecmp(s, "Content-Type:", 13) == 0)
 					/*
 					 * Don't bother with plain/text or
 					 * plain/html
 					 */
 					if(strstr(s, "text/") == NULL)
6862efc7
 						/*
 						 * Don't bother to save the unuseful
 						 * part
 						 */
6fd711b2
 						break;
 			}
 
 			if(lookahead && (lookahead->t_line == NULL)) {
 				cli_dbgmsg("Non mime part bounce message is not mime encoded, so it will not be scanned\n");
 				t = lookahead;
 				/* look for next bounce message */
 				continue;
 			}
 
6862efc7
 			/*
 			 * Prescan the bounce message to see if there's likely
 			 * to be anything nasty.
 			 * This algorithm is hand crafted and may be breakable
 			 * so all submissions are welcome. It's best NOT to
 			 * remove this however you may be tempted, because it
 			 * significantly speeds up the scanning of multiple
 			 * bounces (i.e. bounces within many bounces)
 			 */
 			for(; lookahead; lookahead = lookahead->t_next) {
 				l = lookahead->t_line;
 
 				if(l) {
 					s = lineGetData(l);
 					if((strncasecmp(s, "Content-Type:", 13) == 0) &&
 					   (strstr(s, "multipart/") == NULL) &&
 					   (strstr(s, "message/rfc822") == NULL) &&
 					   (strstr(s, "text/plain") == NULL))
 						break;
 				}
 			}
 			if(lookahead == NULL) {
7c56033f
 				cli_dbgmsg("cli_mbox: I believe it's plain text which must be clean\n");
6862efc7
 				/* nothing here, move along please */
 				break;
 			}
ebe57840
 			if((fb = fileblobCreate()) == NULL)
 				break;
 			cli_dbgmsg("Save non mime part bounce message\n");
 			fileblobSetFilename(fb, dir, "bounce");
 			fileblobAddData(fb, (unsigned char *)"Received: by clamd (bounce)\n", 28);
 
 			inheader = TRUE;
 			topofbounce = NULL;
 			for(;;) {
 				l = t->t_line;
 
 				if(l == NULL) {
 					if(inheader) {
 						inheader = FALSE;
 						topofbounce = t;
 					}
 				} else {
 					s = lineGetData(l);
 					fileblobAddData(fb, (unsigned char *)s, strlen(s));
 				}
 				fileblobAddData(fb, (unsigned char *)"\n", 1);
 				lookahead = t->t_next;
 				if(lookahead == NULL)
 					break;
 				t = lookahead;
 				l = t->t_line;
 				if((!inheader) && l) {
 					s = lineGetData(l);
 					if(cli_filetype(s, strlen(s)) == CL_TYPE_MAIL) {
 						cli_dbgmsg("Found the start of another bounce candidate\n");
 						break;
 					}
 				}
6fd711b2
 			}
ebe57840
 
 			fileblobDestroy(fb);
 			if(topofbounce)
 				t = topofbounce;
 			/*
 			 * Don't do this - it slows bugs.txt
 			 */
 			/*if(mainMessage)
 				mainMessage->bounce = NULL;*/
6fd711b2
 		}
f12d2498
 		textDestroy(aText);
 		aText = NULL;
 	}
 
b0b860f1
 	/*
 	 * No attachments - scan the text portions, often files
 	 * are hidden in HTML code
 	 */
 	cli_dbgmsg("%d multiparts found\n", multiparts);
 	for(i = 0; i < multiparts; i++) {
 		fb = messageToFileblob(messages[i], dir);
e3aaff8e
 
b0b860f1
 		if(fb) {
c7b69776
 			cli_dbgmsg("Saving multipart %d\n", i);
d4d14218
 
b0b860f1
 			fileblobDestroy(fb);
 		}
 	}
 
 	if(mainMessage) {
e3aaff8e
 		/*
b0b860f1
 		 * Look for uu-encoded main file
e3aaff8e
 		 */
b0b860f1
 		const text *t_line;
 
182bbcc8
 		if((encodingLine(mainMessage) != NULL) &&
69543a9d
 			  ((t_line = bounceBegin(mainMessage)) != NULL)) {
b116962d
 			const text *t, *start;
d4d14218
 			/*
b0b860f1
 			 * Attempt to save the original (unbounced)
 			 * message - clamscan will find that in the
 			 * directory and call us again (with any luck)
e72de3f1
 			 * having found an e-mail message to handle.
b0b860f1
 			 *
 			 * This finds a lot of false positives, the
e72de3f1
 			 * search that a content type is in the
b0b860f1
 			 * bounce (i.e. it's after the bounce header)
e72de3f1
 			 * helps a bit.
 			 *
 			 * messageAddLine
b0b860f1
 			 * optimisation could help here, but needs
 			 * careful thought, do it with line numbers
 			 * would be best, since the current method in
 			 * messageAddLine of checking encoding first
 			 * must remain otherwise non bounce messages
 			 * won't be scanned
d4d14218
 			 */
b116962d
 			for(t = start = t_line; t; t = t->t_next) {
85bb253e
 				char cmd[RFC2821LENGTH + 1];
b0b860f1
 				const char *txt = lineGetData(t->t_line);
 
b116962d
 				if(txt == NULL)
 					continue;
 				if(cli_strtokbuf(txt, 0, ":", cmd) == NULL)
 					continue;
 
 				switch(tableFind(rfc821Table, cmd)) {
 					case CONTENT_TRANSFER_ENCODING:
 						if((strstr(txt, "7bit") == NULL) &&
 						   (strstr(txt, "8bit") == NULL))
 							break;
 						continue;
 					case CONTENT_DISPOSITION:
 						break;
 					case CONTENT_TYPE:
 						if(strstr(txt, "text/plain") != NULL)
 							t = NULL;
 						break;
 					default:
 						if(strcasecmp(cmd, "From") == 0)
 							start = t_line;
 						else if(strcasecmp(cmd, "Received") == 0)
 							start = t_line;
 						continue;
e72de3f1
 				}
b116962d
 				break;
b0b860f1
 			}
 			if(t && ((fb = fileblobCreate()) != NULL)) {
 				cli_dbgmsg("Found a bounce message\n");
 				fileblobSetFilename(fb, dir, "bounce");
6b3fb261
 				if(textToFileblob(start, fb) == NULL)
 					cli_dbgmsg("Nothing new to save in the bounce message");
 				else
 					rc = 1;
b0b860f1
 				fileblobDestroy(fb);
b143af46
 			} else
 				cli_dbgmsg("Not found a bounce message\n");
b0b860f1
 		} else {
 			bool saveIt;
d4d14218
 
b0b860f1
 			if(messageGetMimeType(mainMessage) == MESSAGE)
f01bbfe8
 				/*
b0b860f1
 				 * Quick peek, if the encapsulated
 				 * message has no
 				 * content encoding statement don't
 				 * bother saving to scan, it's safe
f01bbfe8
 				 */
b0b860f1
 				saveIt = (encodingLine(mainMessage) != NULL);
 			else if((t_line = encodingLine(mainMessage)) != NULL) {
a7527b1f
 				/*
b0b860f1
 				 * Some bounces include the message
 				 * body without the headers.
ebe57840
 				 * FIXME: Unfortunately this generates a
b0b860f1
 				 * lot of false positives that a bounce
 				 * has been found when it hasn't.
a7527b1f
 				 */
b0b860f1
 				if((fb = fileblobCreate()) != NULL) {
ae5c693a
 					cli_dbgmsg("Found a bounce message with no header at '%s'\n",
 						lineGetData(t_line->t_line));
0e5a0129
 					fileblobSetFilename(fb, dir, "bounce");
f24bf390
 					fileblobAddData(fb,
 						(const unsigned char *)"Received: by clamd (bounce)\n",
 						28);
cca4efe4
 
b0b860f1
 					fb = textToFileblob(t_line, fb);
5c1150ac
 
b0b860f1
 					fileblobDestroy(fb);
5c1150ac
 				}
b0b860f1
 				saveIt = FALSE;
59da5a4f
 			} else if(multiparts == 0)
b0b860f1
 				/*
 				 * Save the entire text portion,
 				 * since it it may be an HTML file with
 				 * a JavaScript virus
 				 */
 				saveIt = TRUE;
59da5a4f
 			else
 				saveIt = FALSE;
e3aaff8e
 
b0b860f1
 			if(saveIt) {
 				cli_dbgmsg("Saving text part to scan\n");
 				/*
 				 * TODO: May be better to save aText
 				 */
 				saveTextPart(mainMessage, dir);
59da5a4f
 				if(mainMessage != messageIn) {
 					messageDestroy(mainMessage);
 					mainMessage = NULL;
 				} else
 					messageReset(mainMessage);
 				rc = 1;
049a18b9
 			}
e3aaff8e
 		}
b0b860f1
 	} else
 		rc = (multiparts) ? 1 : 2;	/* anything saved? */
e3aaff8e
 
ad9c6836
 	if(mainMessage && (mainMessage != messageIn))
 		messageDestroy(mainMessage);
 
b726511f
 	if(messages)
 		free(messages);
 
e06d34dc
 	cli_dbgmsg("parseEmailBody() returning %d\n", rc);
e3aaff8e
 
e06d34dc
 	return rc;
e3aaff8e
 }
 
 /*
  * Is the current line the start of a new section?
  *
  * New sections start with --boundary
  */
 static int
 boundaryStart(const char *line, const char *boundary)
 {
d72749e0
 	char *ptr, *out;
df8806fd
 	int rc;
85bb253e
 	char buf[RFC2821LENGTH + 1];
2ad0c86e
 
0e4e16d4
 	if(line == NULL)
 		return 0;	/* empty line */
 
6e84cebb
 	/*cli_dbgmsg("boundaryStart: line = '%s' boundary = '%s'\n", line, boundary);*/
2ad0c86e
 
ebe57840
 	if((*line != '-') && (*line != '('))
 		return 0;
 
 	if(strchr(line, '-') == NULL)
 		return 0;
 
d72749e0
 	if(strlen(line) <= sizeof(buf)) {
 		out = NULL;
 		ptr = rfc822comments(line, buf);
 	} else
 		out = ptr = rfc822comments(line, NULL);
 
2ad0c86e
 	if(ptr == NULL)
bdb843f6
 		ptr = (char *)line;
2ad0c86e
 
 	if(*ptr++ != '-') {
d72749e0
 		if(out)
 			free(out);
0e4e16d4
 		return 0;
2ad0c86e
 	}
0e4e16d4
 
e3aaff8e
 	/*
0e4e16d4
 	 * Gibe.B3 is broken, it has:
e3aaff8e
 	 *	boundary="---- =_NextPart_000_01C31177.9DC7C000"
 	 * but it's boundaries look like
 	 *	------ =_NextPart_000_01C31177.9DC7C000
0e4e16d4
 	 * notice the one too few '-'.
 	 * Presumably this is a deliberate exploitation of a bug in some mail
 	 * clients.
 	 *
 	 * The trouble is that this creates a lot of false positives for
 	 * boundary conditions, if we're too lax about matches. We do our level
 	 * best to avoid these false positives. For example if we have
 	 * boundary="1" we want to ensure that we don't break out of every line
 	 * that has -1 in it instead of starting --1. This needs some more work.
7c56033f
 	 *
 	 * Look with and without RFC822 comments stripped, I've seen some
 	 * samples where () are taken as comments in boundaries and some where
 	 * they're not. Irrespective of whatever RFC2822 says we need to find
 	 * viruses in both types of mails
e3aaff8e
 	 */
7c56033f
 	if((strstr(ptr, boundary) != NULL) || (strstr(line, boundary) != NULL))
df8806fd
 		rc = 1;
 	else if(*ptr++ != '-')
 		rc = 0;
 	else
79179da5
 		rc = (strcasecmp(ptr, boundary) == 0);
df8806fd
 
d72749e0
 	if(out)
 		free(out);
df8806fd
 
 	if(rc == 1)
 		cli_dbgmsg("boundaryStart: found %s in %s\n", boundary, line);
 
 	return rc;
e3aaff8e
 }
 
 /*
  * Is the current line the end?
  *
  * The message ends with with --boundary--
  */
 static int
 endOfMessage(const char *line, const char *boundary)
 {
 	size_t len;
 
02927896
 	if(line == NULL)
 		return 0;
6e84cebb
 	/*cli_dbgmsg("endOfMessage: line = '%s' boundary = '%s'\n", line, boundary);*/
e3aaff8e
 	if(*line++ != '-')
 		return 0;
 	if(*line++ != '-')
 		return 0;
 	len = strlen(boundary);
049a18b9
 	if(strncasecmp(line, boundary, len) != 0)
 		return 0;
0e523db2
 	/*
 	 * Use < rather than == because some broken mails have white
 	 * space after the boundary
 	 */
c29f01c5
 	if(strlen(line) < (len + 2))
e3aaff8e
 		return 0;
 	line = &line[len];
 	if(*line++ != '-')
 		return 0;
 	return *line == '-';
 }
 
 /*
  * Initialise the various lookup tables
  */
 static int
 initialiseTables(table_t **rfc821Table, table_t **subtypeTable)
 {
 	const struct tableinit *tableinit;
 
 	/*
 	 * Initialise the various look up tables
 	 */
 	*rfc821Table = tableCreate();
 	assert(*rfc821Table != NULL);
 
 	for(tableinit = rfc821headers; tableinit->key; tableinit++)
51fc2aa8
 		if(tableInsert(*rfc821Table, tableinit->key, tableinit->value) < 0) {
 			tableDestroy(*rfc821Table);
767f16ab
 			*rfc821Table = NULL;
e3aaff8e
 			return -1;
51fc2aa8
 		}
e3aaff8e
 
 	*subtypeTable = tableCreate();
 	assert(*subtypeTable != NULL);
 
 	for(tableinit = mimeSubtypes; tableinit->key; tableinit++)
 		if(tableInsert(*subtypeTable, tableinit->key, tableinit->value) < 0) {
 			tableDestroy(*rfc821Table);
51fc2aa8
 			tableDestroy(*subtypeTable);
767f16ab
 			*rfc821Table = NULL;
 			*subtypeTable = NULL;
e3aaff8e
 			return -1;
 		}
 
 	return 0;
 }
 
 /*
d4d14218
  * If there's a HTML text version use that, otherwise
e3aaff8e
  * use the first text part, otherwise just use the
d4d14218
  * first one around. HTML text is most likely to include
  * a scripting worm
e3aaff8e
  *
  * If we can't find one, return -1
  */
 static int
 getTextPart(message *const messages[], size_t size)
 {
 	size_t i;
28010d29
 	int textpart = -1;
e3aaff8e
 
 	for(i = 0; i < size; i++) {
 		assert(messages[i] != NULL);
28010d29
 		if(messageGetMimeType(messages[i]) == TEXT) {
 			if(strcasecmp(messageGetMimeSubtype(messages[i]), "html") == 0)
 				return (int)i;
 			textpart = (int)i;
 		}
e3aaff8e
 	}
28010d29
 	return textpart;
e3aaff8e
 }
 
 /*
  * strip -
767f16ab
  *	Remove the trailing spaces from a buffer. Don't call this directly,
  * always call strstrip() which is a wrapper to this routine to be used with
  * NUL terminated strings. This code looks a bit strange because of it's
  * heritage from code that worked on strings that weren't necessarily NUL
  * terminated.
  * TODO: rewrite for clamAV
  *
e3aaff8e
  * Returns it's new length (a la strlen)
  *
  * len must be int not size_t because of the >= 0 test, it is sizeof(buf)
  *	not strlen(buf)
  */
 static size_t
 strip(char *buf, int len)
 {
 	register char *ptr;
 	register size_t i;
 
 	if((buf == NULL) || (len <= 0))
767f16ab
 		return 0;
e3aaff8e
 
 	i = strlen(buf);
 	if(len > (int)(i + 1))
767f16ab
 		return i;
e3aaff8e
 	ptr = &buf[--len];
 
 #if	defined(UNIX) || defined(C_LINUX) || defined(C_DARWIN)	/* watch - it may be in shared text area */
 	do
 		if(*ptr)
 			*ptr = '\0';
87c9313e
 	while((--len >= 0) && (!isgraph(*--ptr)) && (*ptr != '\n') && (*ptr != '\r'));
e3aaff8e
 #else	/* more characters can be displayed on DOS */
 	do
 #ifndef	REAL_MODE_DOS
 		if(*ptr)	/* C8.0 puts into a text area */
 #endif
 			*ptr = '\0';
 	while((--len >= 0) && ((*--ptr == '\0') || (isspace((int)*ptr))));
 #endif
 	return((size_t)(len + 1));
 }
 
 /*
  * strstrip:
  *	Strip a given string
  */
f0627588
 size_t
e3aaff8e
 strstrip(char *s)
 {
 	if(s == (char *)NULL)
 		return(0);
02927896
 
e3aaff8e
 	return(strip(s, strlen(s) + 1));
 }
 
 /*
c8a7cef0
  * Some broken email headers use ';' at the end of a line to continue
  * to the next line and don't add a leading white space on the next line
e3aaff8e
  */
 static bool
 continuationMarker(const char *line)
 {
c8a7cef0
 	const char *ptr;
 
 	if(line == NULL)
 		return FALSE;
 
 #ifdef	CL_DEBUG
 	cli_dbgmsg("continuationMarker(%s)\n", line);
 #endif
 
 	if(strlen(line) == 0)
 		return FALSE;
 
 	ptr = strchr(line, '\0');
 
 	assert(ptr != NULL);
 
 	while(ptr > line)
 		switch(*--ptr) {
 			case '\n':
 			case '\r':
 			case ' ':
 			case '\t':
 				continue;
 			case ';':
 				return TRUE;
 			default:
 				return FALSE;
 		}
 
e3aaff8e
 	return FALSE;
 }
 
 static int
 parseMimeHeader(message *m, const char *cmd, const table_t *rfc821Table, const char *arg)
 {
38d07186
 	char *copy, *p;
 	const char *ptr;
8b3563f2
 	int commandNumber;
4f1d0bfc
 
e3aaff8e
 	cli_dbgmsg("parseMimeHeader: cmd='%s', arg='%s'\n", cmd, arg);
8b3563f2
 
d72749e0
 	copy = rfc822comments(cmd, NULL);
38d07186
 	if(copy) {
 		commandNumber = tableFind(rfc821Table, copy);
 		free(copy);
f017fbdd
 	} else
 		commandNumber = tableFind(rfc821Table, cmd);
8b3563f2
 
d72749e0
 	copy = rfc822comments(arg, NULL);
e3aaff8e
 
38d07186
 	if(copy)
 		ptr = copy;
 	else
 		ptr = arg;
e75e1ad1
 
8b3563f2
 	switch(commandNumber) {
e3aaff8e
 		case CONTENT_TYPE:
 			/*
 			 * Fix for non RFC1521 compliant mailers
 			 * that send content-type: Text instead
 			 * of content-type: Text/Plain, or
 			 * just simply "Content-Type:"
 			 */
5e394e73
 			if(arg == NULL)
69543a9d
 				/*
 				 * According to section 4 of RFC1521:
 				 * "Note also that a subtype specification is
 				 * MANDATORY. There are no default subtypes"
 				 *
1eec55a6
 				 * We have to break this and make an assumption
69543a9d
 				 * for the subtype because virus writers and
 				 * email client writers don't get it right
 				 */
 				 cli_warnmsg("Empty content-type received, no subtype specified, assuming text/plain; charset=us-ascii\n");
38d07186
 			else if(strchr(ptr, '/') == NULL)
69543a9d
 				/*
 				 * Empty field, such as
 				 *	Content-Type:
 				 * which I believe is illegal according to
 				 * RFC1521
 				 */
38d07186
 				cli_dbgmsg("Invalid content-type '%s' received, no subtype specified, assuming text/plain; charset=us-ascii\n", ptr);
e3aaff8e
 			else {
8037334b
 				int i;
6d312569
 				char *mimeArgs;	/* RHS of the ; */
 
e3aaff8e
 				/*
 				 * Some clients are broken and
 				 * put white space after the ;
 				 */
2625d6a0
 				if(*arg == '/') {
 					cli_warnmsg("Content-type '/' received, assuming application/octet-stream\n");
 					messageSetMimeType(m, "application");
 					messageSetMimeSubtype(m, "octet-stream");
 				} else {
 					/*
0960ff5e
 					 * The content type could be in quotes:
 					 *	Content-Type: "multipart/mixed"
 					 * FIXME: this is a hack in that ignores
 					 *	the quotes, it doesn't handle
 					 *	them properly
2625d6a0
 					 */
38d07186
 					while(isspace(*ptr))
 						ptr++;
 					if(ptr[0] == '\"')
 						ptr++;
0960ff5e
 
38d07186
 					if(ptr[0] != '/') {
f017fbdd
 						char *s;
 						char *mimeType;	/* LHS of the ; */
38d07186
 #ifdef CL_THREAD_SAFE
 						char *strptr;
 #endif
f017fbdd
 
38d07186
 						s = mimeType = cli_strtok(ptr, 0, ";");
0960ff5e
 						/*
6d312569
 						 * Handle
 						 * Content-Type: foo/bar multipart/mixed
 						 * and
 						 * Content-Type: multipart/mixed foo/bar
0960ff5e
 						 */
38e2ab86
 						if(s && *s) for(;;) {
548a5f96
 #ifdef	CL_THREAD_SAFE
6d312569
 							int set = messageSetMimeType(m, strtok_r(s, "/", &strptr));
548a5f96
 #else
 							int set = messageSetMimeType(m, strtok(s, "/"));
 #endif
6d312569
 
 							/*
 							 * Stephen White <stephen@earth.li>
 							 * Some clients put space after
 							 * the mime type but before
 							 * the ;
 							 */
548a5f96
 #ifdef	CL_THREAD_SAFE
6d312569
 							s = strtok_r(NULL, ";", &strptr);
548a5f96
 #else
 							s = strtok(NULL, ";");
 #endif
6d312569
 							if(s == NULL)
 								break;
 							if(set) {
f017fbdd
 								size_t len = strstrip(s) - 1;
6d312569
 								if(s[len] == '\"') {
 									s[len] = '\0';
 									len = strstrip(s);
 								}
 								if(len) {
f017fbdd
 									if(strchr(s, ' ')) {
 										char *t = cli_strtok(s, 0, " ");
6d312569
 
f017fbdd
 										messageSetMimeSubtype(m, t);
 										free(t);
 									} else
 										messageSetMimeSubtype(m, s);
6d312569
 								}
0960ff5e
 							}
6d312569
 
 							while(*s && !isspace(*s))
 								s++;
 							if(*s++ == '\0')
 								break;
 							if(*s == '\0')
 								break;
0960ff5e
 						}
38e2ab86
 						if(mimeType)
 							free(mimeType);
f017fbdd
 					}
2625d6a0
 				}
e3aaff8e
 
 				/*
20d3dde9
 				 * Add in all rest of the the arguments.
 				 * e.g. if the header is this:
 				 * Content-Type:', arg='multipart/mixed; boundary=foo
 				 * we find the boundary argument set it
e3aaff8e
 				 */
8037334b
 				i = 1;
38d07186
 				while((mimeArgs = cli_strtok(ptr, i++, ";")) != NULL) {
8037334b
 					cli_dbgmsg("mimeArgs = '%s'\n", mimeArgs);
 
6d312569
 					messageAddArguments(m, mimeArgs);
 					free(mimeArgs);
 				}
e3aaff8e
 			}
 			break;
 		case CONTENT_TRANSFER_ENCODING:
38d07186
 			messageSetEncoding(m, ptr);
e3aaff8e
 			break;
 		case CONTENT_DISPOSITION:
38d07186
 			p = cli_strtok(ptr, 0, ";");
 			if(p) {
 				if(*p) {
 					messageSetDispositionType(m, p);
 					free(p);
 					p = cli_strtok(ptr, 1, ";");
 					messageAddArgument(m, p);
 				}
 				free(p);
548a5f96
 			}
ab84808e
 			if((p = (char *)messageFindArgument(m, "filename")) == NULL)
 				/*
 				 * Handle this type of header, without
 				 * a filename (e.g. some Worm.Torvil.D)
 				 *	Content-ID: <nRfkHdrKsAxRU>
 				 * Content-Transfer-Encoding: base64
 				 * Content-Disposition: attachment
 				 */
 				messageAddArgument(m, "filename=unknown");
 			else
 				free(p);
e3aaff8e
 	}
38d07186
 	if(copy)
 		free(copy);
e3aaff8e
 
4f1d0bfc
 	return 0;
e3aaff8e
 }
 
e06d34dc
 /*
cca4efe4
  * Save the text portion of the message
  */
 static void
 saveTextPart(message *m, const char *dir)
 {
0e5a0129
 	fileblob *fb;
cca4efe4
 
 	messageAddArgument(m, "filename=textportion");
0e5a0129
 	if((fb = messageToFileblob(m, dir)) != NULL) {
cca4efe4
 		/*
 		 * Save main part to scan that
 		 */
c77c8809
 		cli_dbgmsg("Saving main message\n");
cca4efe4
 
0e5a0129
 		fileblobDestroy(fb);
cca4efe4
 	}
 }
 
a9714c49
 /*
f017fbdd
  * Handle RFC822 comments in headers.
d72749e0
  * If out == NULL, return a buffer without the comments, the caller must free
  *	the returned buffer
  * Return NULL on error or if the input * has no comments.
f017fbdd
  * See secion 3.4.3 of RFC822
a9714c49
  * TODO: handle comments that go on to more than one line
  */
 static char *
d72749e0
 rfc822comments(const char *in, char *out)
a9714c49
 {
 	const char *iptr;
d72749e0
 	char *optr;
a9714c49
 	int backslash, inquote, commentlevel;
 
 	if(in == NULL)
f017fbdd
 		return NULL;
a9714c49
 
 	if(strchr(in, '(') == NULL)
f017fbdd
 		return NULL;
a9714c49
 
d72749e0
 	assert(out != in);
 
 	if(out == NULL) {
 		out = cli_malloc(strlen(in) + 1);
 		if(out == NULL)
 			return NULL;
 	}
a9714c49
 
 	backslash = commentlevel = inquote = 0;
 	optr = out;
 
 	cli_dbgmsg("rfc822comments: contains a comment\n");
 
 	for(iptr = in; *iptr; iptr++)
 		if(backslash) {
b814e02a
 			if(commentlevel == 0)
 				*optr++ = *iptr;
a9714c49
 			backslash = 0;
 		} else switch(*iptr) {
 			case '\\':
 				backslash = 1;
 				break;
 			case '\"':
7c56033f
 				*optr++ = '\"';
a9714c49
 				inquote = !inquote;
 				break;
 			case '(':
7c56033f
 				if(inquote)
 					*optr++ = '(';
 				else
 					commentlevel++;
a9714c49
 				break;
 			case ')':
7c56033f
 				if(inquote)
 					*optr++ = ')';
 				else if(commentlevel > 0)
a9714c49
 					commentlevel--;
 				break;
 			default:
 				if(commentlevel == 0)
 					*optr++ = *iptr;
 		}
 
 	if(backslash)	/* last character was a single backslash */
 		*optr++ = '\\';
 	*optr = '\0';
 
d72749e0
 	/*strstrip(out);*/
a9714c49
 
 	cli_dbgmsg("rfc822comments '%s'=>'%s'\n", in, out);
 
 	return out;
 }
50df4118
 
 /*
  * Handle RFC2047 encoding. Returns a malloc'd buffer that the caller must
  * free, or NULL on error
  */
 static char *
 rfc2047(const char *in)
 {
 	char *out, *pout;
 	size_t len;
 
4de5fffd
 	if((strstr(in, "=?") == NULL) || (strstr(in, "?=") == NULL))
50df4118
 		return strdup(in);
 
 	cli_dbgmsg("rfc2047 '%s'\n", in);
 	out = cli_malloc(strlen(in) + 1);
 
 	if(out == NULL)
 		return NULL;
 
 	pout = out;
 
 	/* For each RFC2047 string */
 	while(*in) {
cf569541
 		char encoding, *ptr, *enctext;
50df4118
 		message *m;
 		blob *b;
 
 		/* Find next RFC2047 string */
 		while(*in) {
 			if((*in == '=') && (in[1] == '?')) {
 				in += 2;
 				break;
 			}
 			*pout++ = *in++;
 		}
 		/* Skip over charset, find encoding */
 		while((*in != '?') && *in)
 			in++;
 		if(*in == '\0')
 			break;
 		encoding = *++in;
 		encoding = tolower(encoding);
 
 		if((encoding != 'q') && (encoding != 'b')) {
6fcf5624
 			cli_warnmsg("Unsupported RFC2047 encoding type '%c' - if you believe this file contains a virus, submit it to www.clamav.net\n", encoding);
1b00d9a4
 			free(out);
 			out = NULL;
50df4118
 			break;
 		}
 		/* Skip to encoded text */
 		if(*++in != '?')
 			break;
 		if(*++in == '\0')
 			break;
 
cf569541
 		enctext = strdup(in);
 		if(enctext == NULL) {
 			free(out);
 			out = NULL;
 			break;
 		}
50df4118
 		in = strstr(in, "?=");
cf569541
 		if(in == NULL) {
 			free(enctext);
50df4118
 			break;
cf569541
 		}
50df4118
 		in += 2;
 		ptr = strstr(enctext, "?=");
 		assert(ptr != NULL);
 		*ptr = '\0';
 		/*cli_dbgmsg("Need to decode '%s' with method '%c'\n", enctext, encoding);*/
 
 		m = messageCreate();
c77c8809
 		if(m == NULL)
50df4118
 			break;
564b3e07
 		messageAddStr(m, enctext);
cf569541
 		free(enctext);
767f16ab
 		switch(encoding) {
50df4118
 			case 'q':
 				messageSetEncoding(m, "quoted-printable");
 				break;
 			case 'b':
 				messageSetEncoding(m, "base64");
 				break;
 		}
 		b = messageToBlob(m);
 		len = blobGetDataSize(b);
 		cli_dbgmsg("Decoded as '%*.*s'\n", len, len, blobGetData(b));
 		memcpy(pout, blobGetData(b), len);
 		blobDestroy(b);
 		messageDestroy(m);
 		if(pout[len - 1] == '\n')
 			pout += len - 1;
 		else
 			pout += len;
 
 	}
ec8e31fa
 	if(out == NULL)
 		return NULL;
 
 	*pout = '\0';
50df4118
 
ec8e31fa
 	cli_dbgmsg("rfc2047 returns '%s'\n", out);
50df4118
 	return out;
 }
 
f10460ed
 #ifdef	PARTIAL_DIR
 /*
  * Handle partial messages
  */
 static int
 rfc1341(message *m, const char *dir)
 {
 	fileblob *fb;
13462674
 	char *arg, *id, *number, *total, *oldfilename;
fb79b576
 	const char *tmpdir;
16ea58a2
 	char pdir[NAME_MAX + 1];
fb79b576
 
f003b79e
 	id = (char *)messageFindArgument(m, "id");
 	if(id == NULL)
 		return -1;
 
f83668bf
 #ifdef  C_CYGWIN
45aba293
 	if((tmpdir = getenv("TEMP")) == (char *)NULL)
 		if((tmpdir = getenv("TMP")) == (char *)NULL)
 			if((tmpdir = getenv("TMPDIR")) == (char *)NULL)
 				tmpdir = "C:\\";
fb79b576
 #else
45aba293
 	if((tmpdir = getenv("TMPDIR")) == (char *)NULL)
 		if((tmpdir = getenv("TMP")) == (char *)NULL)
 			if((tmpdir = getenv("TEMP")) == (char *)NULL)
fb79b576
 #ifdef	P_tmpdir
45aba293
 				tmpdir = P_tmpdir;
fb79b576
 #else
45aba293
 				tmpdir = "/tmp";
fb79b576
 #endif
 #endif
f10460ed
 
16ea58a2
 	snprintf(pdir, sizeof(pdir) - 1, "%s/clamav-partial", tmpdir);
fb79b576
 
 	if((mkdir(pdir, 0700) < 0) && (errno != EEXIST)) {
 		cli_errmsg("Can't create the directory '%s'\n", pdir);
f10460ed
 		return -1;
13462674
 	} else {
 		struct stat statb;
 
fb79b576
 		if(stat(pdir, &statb) < 0) {
 			cli_errmsg("Can't stat the directory '%s'\n", pdir);
13462674
 			return -1;
 		}
 		if(statb.st_mode & 077)
 			cli_warnmsg("Insecure partial directory %s (mode 0%o)\n",
fb79b576
 				pdir, statb.st_mode & 0777);
f10460ed
 	}
 
 	number = (char *)messageFindArgument(m, "number");
 	if(number == NULL) {
 		free(id);
 		return -1;
 	}
 
 	oldfilename = (char *)messageFindArgument(m, "filename");
 	if(oldfilename == NULL)
 		oldfilename = (char *)messageFindArgument(m, "name");
 
 	arg = cli_malloc(10 + strlen(id) + strlen(number));
a43dd3cd
 	if(arg) {
 		sprintf(arg, "filename=%s%s", id, number);
 		messageAddArgument(m, arg);
 		free(arg);
 	}
f10460ed
 
 	if(oldfilename) {
 		cli_warnmsg("Must reset to %s\n", oldfilename);
 		free(oldfilename);
 	}
 
fb79b576
 	if((fb = messageToFileblob(m, pdir)) == NULL) {
f10460ed
 		free(id);
 		free(number);
 		return -1;
 	}
 
 	fileblobDestroy(fb);
 
 	total = (char *)messageFindArgument(m, "total");
 	cli_dbgmsg("rfc1341: %s, %s of %s\n", id, number, (total) ? total : "?");
 	if(total) {
 		int n = atoi(number);
 		int t = atoi(total);
 		DIR *dd = NULL;
 
f003b79e
 		free(total);
f10460ed
 		/*
 		 * If it's the last one - reassemble it
3a0f75c6
 		 * FIXME: this assumes that we receive the parts in order
f10460ed
 		 */
fb79b576
 		if((n == t) && ((dd = opendir(pdir)) != NULL)) {
f10460ed
 			FILE *fout;
 			char outname[NAME_MAX + 1];
e6be10f7
 			time_t now;
f10460ed
 
 			snprintf(outname, sizeof(outname) - 1, "%s/%s", dir, id);
 
 			cli_dbgmsg("outname: %s\n", outname);
 
 			fout = fopen(outname, "wb");
 			if(fout == NULL) {
3a0f75c6
 				cli_errmsg("Can't open '%s' for writing", outname);
f10460ed
 				free(id);
 				free(number);
 				closedir(dd);
 				return -1;
 			}
 
e6be10f7
 			time(&now);
f10460ed
 			for(n = 1; n <= t; n++) {
 				char filename[NAME_MAX + 1];
13462674
 				const struct dirent *dent;
 #if defined(HAVE_READDIR_R_3) || defined(HAVE_READDIR_R_2)
242bfde8
 				union {
 					struct dirent d;
 					char b[offsetof(struct dirent, d_name) + NAME_MAX + 1];
 				} result;
13462674
 #endif
f10460ed
 
 				snprintf(filename, sizeof(filename), "%s%d", id, n);
fdc6adbe
 
242bfde8
 #ifdef HAVE_READDIR_R_3
 				while((readdir_r(dd, &result.d, &dent) == 0) && dent) {
f10460ed
 #elif defined(HAVE_READDIR_R_2)
242bfde8
 				while((dent = (struct dirent *)readdir_r(dd, &result.d))) {
fdc6adbe
 #else	/*!HAVE_READDIR_R*/
f10460ed
 				while((dent = readdir(dd))) {
 #endif
 					FILE *fin;
e6be10f7
 					char buffer[BUFSIZ], fullname[NAME_MAX + 1];
f10460ed
 					int nblanks;
fb79b576
 					extern short cli_leavetemps_flag;
e6be10f7
 					struct stat statb;
f10460ed
 
f83668bf
 #ifdef  C_CYGWIN
f10460ed
 					if(dent->d_ino == 0)
 						continue;
f83668bf
 #endif
f10460ed
 
a43dd3cd
 					snprintf(fullname, sizeof(fullname) - 1,
 						"%s/%s", pdir, dent->d_name);
 
e6be10f7
 					if(strncmp(filename, dent->d_name, strlen(filename)) != 0) {
 						if(!cli_leavetemps_flag)
 							continue;
 						if(stat(fullname, &statb) < 0)
 							continue;
 						if(now - statb.st_mtime > (time_t)(7 * 24 * 3600))
 							if(unlink(fullname) >= 0)
 								cli_warnmsg("removed old RFC1341 file %s\n", fullname);
f10460ed
 						continue;
e6be10f7
 					}
f10460ed
 
e6be10f7
 					fin = fopen(fullname, "rb");
f10460ed
 					if(fin == NULL) {
e6be10f7
 						cli_errmsg("Can't open '%s' for reading", fullname);
f10460ed
 						fclose(fout);
 						unlink(outname);
 						free(id);
 						free(number);
 						closedir(dd);
 						return -1;
 					}
 					nblanks = 0;
9f2024cc
 					while(fgets(buffer, sizeof(buffer) - 1, fin) != NULL)
f10460ed
 						/*
 						 * Ensure that trailing newlines
 						 * aren't copied
 						 */
f003b79e
 						if(buffer[0] == '\n')
f10460ed
 							nblanks++;
f003b79e
 						else {
f10460ed
 							if(nblanks)
 								do
 									putc('\n', fout);
 								while(--nblanks > 0);
 							fputs(buffer, fout);
 						}
 					fclose(fin);
fb79b576
 
 					/* don't unlink if leave temps */
 					if(!cli_leavetemps_flag)
e6be10f7
 						unlink(fullname);
f10460ed
 					break;
 				}
 				rewinddir(dd);
 			}
 			closedir(dd);
 			fclose(fout);
 		}
 	}
f003b79e
 	free(number);
f10460ed
 	free(id);
 
 	return 0;
 }
 #endif
 
ad091acf
 #if	defined(FOLLOWURLS) && (FOLLOWURLS > 0)
71ba1dcd
 static void
 checkURLs(message *m, const char *dir)
 {
 	blob *b = messageToBlob(m);
 	size_t len;
87c9313e
 	table_t *t;
15021325
 	int i, n;
f121cb96
 #if	defined(WITH_CURL) && defined(CL_THREAD_SAFE)
ad091acf
 	pthread_t tid[FOLLOWURLS];
 	struct arg args[FOLLOWURLS];
f121cb96
 #endif
15021325
 	tag_arguments_t hrefs;
71ba1dcd
 
 	if(b == NULL)
 		return;
 
 	len = blobGetDataSize(b);
 
22080fa5
 	if(len == 0) {
 		blobDestroy(b);
55a3f03b
 		return;
22080fa5
 	}
55a3f03b
 
87c9313e
 	/* TODO: make this size customisable */
 	if(len > 100*1024) {
 		cli_warnmsg("Viruses pointed to by URL not scanned in large message\n");
 		blobDestroy(b);
22080fa5
 		return;
87c9313e
 	}
 
22080fa5
 	blobClose(b);
87c9313e
 	t = tableCreate();
3499d81e
 	if(t == NULL) {
 		blobDestroy(b);
 		return;
 	}
55a3f03b
 
d77c655d
 	hrefs.count = 0;
 	hrefs.tag = hrefs.value = NULL;
15021325
 
 	cli_dbgmsg("checkURLs: calling html_normalise_mem\n");
3499d81e
 	if(!html_normalise_mem(blobGetData(b), len, NULL, &hrefs)) {
ef822cfc
 		blobDestroy(b);
 		tableDestroy(t);
 		return;
3499d81e
 	}
 	cli_dbgmsg("checkURLs: html_normalise_mem returned\n");
 
b143af46
 	/* TODO: Do we need to call remove_html_comments? */
87c9313e
 
15021325
 	n = 0;
 
 	for(i = 0; i < hrefs.count; i++) {
242bfde8
 		const char *url = (const char *)hrefs.value[i];
15021325
 
9b1a0518
 		/*
 		 * TODO: If it's an image source, it'd be nice to note beacons
 		 *	where width="0" height="0", which needs support from
 		 *	the HTML normalise code
 		 */
15021325
 		if(strncasecmp("http://", url, 7) == 0) {
 			char *ptr;
f121cb96
 #ifdef	WITH_CURL
 #ifndef	CL_THREAD_SAFE
 			struct arg arg;
 #endif
 
 #else	/*!WITH_CURL*/
6eedb434
 #ifdef	CL_THREAD_SAFE
 			static pthread_mutex_t system_mutex = PTHREAD_MUTEX_INITIALIZER;
 #endif
87c9313e
 			struct stat statb;
 			char cmd[512];
f121cb96
 #endif	/*WITH_CURL*/
2c7d1edd
 			char name[NAME_MAX + 1];
15021325
 
 			if(tableFind(t, url) == 1) {
 				cli_dbgmsg("URL %s already downloaded\n", url);
4f1d0bfc
 				continue;
 			}
9b1a0518
 			/*
 			 * What about foreign character spoofing?
 			 * It would be useful be able to check if url
 			 *	is the same as the text displayed, e.g.
 			 *	<a href="http://dodgy.biz">www.paypal.com</a>
 			 *	but that needs support from HTML normalise
 			 */
 			if(strchr(url, '%') && strchr(url, '@'))
c8985288
 				cli_warnmsg("Possible URL spoofing attempt noticed, but not yet handled (%s)\n", url);
9b1a0518
 
9f2024cc
 			if(n == FOLLOWURLS) {
 				cli_warnmsg("URL %s will not be scanned\n", url);
 				break;
 			}
 
15021325
 			(void)tableInsert(t, url, 1);
 			cli_dbgmsg("Downloading URL %s to be scanned\n", url);
6771c811
 			strncpy(name, url, sizeof(name) - 1);
e5f64b54
 			name[sizeof(name) - 1] = '\0';
15021325
 			for(ptr = name; *ptr; ptr++)
 				if(*ptr == '/')
 					*ptr = '_';
71ba1dcd
 
65684cec
 #ifdef	WITH_CURL
f121cb96
 #ifdef	CL_THREAD_SAFE
2c7d1edd
 			args[n].dir = dir;
 			args[n].url = url;
f121cb96
 			args[n].filename = strdup(name);
 			pthread_create(&tid[n], NULL, getURL, &args[n]);
 #else
15021325
 			arg.url = url;
f121cb96
 			arg.dir = dir;
 			arg.filename = name;
 			getURL(&arg);
 #endif
 
9b4bb8b7
 #else
 			/*
 			 * TODO: maximum size and timeouts
 			 */
6771c811
 			len = sizeof(cmd) - 26 - strlen(dir) - strlen(name);
 #ifdef	CL_DEBUG
4c586bc8
 			snprintf(cmd, sizeof(cmd) - 1, "GET -t10 \"%.*s\" >%s/%s", len, url, dir, name);
6771c811
 #else
4c586bc8
 			snprintf(cmd, sizeof(cmd) - 1, "GET -t10 \"%.*s\" >%s/%s 2>/dev/null", len, url, dir, name);
6771c811
 #endif
 			cmd[sizeof(cmd) - 1] = '\0';
 
71ba1dcd
 			cli_dbgmsg("%s\n", cmd);
6eedb434
 #ifdef	CL_THREAD_SAFE
 			pthread_mutex_lock(&system_mutex);
 #endif
71ba1dcd
 			system(cmd);
6eedb434
 #ifdef	CL_THREAD_SAFE
 			pthread_mutex_unlock(&system_mutex);
 #endif
 			snprintf(cmd, sizeof(cmd), "%s/%s", dir, name);
 			if(stat(cmd, &statb) >= 0)
 				if(statb.st_size == 0) {
15021325
 					cli_warnmsg("URL %s failed to download\n", url);
6eedb434
 					/*
 					 * Don't bother scanning an empty file
 					 */
 					(void)unlink(cmd);
 				}
9b4bb8b7
 #endif
f121cb96
 			++n;
71ba1dcd
 		}
 	}
 	blobDestroy(b);
4f1d0bfc
 	tableDestroy(t);
f121cb96
 
 #if	defined(WITH_CURL) && defined(CL_THREAD_SAFE)
ad091acf
 	assert(n <= FOLLOWURLS);
f121cb96
 	cli_dbgmsg("checkURLs: waiting for %d thread(s) to finish\n", n);
 	while(--n >= 0) {
 		pthread_join(tid[n], NULL);
 		free(args[n].filename);
 	}
 #endif
2c7d1edd
 	html_tag_arg_free(&hrefs);
71ba1dcd
 }
 
2c9c9f3b
 /*
  * Includes some Win32 patches by Gianluigi Tiesi <sherpya@netfarm.it>
ec0cef20
  *
  * FIXME: Often WMF exploits work by sending people an email directing them
  *	to a page which displays a picture containing the exploit. This is not
  *	currently found, since only the HTML on the referred page is downloaded.
  *	It would be useful to scan the HTML for references to pictures and
  *	download them for scanning. But that will hit performance so there is
  *	an issue here.
2c9c9f3b
  */
65684cec
 #ifdef	WITH_CURL
f121cb96
 static void *
 #ifdef	CL_THREAD_SAFE
 getURL(void *a)
 #else
 getURL(struct arg *arg)
 #endif
9b4bb8b7
 {
87c9313e
 	CURL *curl;
9b4bb8b7
 	FILE *fp;
87c9313e
 	struct curl_slist *headers;
 	static int initialised = 0;
f121cb96
 #ifdef	CL_THREAD_SAFE
 	static pthread_mutex_t init_mutex = PTHREAD_MUTEX_INITIALIZER;
 	struct arg *arg = (struct arg *)a;
 #endif
 	const char *url = arg->url;
 	const char *dir = arg->dir;
 	const char *filename = arg->filename;
38d07186
 	char fout[NAME_MAX + 1];
45dc1456
 #ifdef	CURLOPT_ERRORBUFFER
ef91e68b
 	char errorbuffer[CURL_ERROR_SIZE];
f7776df3
 #elif	(LIBCURL_VERSION_NUM >= 0x070C00)
2c9c9f3b
 	CURLcode res = CURLE_OK;
45dc1456
 #endif
9b4bb8b7
 
f121cb96
 #ifdef	CL_THREAD_SAFE
 	pthread_mutex_lock(&init_mutex);
 #endif
87c9313e
 	if(!initialised) {
2c9c9f3b
 		if(curl_global_init(CURL_GLOBAL_ALL) != 0) {
f121cb96
 #ifdef	CL_THREAD_SAFE
 			pthread_mutex_unlock(&init_mutex);
 #endif
b025d30e
 			cli_errmsg("curl_global_init failed");
f121cb96
 			return NULL;
 		}
87c9313e
 		initialised = 1;
9b4bb8b7
 	}
f121cb96
 #ifdef	CL_THREAD_SAFE
 	pthread_mutex_unlock(&init_mutex);
 #endif
 
87c9313e
 	/* easy isn't the word I'd use... */
 	curl = curl_easy_init();
b025d30e
 	if(curl == NULL) {
 		cli_errmsg("curl_easy_init failed");
f121cb96
 		return NULL;
b025d30e
 	}
65684cec
 
87c9313e
 	(void)curl_easy_setopt(curl, CURLOPT_USERAGENT, "www.clamav.net");
 
b025d30e
 	if(curl_easy_setopt(curl, CURLOPT_URL, url) != 0) {
 		cli_errmsg("%s: curl_easy_setopt failed", url);
 		curl_easy_cleanup(curl);
f121cb96
 		return NULL;
b025d30e
 	}
87c9313e
 
2c7d1edd
 	snprintf(fout, NAME_MAX, "%s/%s", dir, filename);
9b4bb8b7
 
2c9c9f3b
 	fp = fopen(fout, "wb");
9b4bb8b7
 
 	if(fp == NULL) {
3a0f75c6
 		cli_errmsg("Can't open '%s' for writing", fout);
65684cec
 		curl_easy_cleanup(curl);
f121cb96
 		return NULL;
9b4bb8b7
 	}
7e492164
 #ifdef	CURLOPT_WRITEDATA
f121cb96
 	if(curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp) != 0) {
 		fclose(fp);
 		curl_easy_cleanup(curl);
 		return NULL;
 	}
7e492164
 #else
 	if(curl_easy_setopt(curl, CURLOPT_FILE, fp) != 0) {
 		fclose(fp);
 		curl_easy_cleanup(curl);
 		return NULL;
 	}
 #endif
f121cb96
 
87c9313e
 	/*
55a3f03b
 	 * If an item is in squid's cache get it from there (TCP_HIT/200)
87c9313e
 	 * by default curl doesn't (TCP_CLIENT_REFRESH_MISS/200)
 	 */
 	headers = curl_slist_append(NULL, "Pragma:");
 	curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
9b4bb8b7
 
87c9313e
 	/* These should be customisable */
 	curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30);
 	curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10);
393a6d67
 #ifdef	CURLOPT_MAXFILESIZE
 	curl_easy_setopt(curl, CURLOPT_MAXFILESIZE, 50*1024);
 #endif
9b4bb8b7
 
f121cb96
 #ifdef  CL_THREAD_SAFE
00d46ae6
 #ifdef	CURLOPT_DNS_USE_GLOBAL_CACHE
f121cb96
 	curl_easy_setopt(curl, CURLOPT_DNS_USE_GLOBAL_CACHE, 0);
 #endif
00d46ae6
 #endif
15f4aa67
 
 	/*
 	 * Prevent password: prompting with older versions
 	 * FIXME: a better username?
 	 */
cd483c9b
 	curl_easy_setopt(curl, CURLOPT_USERPWD, "username:password");
15f4aa67
 
f121cb96
 	/*
 	 * FIXME: valgrind reports "pthread_mutex_unlock: mutex is not locked"
 	 * from gethostbyaddr_r within this. It may be a bug in libcurl
 	 * rather than this code, but I need to check, see Curl_resolv()
 	 * If pushed really hard it will sometimes say
 	 * Conditional jump or move depends on uninitialised value(s) and
 	 * quit. But the program seems to work OK without valgrind...
ef91e68b
 	 * Perhaps Curl_resolv() isn't thread safe?
 	 *
 	 * I have seen segfaults in version 7.12.3. Version 7.14 seems OK.
f121cb96
 	 */
e72de3f1
 	/*
bdb843f6
 	 * On some C libraries (notably with FC3, glibc-2.3.3-74) you get a
b025d30e
 	 * memory leak here in getaddrinfo(), see
b116962d
 	 *	https://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=139559
e72de3f1
 	 */
45dc1456
 #ifdef	CURLOPT_ERRORBUFFER
f7776df3
 	curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorbuffer);
 
de79719e
 	if(curl_easy_perform(curl) != CURLE_OK)
45dc1456
 		cli_warnmsg("URL %s failed to download: %s\n", url, errorbuffer);
063e914e
 #elif	(LIBCURL_VERSION_NUM >= 0x070C00)
de79719e
 	if((res = curl_easy_perform(curl)) != CURLE_OK)
2c9c9f3b
 		cli_warnmsg("URL %s failed to download: %s\n", url,
 			curl_easy_strerror(res));
063e914e
 #else
f7776df3
 	if(curl_easy_perform(curl) != CURLE_OK)
063e914e
 		cli_warnmsg("URL %s failed to download\n", url);
45dc1456
 #endif
87c9313e
 
 	fclose(fp);
 	curl_easy_cleanup(curl);
5865b0ce
 	curl_slist_free_all(headers);
f121cb96
 
 	return NULL;
9b4bb8b7
 }
 #endif
 
 #else
 static void
 checkURLs(message *m, const char *dir)
 {
 }
 #endif
 
f2f25418
 #ifdef HAVE_BACKTRACE
4f1d0bfc
 static void
02927896
 sigsegv(int sig)
 {
 	signal(SIGSEGV, SIG_DFL);
f2f25418
 	print_trace(1);
02927896
 	exit(SIGSEGV);
 }
 
4f1d0bfc
 static void
02927896
 print_trace(int use_syslog)
 {
 	void *array[10];
 	size_t size;
 	char **strings;
 	size_t i;
 	pid_t pid = getpid();
 
 	size = backtrace(array, 10);
 	strings = backtrace_symbols(array, size);
 
 	if(use_syslog == 0)
 		cli_dbgmsg("Backtrace of pid %d:\n", pid);
f73920a4
 	else
02927896
 		syslog(LOG_ERR, "Backtrace of pid %d:", pid);
 
 	for(i = 0; i < size; i++)
 		if(use_syslog)
04c39f39
 			syslog(LOG_ERR, "bt[%u]: %s", i, strings[i]);
02927896
 		else
 			cli_dbgmsg("%s\n", strings[i]);
 
ef822cfc
 	/* TODO: dump the current email */
 
02927896
 	free(strings);
 }
 #endif
f24bf390
 
ddea752e
 static bool
 usefulHeader(int commandNumber, const char *cmd)
 {
 	switch(commandNumber) {
 		case CONTENT_TRANSFER_ENCODING:
 		case CONTENT_DISPOSITION:
 		case CONTENT_TYPE:
 			return TRUE;
 		default:
 			if(strcasecmp(cmd, "From") == 0)
 				return TRUE;
 			else if(strcasecmp(cmd, "Received") == 0)
 				return TRUE;
 			else if(strcasecmp(cmd, "De") == 0)
 				return TRUE;
 	}
 
 	return FALSE;
 }
 
ae5c693a
 /*
72cf1461
  * Like fgets but cope with end of line by "\n", "\r\n", "\n\r", "\r"
  */
 static char *
d8142abc
 getline_from_mbox(char *buffer, size_t len, FILE *fin)
72cf1461
 {
 	char *ret;
 
 	if(feof(fin))
 		return NULL;
 
 	if((len == 0) || (buffer == NULL)) {
d8142abc
 		cli_errmsg("Invalid call to getline_from_mbox(). Report to bugs@clamav.net\n");
72cf1461
 		return NULL;
 	}
 
 	ret = buffer;
 
 	do {
 		int c = getc(fin);
 
 		if(ferror(fin))
 			return NULL;
 
 		switch(c) {
 			case '\n':
 				*buffer++ = '\n';
 				c = getc(fin);
 				if((c != '\r') && !feof(fin))
 					ungetc(c, fin);
 				break;
 			default:
c40715eb
 				*buffer++ = (char)c;
72cf1461
 				continue;
 			case EOF:
 				break;
 			case '\r':
 				*buffer++ = '\n';
 				c = getc(fin);
 				if((c != '\n') && !feof(fin))
 					ungetc(c, fin);
 				break;
 		}
 		break;
85bb253e
 	} while(--len > 1);
72cf1461
 
 	if(len == 0) {
182bbcc8
 		/* the email probably breaks RFC821 */
d8142abc
 		cli_warnmsg("getline_from_mbox: buffer overflow stopped - line lost\n");
72cf1461
 		return NULL;
 	}
85bb253e
 	if(len == 1)
 		/* over flows will have appear on separate lines */
d8142abc
 		cli_dbgmsg("getline_from_mbox: buffer overflow stopped - line recovered\n");
72cf1461
 	*buffer = '\0';
 
 	return ret;
 }