clamav-milter/clamav-milter.c
b151ef55
 /*
  * clamav-milter.c
  *	.../clamav-milter/clamav-milter.c
  *
  *  Copyright (C) 2003 Nigel Horne <njh@bandsman.co.uk>
  *
  *  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
  *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  *
f02c3c82
  * Install into /usr/local/sbin/clamav-milter
b151ef55
  *
  * See http://www.nmt.edu/~wcolburn/sendmail-8.12.5/libmilter/docs/sample.html
  *
71f25024
  * For installation instructions see the file INSTALL that came with this file
cbd7686b
  *
b5d15e64
  * Change History:
  * $Log: clamav-milter.c,v $
fe645903
  * Revision 1.92  2004/06/03 13:14:08  nigelhorne
  * Up-issued
  *
39378e7f
  * Revision 1.91  2004/05/25 16:24:21  nigelhorne
  * X-Virus-Scanned wasn't being added in maxstreamlength was exceeded
  *
71f25024
  * Revision 1.90  2004/05/24 17:05:18  nigelhorne
  * Include the hostname of the scanner in the headers
  *
f7925922
  * Revision 1.89  2004/05/21 09:14:57  nigelhorne
  * Handle --from, print error message if write to quarantine fails
  *
b90c8762
  * Revision 1.88  2004/05/16 08:25:09  nigelhorne
  * Up issue
  *
d69535ae
  * Revision 1.87  2004/05/09 17:39:04  nigelhorne
  * Waiting threads weren't being woken up
  *
0cb97bcb
  * Revision 1.86  2004/05/06 11:25:20  nigelhorne
  * Some work on maxStreamLength
  *
c63633c4
  * Revision 1.85  2004/04/29 07:35:27  nigelhorne
  * Change from realloc to cli_realloc - keep assignment
  *
a121491a
  * Revision 1.84  2004/04/28 14:28:29  nigelhorne
  * Various updates
  *
679ff9e7
  * Revision 1.83  2004/04/25 12:56:35  nigelhorne
  * Added --pidfile
  *
c51c112c
  * Revision 1.82  2004/04/23 09:13:30  nigelhorne
  * Better quarantine email subject
  *
97727aa0
  * Revision 1.81  2004/04/22 16:47:04  nigelhorne
  * Various changes
  *
62f5a55b
  * Revision 1.80  2004/04/21 15:27:02  nigelhorne
  * Various changes
  *
40c9a608
  * Revision 1.79  2004/04/20 14:15:01  nigelhorne
  * Sorted out X- headers and handle hostaddr == NULL
  *
6ad582fe
  * Revision 1.78  2004/04/20 08:13:15  nigelhorne
  * Print better message if hostaddr is null
  *
063b6c33
  * Revision 1.77  2004/04/19 22:11:20  nigelhorne
  * Many changes
  *
f26b5918
  * Revision 1.76  2004/04/19 13:28:41  nigelhorne
  * Started coding e-mail template support
  *
1392cf22
  * Revision 1.75  2004/04/19 13:28:00  nigelhorne
  * Started coding e-mail template support
  *
dd68be92
  * Revision 1.74  2004/04/17 20:39:04  nigelhorne
  * Add the virus name into the 550 rejection if sent
  *
0a9dafb1
  * Revision 1.73  2004/04/15 09:53:25  nigelhorne
  * Handle systems without inet_ntop
  *
0a867b46
  * Revision 1.72  2004/04/09 08:36:53  nigelhorne
  * Handle clamd giving up on StreamMaxLength before clamav-milter
  *
5691e168
  * Revision 1.71  2004/04/08 13:14:07  nigelhorne
  * Code tidy up
  *
7cc3891c
  * Revision 1.70  2004/04/06 22:43:43  kojm
  * reverse strlcpy/strlcat patch
  *
fdc3273d
  * Revision 1.69  2004/04/06 12:14:52  kojm
  * use strlcpy/strlcat
  *
cc511c7a
  * Revision 1.68  2004/04/03 04:47:22  nigelhorne
  * Honour StreamMaxLength
  *
9873b3c1
  * Revision 1.67  2004/04/01 15:34:00  nigelhorne
  * ThreadTimeout has been renamed ReadTimeout
  *
c96f7461
  * Revision 1.66  2004/03/31 20:48:03  nigelhorne
  * Config file has changed
  *
6489ba59
  * Revision 1.65  2004/03/27 21:44:21  nigelhorne
  * Attempt to handle clamd quick timeout for slow remote sites
  *
ea815cbc
  * Revision 1.64  2004/03/26 11:10:27  nigelhorne
  * Added debug information
  *
5f911bde
  * Revision 1.63  2004/03/20 12:30:00  nigelhorne
  * strerror_r is confused on Linux
  *
3f29c0de
  * Revision 1.62  2004/03/17 19:46:49  nigelhorne
  * Upissue to 0.70@
  *
51255149
  * Revision 1.61  2004/03/15 19:54:12  kojm
  * 0.70-rc
  *
5c0d3a77
  * Revision 1.60  2004/03/10 11:31:03  nigelhorne
  * Use HAVE_STRERROR_R
  *
cbd7686b
  * Revision 1.59  2004/03/07 15:11:15  nigelhorne
  * Added more information to headers flag
  *
8f1f6fb8
  * Revision 1.58  2004/03/03 09:14:55  nigelhorne
  * Change way check for TCPwrappers on TCP/IP
  *
6e945c41
  * Revision 1.57  2004/02/27 15:27:11  nigelhorne
  * call checkClamd on start
  *
ce14cc31
  * Revision 1.56  2004/02/27 09:23:56  nigelhorne
  * Don't use TCP wrappers when UNIX domain sockets are used
  *
e27af651
  * Revision 1.55  2004/02/22 22:53:50  nigelhorne
  * Handle ERROR message from clamd
  *
f02c3c82
  * Revision 1.54  2004/02/22 17:27:40  nigelhorne
  * Updated installation instructions now that privileges are dropped
  *
79f846a3
  * Revision 1.53  2004/02/21 11:03:23  nigelhorne
  * Error if quarantine-dir is publically accessable
  *
062dddc9
  * Revision 1.52  2004/02/20 17:07:24  nigelhorne
  * Added checkClamd
  *
64d9c7a1
  * Revision 1.51  2004/02/20 09:50:42  nigelhorne
  * Removed warnings added by new configuration script
  *
35d98cf9
  * Revision 1.50  2004/02/19 10:00:26  nigelhorne
  * Rework TCPWrappers support
  *
3bc05064
  * Revision 1.49  2004/02/18 13:30:34  nigelhorne
  * Added dont-long-clean argument
  *
f8a7079c
  * Revision 1.48  2004/02/18 10:06:51  nigelhorne
  * Fix FreeBSD
  *
64d5612d
  * Revision 1.47  2004/02/16 11:55:24  nigelhorne
  * Added clamfi_free which helps with the tidying up
  *
7ac60058
  * Revision 1.46  2004/02/16 09:39:22  nigelhorne
  * Upissued to 0.67
  *
b7f54bf2
  * Revision 1.45  2004/02/14 17:20:38  nigelhorne
  * Add TCPwrappers support
  *
d9b674b2
  * Revision 1.44  2004/02/09 11:05:33  nigelhorne
  * Added Hflag
  *
02e79d0c
  * Revision 1.43  2004/02/07 12:16:20  nigelhorne
  * Added config.h
  *
8ad6dd05
  * Revision 1.42  2004/02/02 13:44:31  nigelhorne
  * Include the ID of the message when warnings are sent to the postmaster-only
  *
a7164828
  * Revision 1.41  2004/01/29 12:52:35  nigelhorne
  * Added --noreject flag
  *
ca59d8d0
  * Revision 1.40  2004/01/28 15:55:59  nigelhorne
  * Fixed compilation error with --enable-debug
  *
6a914c6e
  * Revision 1.39  2004/01/26 14:12:42  nigelhorne
  * Corrected endian problem (ntohs instead of htons)
  *
244be94f
  * Revision 1.38  2004/01/25 14:23:51  nigelhorne
  * Support multiple clamd servers
  *
bbc9d684
  * Revision 1.37  2004/01/24 18:09:39  nigelhorne
  * Allow clamd server name as well as IPaddress in -s option
  *
462b5251
  * Revision 1.36  2004/01/12 15:30:53  nigelhorne
  * FixStaleSocket no longer complains on ENOENT
  *
cdbe607d
  * Revision 1.35  2004/01/10 16:22:14  nigelhorne
  * Added OpenBSD instructions and --signature-file
  *
e2bb746e
  * Revision 1.34  2003/12/31 14:46:35  nigelhorne
  * Include the sendmail queue ID in the log
  *
3166c010
  * Revision 1.33  2003/12/27 17:28:56  nigelhorne
  * Moved --sign data to private area
  *
e6bffccb
  * Revision 1.32  2003/12/22 14:05:31  nigelhorne
  * Added --sign option
  *
5dc96b9f
  * Revision 1.31  2003/12/13 16:43:21  nigelhorne
  * Upissue
  *
85c1dbfd
  * Revision 1.30  2003/12/12 13:42:47  nigelhorne
  * alls to clamfi_cleanup were missing
  *
d2efb3fa
  * Revision 1.29  2003/12/10 12:00:39  nigelhorne
  * Timeout on waiting for data from clamd
  *
b696653a
  * Revision 1.28  2003/12/09 09:22:14  nigelhorne
  * Use the location of sendmail discovered by configure
  *
709d1342
  * Revision 1.27  2003/12/05 19:14:07  nigelhorne
  * Set umask; handle unescaped From in mailboxes
  *
65a8d561
  * Revision 1.26  2003/12/02 06:37:26  nigelhorne
  * Use setsid if setpgrp not present
  *
3454ad43
  * Revision 1.25  2003/11/30 06:12:06  nigelhorne
  * Added --quarantine-dir option
  *
4ba69cb6
  * Revision 1.24  2003/11/29 11:51:19  nigelhorne
  * Fix problem of possible confused pointers if large number of recipients given
  *
2a1ff3e4
  * Revision 1.23  2003/11/25 05:56:43  nigelhorne
  * Handle empty hostname or hostaddr
  *
434012b8
  * Revision 1.22  2003/11/24 04:48:44  nigelhorne
  * Support AllowSupplementaryGroups
  *
bb9979e6
  * Revision 1.21  2003/11/22 11:47:45  nigelhorne
79f846a3
  * Drop root priviliges and support quarantine
bb9979e6
  *
0b6bce84
  * Revision 1.20  2003/11/19 16:32:22  nigelhorne
  * Close cmdSocket earlier
  *
c2ac5345
  * Revision 1.19  2003/11/17 04:48:30  nigelhorne
  * Up issue to version 0.65
  *
a6f07599
  * Revision 1.18  2003/11/11 08:19:20  nigelhorne
  * Handle % characters in e-mail addresses
  *
3a805bfd
  * Revision 1.17  2003/11/05 15:41:11  nigelhorne
  * Tidyup pthread_cond_timewait call
  *
b0a42ec6
  * Revision 1.16  2003/10/31 13:33:40  nigelhorne
  * Added dont scan on error flag
  *
390a7661
  * Revision 1.15  2003/10/22 19:44:01  nigelhorne
  * more calls to pthread_cond_broadcast
  *
f0d6f5a1
  * Revision 1.14  2003/10/12 08:37:21  nigelhorne
  * Uses VERSION command to get version information
  *
dd0d5a8c
  * Revision 1.13  2003/10/11 15:42:15  nigelhorne
  * Don't call clamdscan
  *
3a0b4e5b
  * Revision 1.12  2003/10/05 17:30:04  nigelhorne
  * Only fix old socket when FixStaleSocket is set
  *
31268a5c
  * Revision 1.11  2003/10/05 13:57:47  nigelhorne
  * Fixed handling of MaxThreads
  *
b14e9e77
  * Revision 1.10  2003/10/03 11:54:53  nigelhorne
  * Added white list of recipients
  *
ecb8e6b4
  * Revision 1.9  2003/09/30 11:53:55  nigelhorne
  * clamfi_envfrom was returning EX_TEMPFAIL in some places rather than SMFIS_TEMPFAIL
  *
c15d1d2c
  * Revision 1.8  2003/09/29 06:20:17  nigelhorne
  * max_children now overrides MaxThreads
  *
80a72b0d
  * Revision 1.7  2003/09/29 06:07:49  nigelhorne
  * Ensure remoteIP is set before usage
  *
b5d15e64
  * Revision 1.6  2003/09/28 16:37:23  nigelhorne
  * Added -f flag use MaxThreads if --max-children not set
b151ef55
  */
fe645903
 static	char	const	rcsid[] = "$Id: clamav-milter.c,v 1.92 2004/06/03 13:14:08 nigelhorne Exp $";
b151ef55
 
fe645903
 #define	CM_VERSION	"0.72"
b151ef55
 
 /*#define	CONFDIR	"/usr/local/etc"*/
 
02e79d0c
 #if HAVE_CONFIG_H
 #include "clamav-config.h"
 #endif
 
b151ef55
 #include "defaults.h"
c96f7461
 #include "cfgparser.h"
b151ef55
 #include "../target.h"
244be94f
 #include "str.h"
64d9c7a1
 #include "../libclamav/others.h"
 #include "clamav.h"
b151ef55
 
 #ifndef	CL_DEBUG
 #define	NDEBUG
 #endif
 
 #include <stdio.h>
 #include <sysexits.h>
709d1342
 #include <sys/types.h>
 #include <sys/stat.h>
b151ef55
 #include <syslog.h>
 #include <unistd.h>
 #include <stdlib.h>
 #include <string.h>
 #include <sys/wait.h>
 #include <assert.h>
 #include <arpa/inet.h>
 #include <sys/socket.h>
 #include <sys/un.h>
 #include <stdarg.h>
 #include <errno.h>
 #include <libmilter/mfapi.h>
 #include <pthread.h>
 #include <sys/time.h>
 #include <netinet/in.h>
 #include <signal.h>
1f025849
 #include <regex.h>
 #include <fcntl.h>
bb9979e6
 #include <pwd.h>
434012b8
 #include <grp.h>
bbc9d684
 #include <netdb.h>
b151ef55
 
b7f54bf2
 #ifdef	WITH_TCPWRAP
 #include <tcpd.h>
35d98cf9
 
 int	allow_severity = LOG_DEBUG;
e27af651
 int	deny_severity = LOG_NOTICE;
35d98cf9
 
b7f54bf2
 #endif
 
244be94f
 #if defined(CL_DEBUG) && defined(C_LINUX)
 #include <sys/resource.h>
 #endif
 
b151ef55
 #define _GNU_SOURCE
c6259ac5
 #include "getopt.h"
b151ef55
 
b696653a
 #ifndef	SENDMAIL_BIN
 #define	SENDMAIL_BIN	"/usr/lib/sendmail"
 #endif
 
b7f54bf2
 #ifndef HAVE_IN_PORT_T
 typedef	unsigned short	in_port_t;
 #endif
 
b151ef55
 /*
  * TODO: optional: xmessage on console when virus stopped (SNMP would be real nice!)
434012b8
  *	Having said that, with LogSysLog you can (on Linux) configure the system
  *	to get messages on the system console, see syslog.conf(5), also you
  *	can use wall(1) in the VirusEvent entry in clamav.conf
b151ef55
  * TODO: build with libclamav.so rather than libclamav.a
  * TODO: bounce message should optionally be read from a file
9873b3c1
  * TODO: Support LogTime and Logfile from the conf file
02e79d0c
  * TODO: Warn if TCPAddr doesn't allow connection from us
  * TODO: Decide action (bounce, discard, reject etc.) based on the virus
  *	found. Those with faked addresses, such as SCO.A want discarding,
  *	others could be bounced properly.
1392cf22
  * TODO: Encrypt mails sent to clamd to stop sniffers
063b6c33
  * TODO: Test with IPv6
b151ef55
  */
 
d9b674b2
 struct header_node_t {
 	char *header;
 	struct header_node_t *next;
 };
 
 struct header_list_struct {
 	struct header_node_t *first;
 	struct header_node_t *last;
 };
 
 typedef struct header_list_struct *header_list_t;
 
b151ef55
 /*
  * Each thread has one of these
  */
 struct	privdata {
 	char	*from;	/* Who sent the message */
 	char	**to;	/* Who is the message going to */
 	int	numTo;	/* Number of people the message is going to */
 	int	cmdSocket;	/*
 				 * Socket to send/get commands e.g. PORT for
 				 * dataSocket
 				 */
 	int	dataSocket;	/* Socket to send data to clamd */
3454ad43
 	char	*filename;	/* Where to store the message in quarantine */
3166c010
 	u_char	*body;		/* body of the message if Sflag is set */
 	size_t	bodyLen;	/* number of bytes in body */
d9b674b2
 	header_list_t headers;	/* Message headers */
5691e168
 	long	numBytes;	/* Number of bytes sent so far */
063b6c33
 	char	*received;	/* keep track of received from */
a121491a
 	const	char	*rejectCode;	/* 550 or 554? */
d69535ae
 	char	*messageID;	/* sendmailID */
a121491a
 	int	discard;	/*
 				 * looks like the remote end is playing ping
 				 * pong with us
 				 */
39378e7f
 	int	serverNumber;	/* Index into serverIPs */
b151ef55
 };
 
244be94f
 static	int		pingServer(int serverNumber);
 static	int		findServer(void);
b151ef55
 static	sfsistat	clamfi_connect(SMFICTX *ctx, char *hostname, _SOCK_ADDR *hostaddr);
 static	sfsistat	clamfi_envfrom(SMFICTX *ctx, char **argv);
 static	sfsistat	clamfi_envrcpt(SMFICTX *ctx, char **argv);
 static	sfsistat	clamfi_header(SMFICTX *ctx, char *headerf, char *headerv);
 static	sfsistat	clamfi_eoh(SMFICTX *ctx);
 static	sfsistat	clamfi_body(SMFICTX *ctx, u_char *bodyp, size_t len);
 static	sfsistat	clamfi_eom(SMFICTX *ctx);
 static	sfsistat	clamfi_abort(SMFICTX *ctx);
 static	sfsistat	clamfi_close(SMFICTX *ctx);
 static	void		clamfi_cleanup(SMFICTX *ctx);
64d5612d
 static	void		clamfi_free(struct privdata *privdata);
0cb97bcb
 static	int		clamfi_send(struct privdata *privdata, size_t len, const char *format, ...);
b151ef55
 static	char		*strrcpy(char *dest, const char *source);
cdbe607d
 static	int		clamd_recv(int sock, char *buf, size_t len);
 static	off_t		updateSigFile(void);
d9b674b2
 static	header_list_t	header_list_new(void);
 static	void	header_list_free(header_list_t list);
 static	void	header_list_add(header_list_t list, const char *headerf, const char *headerv);
 static	void	header_list_print(header_list_t list, FILE *fp);
6489ba59
 static	int	connect2clamd(struct privdata *privdata);
062dddc9
 static	void	checkClamd(void);
1392cf22
 static	int	sendtemplate(const char *filename, FILE *sendmail, const char *clamdMessage);
b151ef55
 
f0d6f5a1
 static	char	clamav_version[128];
b5d15e64
 static	int	fflag = 0;	/* force a scan, whatever */
b151ef55
 static	int	oflag = 0;	/* scan messages from our machine? */
 static	int	lflag = 0;	/* scan messages from our site? */
 static	int	bflag = 0;	/*
 				 * send a failure (bounce) message to the
 				 * sender. This probably isn't a good idea
 				 * since most reply addresses will be fake
 				 */
1c3f1ce1
 static	int	pflag = 0;	/*
 				 * Send a warning to the postmaster only,
 				 * this means user's won't be told when someone
 				 * sent them a virus
 				 */
 static	int	qflag = 0;	/*
 				 * Send no warnings when a virus is found,
 				 * this means that the only log of viruses
 				 * found is the syslog, so it's best to
 				 * enable LogSyslog in clamav.conf
 				 */
e6bffccb
 static	int	Sflag = 0;	/*
 				 * Add a signature to each message that
 				 * has been scanned
 				 */
cdbe607d
 static	const	char	*sigFilename;	/*
 				 * File where the scanned message signature
 				 * can be found
 				 */
3454ad43
 static	char	*quarantine;	/*
bb9979e6
 				 * If a virus is found in an email redirect
 				 * it to this account
 				 */
3454ad43
 static	char	*quarantine_dir; /*
 				 * Path to store messages before scanning.
 				 * Infected ones will be left there.
 				 */
3613bd91
 static	int	nflag = 0;	/*
 				 * Don't add X-Virus-Scanned to header. Patch
 				 * from Dirk Meyer <dirk.meyer@dinoex.sub.org>
 				 */
a7164828
 static	int	rejectmail = 1;	/*
 				 * Send a 550 rejection when a virus is
 				 * found
 				 */
d9b674b2
 static	int	hflag = 0;	/*
 				 * Include original message headers in
 				 * report
 				 */
b0a42ec6
 static	int	cl_error = SMFIS_TEMPFAIL; /*
 				 * If an error occurs, return
 				 * this status. Allows messages
 				 * to be passed through
 				 * unscanned in the event of
 				 * an error. Patch from
 				 * Joe Talbott <josepht@cstone.net>
 				 */
cc511c7a
 static	int	readTimeout = CL_DEFAULT_SCANTIMEOUT; /*
d2efb3fa
 				 * number of seconds to wait for clamd to
9873b3c1
 				 * respond, see ReadTimeout in clamav.conf
d2efb3fa
 				 */
5691e168
 static	long	streamMaxLength = -1;	/* StreamMaxLength from clamav.conf */
3bc05064
 static	int	logClean = 1;	/*
 				 * Add clean items to the log file
 				 */
cdbe607d
 static	char	*signature = "-- \nScanned by ClamAv - http://www.clamav.net\n";
 static	time_t	signatureStamp;
1392cf22
 static	char	*templatefile;	/* e-mail to be sent when virus detected */
b151ef55
 
 #ifdef	CL_DEBUG
 static	int	debug_level = 0;
 #endif
 
 static	pthread_mutex_t	n_children_mutex = PTHREAD_MUTEX_INITIALIZER;
 static	pthread_cond_t	n_children_cond = PTHREAD_COND_INITIALIZER;
 static	unsigned	int	n_children = 0;
 static	unsigned	int	max_children = 0;
244be94f
 short	use_syslog = 0;
062dddc9
 static	const	char	*pidFile;
b151ef55
 static	int	logVerbose = 0;
 static	struct	cfgstruct	*copt;
ce14cc31
 static	const	char	*localSocket;	/* milter->clamd comms */
 static	in_port_t	tcpSocket;	/* milter->clamd comms */
 static	char	*port = NULL;	/* sendmail->milter comms */
244be94f
 static	const	char	*serverHostNames = "127.0.0.1";
 static	long	*serverIPs;	/* IPv4 only */
 static	int	numServers;	/* numer of elements in serverIPs */
c6259ac5
 static	const	char	*postmaster = "postmaster";
063b6c33
 static	const	char	*from = "MAILER-DAEMON";
b151ef55
 
434012b8
 /*
f7925922
  * NULL terminated whitelist of target ("to") addresses that we do NOT scan
434012b8
  * TODO: read in from a file
0cb97bcb
  * TODO: add white list of target e-mail addresses that we do NOT scan
  * TODO: items in the list should be regular expressions
434012b8
  */
b14e9e77
 static	const	char	*ignoredEmailAddresses[] = {
 	/*"Mailer-Daemon@bandsman.co.uk",
 	"postmaster@bandsman.co.uk",*/
 	NULL
 };
 
b151ef55
 static void
 help(void)
 {
 	printf("\n\tclamav-milter version %s\n", CM_VERSION);
1392cf22
 	puts("\tCopyright (C) 2004 Nigel Horne <njh@despammed.com>\n");
b151ef55
 
 	puts("\t--bounce\t\t-b\tSend a failure message to the sender.");
 	puts("\t--config-file=FILE\t-c FILE\tRead configuration from FILE.");
3bc05064
 	puts("\t--debug\t\t\t-D\tPrint debug messages.");
 	puts("\t--dont-log-clean\t-C\tDon't add an entry to syslog that a mail is clean.");
bb9979e6
 	puts("\t--dont-scan-on-error\t-d\tPass e-mails through unscanned if a system error occurs.");
063b6c33
 	puts("\t--from=EMAIL\t\t-a EMAIL\tError messages come from here.");
bb9979e6
 	puts("\t--force-scan\t\t-f\tForce scan all messages (overrides (-o and -l).");
b151ef55
 	puts("\t--help\t\t\t-h\tThis message.");
d9b674b2
 	puts("\t--headers\t\t-H\tInclude original message headers in the report.");
b151ef55
 	puts("\t--local\t\t\t-l\tScan messages sent from machines on our LAN.");
 	puts("\t--outgoing\t\t-o\tScan outgoing messages from this machine.");
a7164828
 	puts("\t--noreject\t\t-N\tDon't reject viruses, silently throw them away.");
40c9a608
 	puts("\t--noxheader\t\t-n\tSuppress X-Virus-Scanned/X-Virus-Status headers.");
679ff9e7
 	puts("\t--pidfile=FILE\t\t-i FILE\tLocation of pidfile.");
434012b8
 	puts("\t--postmaster\t\t-p EMAIL\tPostmaster address [default=postmaster].");
bb9979e6
 	puts("\t--postmaster-only\t-P\tSend warnings only to the postmaster.");
1c3f1ce1
 	puts("\t--quiet\t\t\t-q\tDon't send e-mail notifications of interceptions.");
434012b8
 	puts("\t--quarantine=USER\t-Q EMAIL\tQuanrantine e-mail account.");
3454ad43
 	puts("\t--quarantine-dir=DIR\t-U DIR\tDirectory to store infected emails.");
3bc05064
 	puts("\t--server=SERVER\t\t-s SERVER\tHostname/IP address of server(s) running clamd (when using TCPsocket).");
cdbe607d
 	puts("\t--sign\t\t\t-S\tAdd a hard-coded signature to each scanned message.");
063b6c33
 	puts("\t--signature-file=FILE\t-F FILE\tLocation of signature file.");
 	puts("\t--template-file=FILE\t-t FILE\tLocation of e-mail template file.");
b151ef55
 	puts("\t--version\t\t-V\tPrint the version number of this software.");
 #ifdef	CL_DEBUG
 	puts("\t--debug-level=n\t\t-x n\tSets the debug level to 'n'.");
 #endif
 }
 
 int
 main(int argc, char **argv)
 {
 	extern char *optarg;
 	const char *cfgfile = CL_DEFAULT_CFG;
 	struct cfgstruct *cpt;
3454ad43
 	struct passwd *user;
679ff9e7
 	const char *pidfile = NULL;
b151ef55
 	struct smfiDesc smfilter = {
 		"ClamAv", /* filter name */
 		SMFI_VERSION,	/* version code -- leave untouched */
 		SMFIF_ADDHDRS,	/* flags - we add headers */
 		clamfi_connect, /* connection callback */
 		NULL, /* HELO filter callback */
 		clamfi_envfrom, /* envelope sender filter callback */
 		clamfi_envrcpt, /* envelope recipient filter callback */
 		clamfi_header, /* header filter callback */
 		clamfi_eoh, /* end of header callback */
 		clamfi_body, /* body filter callback */
 		clamfi_eom, /* end of message callback */
 		clamfi_abort, /* message aborted callback */
 		clamfi_close, /* connection cleanup callback */
 	};
 
244be94f
 #if defined(CL_DEBUG) && defined(C_LINUX)
 	struct rlimit rlim;
 
 	rlim.rlim_cur = rlim.rlim_max = RLIM_INFINITY;
 	if(setrlimit(RLIMIT_CORE, &rlim) < 0)
 		perror("setrlimit");
 #endif
f0d6f5a1
 	/*
 	 * Temporarily enter guessed value into clamav_version, will
 	 * be overwritten later by the value returned by clamd
 	 */
dd0d5a8c
 	snprintf(clamav_version, sizeof(clamav_version),
 		"ClamAV version %s, clamav-milter version %s",
 		VERSION, CM_VERSION);
 
b151ef55
 	for(;;) {
 		int opt_index = 0;
 #ifdef	CL_DEBUG
f7925922
 		const char *args = "abc:CDfF:lm:nNop:PqQ:dhHs:St:U:Vx:";
b151ef55
 #else
f7925922
 		const char *args = "abc:CDfF:lm:nNop:PqQ:dhHs:St:U:V";
b151ef55
 #endif
bb9979e6
 
b151ef55
 		static struct option long_options[] = {
 			{
063b6c33
 				"from", 0, NULL, 'a'
 			},
 			{
b151ef55
 				"bounce", 0, NULL, 'b'
 			},
 			{
 				"config-file", 1, NULL, 'c'
 			},
 			{
3bc05064
 				"dont-log-clean", 0, NULL, 'C'
 			},
 			{
b0a42ec6
 				"dont-scan-on-error", 0, NULL, 'd'
 			},
 			{
244be94f
 				"debug", 0, NULL, 'D'
 			},
 			{
3454ad43
 				"force-scan", 0, NULL, 'f'
b5d15e64
 			},
 			{
cbd7686b
 				"headers", 0, NULL, 'H'
d9b674b2
 			},
 			{
b151ef55
 				"help", 0, NULL, 'h'
 			},
 			{
679ff9e7
 				"pidfile", 1, NULL, 'i'
 			},
 			{
b151ef55
 				"local", 0, NULL, 'l'
 			},
 			{
a7164828
 				"noreject", 0, NULL, 'N'
 			},
 			{
3613bd91
 				"noxheader", 0, NULL, 'n'
 			},
 			{
b151ef55
 				"outgoing", 0, NULL, 'o'
 			},
 			{
434012b8
 				"postmaster", 1, NULL, 'p'
c6259ac5
 			},
 			{
1c3f1ce1
 				"postmaster-only", 0, NULL, 'P',
 			},
 			{
 				"quiet", 0, NULL, 'q'
 			},
 			{
bb9979e6
 				"quarantine", 1, NULL, 'Q',
 			},
 			{
3454ad43
 				"quarantine-dir", 1, NULL, 'U',
 			},
 			{
b151ef55
 				"max-children", 1, NULL, 'm'
 			},
 			{
 				"server", 1, NULL, 's'
 			},
 			{
cdbe607d
 				"sign", 0, NULL, 'S'
 			},
 			{
 				"signature-file", 1, NULL, 'F'
e6bffccb
 			},
 			{
1392cf22
 				"template-file", 1, NULL, 't'
 			},
 			{
b151ef55
 				"version", 0, NULL, 'V'
 			},
 #ifdef	CL_DEBUG
 			{
 				"debug-level", 1, NULL, 'x'
 			},
 #endif
 			{
 				NULL, 0, NULL, '\0'
 			}
 		};
 
 		int ret = getopt_long(argc, argv, args, long_options, &opt_index);
 
 		if(ret == -1)
 			break;
 		else if(ret == 0)
 			ret = long_options[opt_index].val;
 
 		switch(ret) {
063b6c33
 			case 'a':	/* e-mail errors from here */
 				from = optarg;
 				break;
b151ef55
 			case 'b':	/* bounce worms/viruses */
 				bflag++;
 				break;
 			case 'c':	/* where is clamav.conf? */
 				cfgfile = optarg;
 				break;
3bc05064
 			case 'C':	/* dont log clean */
 				logClean = 0;
 				break;
b0a42ec6
 			case 'd':	/* don't scan on error */
 				cl_error = SMFIS_ACCEPT;
 				break;
244be94f
 			case 'D':	/* enable debug messages */
 				cl_debug();
 				break;
b5d15e64
 			case 'f':	/* force the scan */
 				fflag++;
 				break;
b151ef55
 			case 'h':
 				help();
 				return EX_OK;
d9b674b2
 			case 'H':
 				hflag++;
 				break;
679ff9e7
 			case 'i':	/* pidfile */
 				pidfile = optarg;
 				break;
b151ef55
 			case 'l':	/* scan mail from the lan */
 				lflag++;
 				break;
c6259ac5
 			case 'm':	/* maximum number of children */
 				max_children = atoi(optarg);
 				break;
3613bd91
 			case 'n':	/* don't add X-Virus-Scanned */
 				nflag++;
bb9979e6
 				smfilter.xxfi_flags &= ~SMFIF_ADDHDRS;
3613bd91
 				break;
a7164828
 			case 'N':	/* Do we reject mail or silently drop it */
 				rejectmail = 0;
 				break;
b151ef55
 			case 'o':	/* scan outgoing mail */
 				oflag++;
 				break;
c6259ac5
 			case 'p':	/* postmaster e-mail address */
 				postmaster = optarg;
b151ef55
 				break;
1c3f1ce1
 			case 'P':	/* postmaster only */
 				pflag++;
 				break;
 			case 'q':	/* send NO notification email */
 				qflag++;
 				break;
bb9979e6
 			case 'Q':	/* quarantine e-mail address */
 				quarantine = optarg;
 				smfilter.xxfi_flags |= SMFIF_CHGHDRS|SMFIF_ADDRCPT|SMFIF_DELRCPT;
 				break;
b151ef55
 			case 's':	/* server running clamd */
244be94f
 				serverHostNames = optarg;
b151ef55
 				break;
cdbe607d
 			case 'F':	/* signature file */
 				sigFilename = optarg;
 				signature = NULL;
 				/* fall through */
e6bffccb
 			case 'S':	/* sign */
 				smfilter.xxfi_flags |= SMFIF_CHGBODY;
 				Sflag++;
 				break;
1392cf22
 			case 't':	/* e-mail template file */
 				templatefile = optarg;
 				break;
3454ad43
 			case 'U':	/* quarantine path */
 				quarantine_dir = optarg;
 				break;
b151ef55
 			case 'V':
dd0d5a8c
 				puts(clamav_version);
b151ef55
 				return EX_OK;
 #ifdef	CL_DEBUG
 			case 'x':
 				debug_level = atoi(optarg);
 				break;
 #endif
 			default:
 #ifdef	CL_DEBUG
244be94f
 				fprintf(stderr, "Usage: %s [-b] [-c FILE] [-F FILE] [--max-children=num] [-l] [-o] [-p address] [-P] [-q] [-Q USER] [-s SERVER] [-S] [-x#] [-U PATH] socket-addr\n", argv[0]);
b151ef55
 #else
244be94f
 				fprintf(stderr, "Usage: %s [-b] [-c FILE] [-F FILE] [--max-children=num] [-l] [-o] [-p address] [-P] [-q] [-Q USER] [-s SERVER] [-S] [-U PATH] socket-addr\n", argv[0]);
b151ef55
 #endif
 				return EX_USAGE;
 		}
 	}
 
 	if (optind == argc) {
 		fprintf(stderr, "%s: No socket-addr given\n", argv[0]);
 		return EX_USAGE;
 	}
 	port = argv[optind];
 
 	/*
 	 * Sanity checks on the clamav configuration file
 	 */
 	if((copt = parsecfg(cfgfile)) == NULL) {
 		fprintf(stderr, "%s: Can't parse the config file %s\n",
 			argv[0], cfgfile);
 		return EX_CONFIG;
 	}
 
434012b8
 	/*
 	 * Drop privileges
 	 */
 	if(getuid() == 0) {
 		if((cpt = cfgopt(copt, "User")) != NULL) {
 			if((user = getpwnam(cpt->strarg)) == NULL) {
 				fprintf(stderr, "%s: Can't get information about user %s\n", argv[0], cpt->strarg);
 				return EX_CONFIG;
 			}
bb9979e6
 
434012b8
 			if(cfgopt(copt, "AllowSupplementaryGroups"))
 				initgroups(cpt->strarg, user->pw_gid);
 			else
 				setgroups(1, &user->pw_gid);
 
 			setgid(user->pw_gid);
d69535ae
 			if(setuid(user->pw_uid) < 0)
 				perror(cpt->strarg);
 			else
 				cli_dbgmsg("Running as user %s (UID %d, GID %d)\n",
 					cpt->strarg, user->pw_uid, user->pw_gid);
434012b8
 		} else
 			fprintf(stderr, "%s: running as root is not recommended\n", argv[0]);
 	}
79f846a3
 	if(quarantine_dir) {
 		struct stat statb;
 
 		if(access(quarantine_dir, W_OK) < 0) {
 			perror(quarantine_dir);
 			return EX_CONFIG;
 		}
 		if(stat(quarantine_dir, &statb) < 0) {
 			perror(quarantine_dir);
 			return EX_CONFIG;
 		}
 		/*
 		 * Quit if the quarantine directory is publically readable
 		 * or writeable
 		 */
 		if(statb.st_mode & 077) {
 			fprintf(stderr, "%s: unsafe quarantine directory %s\n",
 				argv[0], quarantine_dir);
 			return EX_CONFIG;
 		}
3454ad43
 	}
bb9979e6
 
cdbe607d
 	if(sigFilename && !updateSigFile())
 		return EX_USAGE;
 
b90c8762
 	if(templatefile && (access(templatefile, R_OK) < 0)) {
 		perror(templatefile);
 		return EX_CONFIG;
1392cf22
 	}
 
b151ef55
 	if(!cfgopt(copt, "StreamSaveToDisk")) {
 		fprintf(stderr, "%s: StreamSavetoDisk not enabled in %s\n",
 			argv[0], cfgfile);
 		return EX_CONFIG;
 	}
 
 	if(!cfgopt(copt, "ScanMail")) {
cc511c7a
 		/*
 		 * In fact ScanMail isn't needed if this machine doesn't run
 		 * clamd.
 		 */
b151ef55
 		fprintf(stderr, "%s: ScanMail not enabled in %s\n",
 			argv[0], cfgfile);
 		return EX_CONFIG;
 	}
 
 	/*
b5d15e64
 	 * patch from "Richard G. Roberto" <rgr@dedlegend.com>
 	 * If the --max-children flag isn't set, see if MaxThreads
 	 * is set in the config file
 	 */
c15d1d2c
 	if((max_children == 0) && ((cpt = cfgopt(copt, "MaxThreads")) != NULL))
31268a5c
 		max_children = cpt->numarg;
b5d15e64
 
9873b3c1
 	if((cpt = cfgopt(copt, "ReadTimeout")) != NULL) {
cc511c7a
 		readTimeout = cpt->numarg;
d2efb3fa
 
cc511c7a
 		if(readTimeout < 0) {
9873b3c1
 			fprintf(stderr, "%s: ReadTimeout must not be negative in %s\n",
d2efb3fa
 				argv[0], cfgfile);
cc511c7a
 			return EX_CONFIG;
d2efb3fa
 		}
 	}
cc511c7a
 	if((cpt = cfgopt(copt, "StreamMaxLength")) != NULL) {
 		if(cpt->numarg < 0) {
 			fprintf(stderr, "%s: StreamMaxLength must not be negative in %s\n",
 				argv[0], cfgfile);
 			return EX_CONFIG;
 		}
5691e168
 		streamMaxLength = (long)cpt->numarg;
cc511c7a
 	}
b5d15e64
 	/*
b151ef55
 	 * Get the outgoing socket details - the way to talk to clamd
 	 */
f0d6f5a1
 	if((cpt = cfgopt(copt, "LocalSocket")) != NULL) {
 		if(cfgopt(copt, "TCPSocket") != NULL) {
 			fprintf(stderr, "%s: You can select one server type only (local/TCP) in %s\n",
 				argv[0], cfgfile);
 			return EX_CONFIG;
 		}
b151ef55
 		/*
 		 * TODO: check --server hasn't been set
 		 */
 		localSocket = cpt->strarg;
244be94f
 		if(!pingServer(-1)) {
f0d6f5a1
 			fprintf(stderr, "Can't talk to clamd server via %s\n",
 				localSocket);
 			fprintf(stderr, "Check your entry for LocalSocket in %s\n",
 				cfgfile);
 			return EX_CONFIG;
 		}
f7925922
 		/*if(quarantine_dir == NULL)
 			fprintf(stderr, "When using Localsocket in %s\nyou may improve performance if you use the --quarantine-dir option\n", cfgfile);*/
9873b3c1
 
e27af651
 		umask(077);
244be94f
 
 		serverIPs = (long *)cli_malloc(sizeof(long));
 		serverIPs[0] = inet_addr("127.0.0.1");
f0d6f5a1
 	} else if((cpt = cfgopt(copt, "TCPSocket")) != NULL) {
97727aa0
 		int i, activeServers;
244be94f
 
b151ef55
 		/*
 		 * TCPSocket is in fact a port number not a full socket
 		 */
3454ad43
 		if(quarantine_dir) {
 			fprintf(stderr, "%s: --quarantine-dir not supported for remote scanning - use --quarantine\n", argv[0]);
 			return EX_CONFIG;
 		}
 
cbd7686b
 		tcpSocket = (in_port_t)cpt->numarg;
244be94f
 
bbc9d684
 		/*
244be94f
 		 * cli_strtok's fieldno counts from 0
bbc9d684
 		 */
244be94f
 		for(;;) {
71f25024
 			char *hostname = cli_strtok(serverHostNames, numServers, ":");
244be94f
 			if(hostname == NULL)
 				break;
 			numServers++;
 			free(hostname);
bbc9d684
 		}
 
244be94f
 		cli_dbgmsg("numServers: %d\n", numServers);
3454ad43
 
244be94f
 		serverIPs = (long *)cli_malloc(numServers * sizeof(long));
97727aa0
 		activeServers = 0;
244be94f
 
 		for(i = 0; i < numServers; i++) {
71f25024
 			char *hostname = cli_strtok(serverHostNames, i, ":");
244be94f
 
 			/*
 			 * Translate server's name to IP address
 			 */
 			serverIPs[i] = inet_addr(hostname);
 			if(serverIPs[i] == -1L) {
 				const struct hostent *h = gethostbyname(hostname);
 
 				if(h == NULL) {
 					fprintf(stderr, "%s: Unknown host %s\n",
 						argv[0], hostname);
 					return EX_USAGE;
 				}
 
 				memcpy((char *)&serverIPs[i], h->h_addr, sizeof(serverIPs[i]));
 			}
 
97727aa0
 			if(pingServer(i))
 				activeServers++;
 			else {
 				cli_warnmsg("Warning Can't talk to clamd server %s on port %d\n",
244be94f
 					hostname, tcpSocket);
 			}
 			free(hostname);
b151ef55
 		}
97727aa0
 		if(activeServers == 0) {
 			cli_errmsg("Can't find any clamd servers\n");
 			cli_errmsg("Check your entry for TCPSocket in %s\n",
 				cfgfile);
 			return EX_CONFIG;
 		}
b151ef55
 	} else {
 		fprintf(stderr, "%s: You must select server type (local/TCP) in %s\n",
 			argv[0], cfgfile);
 		return EX_CONFIG;
 	}
 
f0d6f5a1
 	if(!cfgopt(copt, "Foreground")) {
cdbe607d
 #ifdef	CL_DEBUG
 		printf("When debugging it is recommended that you use Foreground mode in %s\n", cfgfile);
 		puts("So that you can see all of the messages");
 #endif
 
b151ef55
 		switch(fork()) {
 			case -1:
 				perror("fork");
 				return EX_TEMPFAIL;
 			case 0:	/* child */
 				break;
 			default:	/* parent */
 				return EX_OK;
 		}
f0d6f5a1
 		close(0);
a121491a
 		open("/dev/null", O_RDONLY);
 
 #ifndef	CL_DEBUG
f0d6f5a1
 		close(1);
 		close(2);
62f5a55b
 		if((open("/dev/console", O_WRONLY) == 1) ||
 		   (open("/dev/null", O_WRONLY) == 1))
f0d6f5a1
 			dup(1);
a121491a
 #endif
 
65a8d561
 #ifdef HAVE_SETPGRP
 #ifdef SETPGRP_VOID
0b6bce84
 		setpgrp();
65a8d561
 #else
 		setpgrp(0,0);
 #endif
 #else
 #ifdef HAVE_SETSID
 		 setsid();
 #endif
 #endif
f0d6f5a1
 	}
b151ef55
 
062dddc9
 	if((cpt = cfgopt(copt, "PidFile")) != NULL)
 		pidFile = cpt->strarg;
 
b151ef55
 	if(cfgopt(copt, "LogSyslog")) {
d69535ae
 		if(cfgopt(copt, "LogVerbose"))
 			logVerbose = 1;
 		use_syslog = 1;
 
b151ef55
 		openlog("clamav-milter", LOG_CONS|LOG_PID, LOG_MAIL);
d69535ae
 		if(logVerbose)
 			syslog(LOG_INFO, "Starting: %s", clamav_version);
 		else
 			syslog(LOG_INFO, clamav_version);
b151ef55
 #ifdef	CL_DEBUG
 		if(debug_level > 0)
 			syslog(LOG_DEBUG, "Debugging is on");
 #endif
1c3f1ce1
 	} else {
 		if(qflag)
d69535ae
 			fprintf(stderr, "%s: (-q && !LogSyslog): warning - all interception message methods are off\n",
1c3f1ce1
 				argv[0]);
b151ef55
 		use_syslog = 0;
1c3f1ce1
 	}
b151ef55
 
679ff9e7
 	if(pidfile) {
 		/* save the PID */
 		FILE *fd;
 		const mode_t old_umask = umask(0006);
 
 		if((fd = fopen(pidfile, "w")) == NULL) {
 			if(use_syslog)
 				syslog(LOG_WARNING, "Can't save PID in file %s",
 					pidfile);
 			cli_warnmsg("Can't save PID in file %s\n", pidfile);
 		} else {
 			fprintf(fd, "%d\n", (int)getpid());
 			fclose(fd);
 		}
 		umask(old_umask);
 	}
 
3a0b4e5b
 	if(cfgopt(copt, "FixStaleSocket")) {
 		/*
 		 * Get the incoming socket details - the way sendmail talks to
 		 * us
 		 *
434012b8
 		 * TODO: There's a security problem here that'll need fixing if
 		 * the User entry of clamav.conf is not used
3a0b4e5b
 		 */
 		if(strncasecmp(port, "unix:", 5) == 0) {
 			if(unlink(&port[5]) < 0)
462b5251
 				if(errno != ENOENT)
 					perror(&port[5]);
3a0b4e5b
 		} else if(strncasecmp(port, "local:", 6) == 0) {
 			if(unlink(&port[6]) < 0)
462b5251
 				if(errno != ENOENT)
 					perror(&port[6]);
3a0b4e5b
 		}
 	}
b151ef55
 
e27af651
 	if(smfi_setconn(port) == MI_FAILURE) {
 		fprintf(stderr, "%s: smfi_setconn failed\n",
 			argv[0]);
 		return EX_SOFTWARE;
 	}
 
b151ef55
 	if(smfi_register(smfilter) == MI_FAILURE) {
35d98cf9
 		cli_errmsg("smfi_register failure\n");
b151ef55
 		return EX_UNAVAILABLE;
 	}
 
 	signal(SIGPIPE, SIG_IGN);
 
d69535ae
 	if(logVerbose)
 		syslog(LOG_INFO, "Started: %s", clamav_version);
 
b151ef55
 	return smfi_main();
 }
 
 /*
  * Verify that the server is where we think it is
  * Returns true or false
244be94f
  *
97727aa0
  * serverNumber counts from 0, but is only used for TCPSocket
b151ef55
  */
 static int
244be94f
 pingServer(int serverNumber)
b151ef55
 {
f0d6f5a1
 	char *ptr;
b151ef55
 	int sock, nbytes;
f0d6f5a1
 	char buf[128];
b151ef55
 
f0d6f5a1
 	if(localSocket) {
 		struct sockaddr_un server;
b151ef55
 
f0d6f5a1
 		memset((char *)&server, 0, sizeof(struct sockaddr_un));
 		server.sun_family = AF_UNIX;
7cc3891c
 		strncpy(server.sun_path, localSocket, sizeof(server.sun_path));
f0d6f5a1
 
 		if((sock = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
 			perror("socket");
 			return 0;
 		}
6e945c41
 		checkClamd();
f0d6f5a1
 		if(connect(sock, (struct sockaddr *)&server, sizeof(struct sockaddr_un)) < 0) {
 			perror(localSocket);
6489ba59
 			close(sock);
f0d6f5a1
 			return 0;
 		}
 	} else {
 		struct sockaddr_in server;
 
 		memset((char *)&server, 0, sizeof(struct sockaddr_in));
 		server.sin_family = AF_INET;
cbd7686b
 		server.sin_port = (in_port_t)htons(tcpSocket);
 
ca59d8d0
 		assert(serverIPs != NULL);
244be94f
 		assert(serverIPs[0] != -1L);
bbc9d684
 
244be94f
 		server.sin_addr.s_addr = serverIPs[serverNumber];
f0d6f5a1
 
 		if((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
 			perror("socket");
 			return 0;
 		}
 		if(connect(sock, (struct sockaddr *)&server, sizeof(struct sockaddr_in)) < 0) {
 			perror("connect");
9873b3c1
 			close(sock);
f0d6f5a1
 			return 0;
 		}
b151ef55
 	}
f0d6f5a1
 
 	/*
 	 * It would be better to use PING, check for PONG then issue the
 	 * VERSION command, since that would better validate that we're
 	 * talking to clamd, however clamd closes the session after
 	 * sending PONG :-(
 	 * So this code does not really validate that we're talking to clamd
 	 * Needs a fix to clamd
 	 * Also version command is verbose: says "clamd / ClamAV version"
 	 * instead of "clamAV version"
 	 */
 	if(send(sock, "VERSION\n", 8, 0) < 8) {
b151ef55
 		perror("send");
 		close(sock);
 		return 0;
 	}
 
 	shutdown(sock, SHUT_WR);
 
d2efb3fa
 	nbytes = clamd_recv(sock, buf, sizeof(buf));
b151ef55
 
 	close(sock);
 
 	if(nbytes < 0) {
 		perror("recv");
 		return 0;
 	}
d2efb3fa
 	if(nbytes == 0)
 		return 0;
 
b151ef55
 	buf[nbytes] = '\0';
 
f0d6f5a1
 	/* Remove the trailing new line from the reply */
 	if((ptr = strchr(buf, '\n')) != NULL)
 		*ptr = '\0';
 
 	/*
 	 * No real validation is done here
244be94f
 	 *
 	 * TODO: When connecting to more than one server, give a warning
 	 *	if they're running different versions, or if the virus DBs
 	 *	are out of date
f0d6f5a1
 	 */
 	snprintf(clamav_version, sizeof(clamav_version),
b7f54bf2
 		"%s, clamav-milter version %s",
f0d6f5a1
 		buf, CM_VERSION);
bb9979e6
 
f0d6f5a1
 	return 1;
b151ef55
 }
 
244be94f
 /*
97727aa0
  * Find the best server to connect to. No intelligence to this.
  * It is best to weight the order of the servers from most wanted to least
  * wanted
244be94f
  *
  * Return value is from 0 - index into serverIPs
97727aa0
  *
  * If the load balancing fails return the first server in the list, not
  * an error, to be on the safe side
244be94f
  */
 static int
 findServer(void)
 {
 	struct sockaddr_in *servers, *server;
 	int *socks, maxsock = 0, i;
 	fd_set rfds;
 	struct timeval tv;
 	int retval;
 
 	assert(tcpSocket != 0);
 	assert(numServers > 0);
 
 	if(numServers == 1)
 		return 0;
 
 	servers = (struct sockaddr_in *)cli_calloc(numServers, sizeof(struct sockaddr_in));
 	socks = (int *)cli_malloc(numServers * sizeof(int));
 
 	FD_ZERO(&rfds);
 
 	for(i = 0, server = servers; i < numServers; i++, server++) {
 		int sock;
 
 		server->sin_family = AF_INET;
cbd7686b
 		server->sin_port = (in_port_t)htons(tcpSocket);
244be94f
 		server->sin_addr.s_addr = serverIPs[i];
 
 		sock = socks[i] = socket(AF_INET, SOCK_STREAM, 0);
 		if(sock < 0) {
 			perror("socket");
 			do
 				if(socks[i] >= 0)
 					close(socks[i]);
 			while(--i >= 0);
 			free(socks);
 			free(servers);
 			return 0;	/* Use the first server on failure */
 		}
 
 		if((connect(sock, (struct sockaddr *)server, sizeof(struct sockaddr)) < 0) ||
 		   (send(sock, "PING\n", 5, 0) < 5)) {
97727aa0
 			const char *hostname = cli_strtok(serverHostNames, i, ":");
c51c112c
 			cli_warnmsg("Check clamd server %s - it may be down\n", hostname);
244be94f
 			if(use_syslog)
97727aa0
 				syslog(LOG_WARNING,
c51c112c
 					"Check clamd server %s - it may be down",
97727aa0
 					hostname);
244be94f
 			socks[i] = -1;
6489ba59
 			close(sock);
244be94f
 			continue;
 		}
 
 		shutdown(sock, SHUT_WR);
 
 		FD_SET(sock, &rfds);
 		if(sock > maxsock)
 			maxsock = sock;
 	}
 
 	free(servers);
 
cc511c7a
 	tv.tv_sec = readTimeout;
244be94f
 	tv.tv_usec = 0;
cbd7686b
 
97727aa0
 	retval = select(maxsock + 1, &rfds, NULL, NULL, &tv);
244be94f
 	if(retval < 0)
 		perror("select");
 
 	for(i = 0; i < numServers; i++)
 		if(socks[i] >= 0)
 			close(socks[i]);
 
 	if(retval == 0) {
 		free(socks);
 		cli_dbgmsg("findServer: No response from any server\n");
 		if(use_syslog)
 			syslog(LOG_WARNING, "findServer: No response from any server");
 		return 0;
 	} else if(retval < 0) {
 		free(socks);
 		if(use_syslog)
c51c112c
 			syslog(LOG_ERR, "findServer: select failed");
244be94f
 		return 0;
 	}
 
 	for(i = 0; i < numServers; i++)
 		if(FD_ISSET(socks[i], &rfds)) {
 			free(socks);
cbd7686b
 			cli_dbgmsg("findServer: using server %d\n", i);
244be94f
 			return i;
 		}
 
 	free(socks);
 	cli_dbgmsg("findServer: No response from any server\n");
 	if(use_syslog)
 		syslog(LOG_WARNING, "findServer: No response from any server");
 	return 0;
 }
 
6489ba59
 /*
  * Sendmail wants to establish a connection to us
  */
b151ef55
 static sfsistat
 clamfi_connect(SMFICTX *ctx, char *hostname, _SOCK_ADDR *hostaddr)
6489ba59
 {
0a9dafb1
 #if	defined(HAVE_INET_NTOP) || defined(WITH_TCPWRAP)
35d98cf9
 	char ip[INET_ADDRSTRLEN];	/* IPv4 only */
0a9dafb1
 #endif
f8a7079c
 	char *remoteIP;
b151ef55
 
2a1ff3e4
 	if(hostname == NULL) {
 		if(use_syslog)
 			syslog(LOG_ERR, "clamfi_connect: hostname is null");
 		return cl_error;
 	}
40c9a608
 	if(hostaddr == NULL)
 		/*
 		 * According to the sendmail API hostaddr is NULL if
 		 * "the type is not supported in the current version". What
 		 * the documentation doesn't say is the type of what?
 		 *
d69535ae
 		 * Possibly the input is not a TCP/IP socket e.g. stdin?
40c9a608
 		 */
 		remoteIP = "127.0.0.1";
 	else {
0a9dafb1
 #ifdef HAVE_INET_NTOP
40c9a608
 		remoteIP = (char *)inet_ntop(AF_INET, &((struct sockaddr_in *)(hostaddr))->sin_addr, ip, sizeof(ip));
0a9dafb1
 #else
40c9a608
 		remoteIP = inet_ntoa(((struct sockaddr_in *)(hostaddr))->sin_addr);
0a9dafb1
 #endif
2a1ff3e4
 
40c9a608
 		if(remoteIP == NULL) {
 			if(use_syslog)
 				syslog(LOG_ERR, "clamfi_connect: remoteIP is null");
 			return cl_error;
 		}
2a1ff3e4
 	}
80a72b0d
 
1f025849
 #ifdef	CL_DEBUG
e2bb746e
 	if(debug_level >= 4) {
 		if(use_syslog)
 			syslog(LOG_NOTICE, "clamfi_connect: connection from %s [%s]", hostname, remoteIP);
35d98cf9
 		cli_dbgmsg("clamfi_connect: connection from %s [%s]\n", hostname, remoteIP);
e2bb746e
 	}
1f025849
 #endif
b151ef55
 
f8a7079c
 #ifdef	WITH_TCPWRAP
 	/*
 	 * Support /etc/hosts.allow and /etc/hosts.deny
 	 */
8f1f6fb8
 	if(strncasecmp(port, "inet:", 5) == 0) {
ce14cc31
 		const char *hostmail;
 		const struct hostent *hp = NULL;
35d98cf9
 
cbd7686b
 		/*
ce14cc31
 		 * Using TCP/IP for the sendmail->clamav-milter connection
 		 */
 		if((hostmail = smfi_getsymval(ctx, "{if_name}")) == NULL) {
 			if(use_syslog)
 				syslog(LOG_WARNING, "Can't get sendmail hostname");
 			hostmail = "unknown";
 		}
35d98cf9
 
ce14cc31
 		if((hp = gethostbyname(hostmail)) == NULL) {
 			if(use_syslog)
 				syslog(LOG_WARNING, "Access Denied: Host Unknown (%s)", hostname);
62f5a55b
 			return cl_error;
ce14cc31
 		}
35d98cf9
 
62f5a55b
 #ifdef HAVE_INET_NTOP
b90c8762
 		if(inet_ntop(AF_INET, (struct in_addr *)hp->h_addr, ip, sizeof(ip)) == NULL) {
d69535ae
 			perror(hp->h_name);
 			/*if(use_syslog)
 				syslog(LOG_WARNING, "Can't get IP address for (%s)", hp->h_name);
 			strcpy(ip, (char *)inet_ntoa(*(struct in_addr *)hp->h_addr));*/
 			if(use_syslog)
 				syslog(LOG_WARNING, "Access Denied: Can't get IP address for (%s)", hp->h_name);
 			return cl_error;
 		}
62f5a55b
 #else
b90c8762
 		strncpy(ip, (char *)inet_ntoa(*(struct in_addr *)hp->h_addr), sizeof(ip) - 1);
62f5a55b
 #endif
ce14cc31
 
 		/*
 		 * Ask is this is a allowed name or IP number
 		 */
 		if(!hosts_ctl("clamav-milter", hp->h_name, ip, STRING_UNKNOWN)) {
 			if(use_syslog)
 				syslog(LOG_WARNING, "Access Denied for %s[%s]", hp->h_name, ip);
 			return SMFIS_TEMPFAIL;
 		}
f8a7079c
 	}
 #endif
 
b5d15e64
 	if(fflag)
 		/*
 		 * Patch from "Richard G. Roberto" <rgr@dedlegend.com>
 		 * Always scan whereever the message is from
 		 */
 		return SMFIS_CONTINUE;
 
b151ef55
 	if(!oflag)
 		if(strcmp(remoteIP, "127.0.0.1") == 0) {
 #ifdef	CL_DEBUG
 			if(use_syslog)
 				syslog(LOG_DEBUG, "clamfi_connect: not scanning outgoing messages");
cbd7686b
 			cli_dbgmsg("clamfi_connect: not scanning outgoing messages\n");
b151ef55
 #endif
 			return SMFIS_ACCEPT;
 		}
 	if(!lflag) {
 		/*
 		 * Decide what constitutes a local IP address. Emails from
 		 * local machines are not scanned.
 		 *
 		 * TODO: read these from clamav.conf
 		 */
 		static const char *localAddresses[] = {
 			/*"^192\\.168\\.[0-9]+\\.[0-9]+$",*/
 			"^192\\.168\\.[0-9]*\\.[0-9]*$",
 			"^10\\.0\\.0\\.[0-9]*$",
 			"127.0.0.1",
 			NULL
 		};
 		const char **possible;
 
 		for(possible = localAddresses; *possible; possible++) {
 			int rc;
 			regex_t reg;
 
 			if(regcomp(&reg, *possible, 0) != 0) {
 				if(use_syslog)
 					syslog(LOG_ERR, "Couldn't parse local regexp");
b0a42ec6
 				return cl_error;
b151ef55
 			}
 
 			rc = (regexec(&reg, remoteIP, 0, NULL, 0) == REG_NOMATCH) ? 0 : 1;
 
 			regfree(&reg);
 
 			if(rc) {
 #ifdef	CL_DEBUG
 				if(use_syslog)
 					syslog(LOG_DEBUG, "clamfi_connect: not scanning local messages");
cbd7686b
 				cli_dbgmsg("clamfi_connect: not scanning outgoing messages\n");
b151ef55
 #endif
 				return SMFIS_ACCEPT;
 			}
 		}
 	}
b7f54bf2
 
b151ef55
 	return SMFIS_CONTINUE;
 }
 
 static sfsistat
 clamfi_envfrom(SMFICTX *ctx, char **argv)
 {
 	struct privdata *privdata;
 
 	if(logVerbose)
 		syslog(LOG_DEBUG, "clamfi_envfrom: %s", argv[0]);
 
6489ba59
 	cli_dbgmsg("clamfi_envfrom: %s\n", argv[0]);
b151ef55
 
 	if(max_children > 0) {
6489ba59
 		int rc = 0;
b151ef55
 
 		pthread_mutex_lock(&n_children_mutex);
 
3a805bfd
 		/*
 		 * Not a while since sendmail doesn't like it if we
 		 * take too long replying. Effectively this means that
 		 * max_children is more of a hint than a rule
 		 */
 		if(n_children >= max_children) {
b151ef55
 			struct timeval now;
 			struct timespec timeout;
 			struct timezone tz;
 
d69535ae
 			if(use_syslog)
 				syslog(LOG_NOTICE,
 					"hit max-children limit (%u >= %u): waiting for some to exit",
 					n_children, max_children);
 
b151ef55
 			/*
 			 * Use pthread_cond_timedwait rather than
 			 * pthread_cond_wait since the sendmail which calls
 			 * us will have a timeout that we don't want to exceed
 			 *
 			 * Wait for a maximum of 1 minute.
 			 *
 			 * TODO: this timeout should be configurable
d69535ae
 			 *
b151ef55
 			 * It stops sendmail getting fidgety.
d69535ae
 			 *
 			 * Patch from Damian Menscher <menscher@uiuc.edu> to
 			 * ensure it wakes up when a child goes away
b151ef55
 			 */
 			gettimeofday(&now, &tz);
 			timeout.tv_sec = now.tv_sec + 60;
 			timeout.tv_nsec = 0;
 
3a805bfd
 			do
 				rc = pthread_cond_timedwait(&n_children_cond, &n_children_mutex, &timeout);
d69535ae
 			while((n_children >= max_children) && (rc != ETIMEDOUT));
b151ef55
 		}
 		n_children++;
 
6489ba59
 		cli_dbgmsg(">n_children = %d\n", n_children);
b151ef55
 		pthread_mutex_unlock(&n_children_mutex);
 
 		if(rc == ETIMEDOUT) {
 #ifdef	CL_DEBUG
 			if(use_syslog)
 				syslog(LOG_NOTICE, "Timeout waiting for a child to die");
 #endif
cbd7686b
 			cli_dbgmsg("Timeout waiting for a child to die\n");
b151ef55
 		}
 	}
 
64d5612d
 	privdata = (struct privdata *)cli_calloc(1, sizeof(struct privdata));
063b6c33
 	if(privdata == NULL)
6ad582fe
 		return cl_error;
063b6c33
 
b151ef55
 	privdata->dataSocket = -1;	/* 0.4 */
 	privdata->cmdSocket = -1;	/* 0.4 */
 
a121491a
 	/*
 	 * Rejection is via 550 until DATA is received. We know that
 	 * DATA has been sent when either we get a header or the end of
 	 * header statement
 	 */
 	privdata->rejectCode = "550";
 
b151ef55
 	privdata->from = strdup(argv[0]);
 
cc511c7a
 	if(hflag)
 		privdata->headers = header_list_new();
64d5612d
 
 	if(smfi_setpriv(ctx, privdata) == MI_SUCCESS)
 		return SMFIS_CONTINUE;
 
 	clamfi_free(privdata);
d9b674b2
 
64d5612d
 	return cl_error;
b151ef55
 }
 
 static sfsistat
 clamfi_envrcpt(SMFICTX *ctx, char **argv)
 {
 	struct privdata *privdata = (struct privdata *)smfi_getpriv(ctx);
 
 	if(logVerbose)
 		syslog(LOG_DEBUG, "clamfi_envrcpt: %s", argv[0]);
 
6489ba59
 	cli_dbgmsg("clamfi_envrcpt: %s\n", argv[0]);
b151ef55
 
 	if(privdata->to == NULL) {
cbd7686b
 		privdata->to = cli_malloc(sizeof(char *) * 2);
b151ef55
 
 		assert(privdata->numTo == 0);
 	} else
ea815cbc
 		privdata->to = cli_realloc(privdata->to, sizeof(char *) * (privdata->numTo + 2));
b151ef55
 
063b6c33
 	if(privdata->to == NULL)
6ad582fe
 		return cl_error;
063b6c33
 
b151ef55
 	privdata->to[privdata->numTo] = strdup(argv[0]);
 	privdata->to[++privdata->numTo] = NULL;
 
 	return SMFIS_CONTINUE;
 }
 
 static sfsistat
 clamfi_header(SMFICTX *ctx, char *headerf, char *headerv)
 {
 	struct privdata *privdata = (struct privdata *)smfi_getpriv(ctx);
 
 	if(logVerbose)
 		syslog(LOG_DEBUG, "clamfi_header: %s: %s", headerf, headerv);
 #ifdef	CL_DEBUG
 	if(debug_level >= 9)
6489ba59
 		cli_dbgmsg("clamfi_header: %s: %s\n", headerf, headerv);
b151ef55
 	else
cbd7686b
 		cli_dbgmsg("clamfi_header\n");
b151ef55
 #endif
 
a121491a
 	/*
 	 * The DATA instruction from SMTP (RFC2821) must have been sent
 	 */
 	privdata->rejectCode = "554";
 
6489ba59
 	if(privdata->dataSocket == -1)
 		/*
 		 * First header - make connection with clamd
 		 */
 		if(!connect2clamd(privdata)) {
 			clamfi_cleanup(ctx);
 			return cl_error;
 		}
 
0cb97bcb
 	if(clamfi_send(privdata, 0, "%s: %s\n", headerf, headerv) <= 0) {
b151ef55
 		clamfi_cleanup(ctx);
b0a42ec6
 		return cl_error;
b151ef55
 	}
d9b674b2
 
 	if(hflag)
cbd7686b
 		header_list_add(privdata->headers, headerf, headerv);
97727aa0
 	else if((strcasecmp(headerf, "Received") == 0) &&
a121491a
 		(strncasecmp(headerv, "from ", 5) == 0)) {
97727aa0
 		if(privdata->received)
063b6c33
 			free(privdata->received);
 		privdata->received = strdup(headerv);
 	}
 
a121491a
 	if((strcasecmp(headerf, "Message-ID") == 0) &&
 	   (strncasecmp(headerv, "<MDAEMON", 8) == 0))
 		privdata->discard = 1;
 
b151ef55
 	return SMFIS_CONTINUE;
 }
 
a121491a
 /*
  * At this point DATA will have been received, so we really ought to
  * send 554 back not 550
  */
b151ef55
 static sfsistat
 clamfi_eoh(SMFICTX *ctx)
 {
 	struct privdata *privdata = (struct privdata *)smfi_getpriv(ctx);
b14e9e77
 	char **to;
b151ef55
 
 	if(logVerbose)
 		syslog(LOG_DEBUG, "clamfi_eoh");
 #ifdef	CL_DEBUG
6489ba59
 	if(debug_level >= 4)
 		cli_dbgmsg("clamfi_eoh\n");
b151ef55
 #endif
 
a121491a
 	/*
 	 * The DATA instruction from SMTP (RFC2821) must have been sent
 	 */
 	privdata->rejectCode = "554";
 
6489ba59
 	if(privdata->dataSocket == -1)
 		/*
 		 * No headers - make connection with clamd
 		 */
 		if(!connect2clamd(privdata)) {
 			clamfi_cleanup(ctx);
 			return cl_error;
 		}
 
0cb97bcb
 	if(clamfi_send(privdata, 1, "\n") != 1) {
b151ef55
 		clamfi_cleanup(ctx);
b0a42ec6
 		return cl_error;
b151ef55
 	}
 
b14e9e77
 	/*
 	 * See if the e-mail is only going to members of the list
 	 * of users we don't scan for. If it is, don't scan, otherwise
 	 * scan
 	 *
 	 * scan = false
 	 * FORALL recipients
 	 *	IF receipient NOT MEMBER OF white address list
 	 *	THEN
 	 *		scan = true
 	 *	FI
 	 * ENDFOR
 	 */
 	for(to = privdata->to; *to; to++) {
 		const char **s;
 
 		for(s = ignoredEmailAddresses; *s; s++)
 			if(strcasecmp(*s, *to) == 0)
 				/*
 				 * This recipient is on the whitelist
 				 */
 				break;
 
 		if(*s == NULL)
 			/*
 			 * This recipient is not on the whitelist,
 			 * no need to check any further
 			 */
 			return SMFIS_CONTINUE;
 	}
 	/*
 	 * Didn't find a recipient who is not on the white list, so all
 	 * must be on the white list, so just accept the e-mail
 	 */
 	if(use_syslog)
9873b3c1
 		syslog(LOG_NOTICE, "clamfi_eoh: ignoring whitelisted message");
b14e9e77
 #ifdef	CL_DEBUG
9873b3c1
 	cli_dbgmsg("clamfi_eoh: not scanning outgoing messages\n");
b14e9e77
 #endif
 	clamfi_cleanup(ctx);
 
 	return SMFIS_ACCEPT;
b151ef55
 }
 
 static sfsistat
 clamfi_body(SMFICTX *ctx, u_char *bodyp, size_t len)
 {
 	struct privdata *privdata = (struct privdata *)smfi_getpriv(ctx);
0cb97bcb
 	int nbytes;
b151ef55
 
 	if(logVerbose)
 		syslog(LOG_DEBUG, "clamfi_envbody: %u bytes", len);
 #ifdef	CL_DEBUG
6489ba59
 	cli_dbgmsg("clamfi_envbody: %u bytes\n", len);
b151ef55
 #endif
 
0cb97bcb
 	nbytes = clamfi_send(privdata, len, (char *)bodyp);
5691e168
 	if(streamMaxLength > 0L) {
cc511c7a
 		if(privdata->numBytes > streamMaxLength) {
6ad582fe
 			if(use_syslog) {
 				const char *sendmailId = smfi_getsymval(ctx, "i");
 				if(sendmailId == NULL)
 					sendmailId = "Unknown";
c51c112c
 				syslog(LOG_NOTICE, "%s: Message more than StreamMaxLength (%ld) bytes - not scanned",
6ad582fe
 					sendmailId, streamMaxLength);
 			}
0cb97bcb
 			if(!nflag)
 				smfi_addheader(ctx, "X-Virus-Status", "Not Scanned - StreamMaxLength exceeded");
 
 			return SMFIS_ACCEPT;	/* clamfi_close will be called */
cc511c7a
 		}
 	}
0cb97bcb
 	if(nbytes < len) {
cc511c7a
 		clamfi_cleanup(ctx);	/* not needed, but just to be safe */
b0a42ec6
 		return cl_error;
b151ef55
 	}
e6bffccb
 	if(Sflag) {
3166c010
 		if(privdata->body) {
 			assert(privdata->bodyLen > 0);
a121491a
 			privdata->body = cli_realloc(privdata->body, privdata->bodyLen + len);
3166c010
 			memcpy(&privdata->body[privdata->bodyLen], bodyp, len);
 			privdata->bodyLen += len;
e6bffccb
 		} else {
3166c010
 			assert(privdata->bodyLen == 0);
cbd7686b
 			privdata->body = cli_malloc(len);
3166c010
 			memcpy(privdata->body, bodyp, len);
 			privdata->bodyLen = len;
e6bffccb
 		}
 	}
b151ef55
 	return SMFIS_CONTINUE;
 }
 
 static sfsistat
 clamfi_eom(SMFICTX *ctx)
 {
 	int rc = SMFIS_CONTINUE;
 	char *ptr;
c96f7461
 	const char *sendmailId;
b151ef55
 	struct privdata *privdata = (struct privdata *)smfi_getpriv(ctx);
 	char mess[128];
 
 	if(logVerbose)
 		syslog(LOG_DEBUG, "clamfi_eom");
 #ifdef	CL_DEBUG
cbd7686b
 	cli_dbgmsg("clamfi_eom\n");
b151ef55
 	assert(privdata != NULL);
3454ad43
 	assert((privdata->cmdSocket >= 0) || (privdata->filename != NULL));
 	assert(!((privdata->cmdSocket >= 0) && (privdata->filename != NULL)));
b151ef55
 	assert(privdata->dataSocket >= 0);
 #endif
 
 	close(privdata->dataSocket);
 	privdata->dataSocket = -1;
 
3454ad43
 	if(quarantine_dir != NULL) {
 		char cmdbuf[1024];
 		/*
 		 * Create socket to talk to clamd.
 		 */
 		struct sockaddr_un server;
 		int nbytes;
 
 		assert(localSocket != NULL);
 
 		memset((char *)&server, 0, sizeof(struct sockaddr_un));
 		server.sun_family = AF_UNIX;
7cc3891c
 		strncpy(server.sun_path, localSocket, sizeof(server.sun_path));
3454ad43
 
 		if((privdata->cmdSocket = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
 			perror("socket");
85c1dbfd
 			clamfi_cleanup(ctx);
3454ad43
 			return cl_error;
 		}
 		if(connect(privdata->cmdSocket, (struct sockaddr *)&server, sizeof(struct sockaddr_un)) < 0) {
 			perror(localSocket);
85c1dbfd
 			clamfi_cleanup(ctx);
3454ad43
 			return cl_error;
 		}
 
 		snprintf(cmdbuf, sizeof(cmdbuf) - 1, "SCAN %s", privdata->filename);
 
 		nbytes = (int)strlen(cmdbuf);
 
 		if(send(privdata->cmdSocket, cmdbuf, nbytes, 0) < nbytes) {
 			perror("send");
 			clamfi_cleanup(ctx);
 			if(use_syslog)
 				syslog(LOG_ERR, "send failed to clamd");
 			return cl_error;
 		}
 
 		shutdown(privdata->cmdSocket, SHUT_WR);
 	}
 
d2efb3fa
 	if(clamd_recv(privdata->cmdSocket, mess, sizeof(mess)) > 0) {
b151ef55
 		if((ptr = strchr(mess, '\n')) != NULL)
 			*ptr = '\0';
 
 		if(logVerbose)
 			syslog(LOG_DEBUG, "clamfi_eom: read %s", mess);
6489ba59
 		cli_dbgmsg("clamfi_eom: read %s\n", mess);
b151ef55
 	} else {
85c1dbfd
 		clamfi_cleanup(ctx);
b151ef55
 		syslog(LOG_NOTICE, "clamfi_eom: read nothing from clamd");
 #ifdef	CL_DEBUG
cbd7686b
 		cli_dbgmsg("clamfi_eom: read nothing from clamd\n");
b151ef55
 #endif
d2efb3fa
 		return cl_error;
b151ef55
 	}
 
0b6bce84
 	close(privdata->cmdSocket);
 	privdata->cmdSocket = -1;
 
c96f7461
 	sendmailId = smfi_getsymval(ctx, "i");
6ad582fe
 	if(sendmailId == NULL)
 		sendmailId = "Unknown";
6489ba59
 
71f25024
 	if(!nflag) {
 		char buf[1024];
 
 		/*
 		 * Include the hostname where the scan took place:
 		 */
39378e7f
 		if(localSocket)
 			snprintf(buf, sizeof(buf) - 1, "%s\n\ton %s",
 				clamav_version,
 				smfi_getsymval(ctx, "{j}"));
 		else {
 			char *hostname = cli_strtok(serverHostNames, privdata->serverNumber, ":");
 
 			if(hostname) {
 				snprintf(buf, sizeof(buf) - 1, "%s\n\ton %s",
 					clamav_version,
 					hostname);
 				free(hostname);
 			} else
 				/* sanity check failed - should issue warning */
 				strcpy(buf, "Error determining host");
 		}
71f25024
 		smfi_addheader(ctx, "X-Virus-Scanned", buf);
 	}
40c9a608
 
c96f7461
 	if(strstr(mess, "ERROR") != NULL) {
0a867b46
 		if(strstr(mess, "Size exceeded") != NULL) {
 			/*
 			 * Clamd has stopped on StreamMaxLength before us
 			 */
 			if(use_syslog)
c51c112c
 				syslog(LOG_NOTICE, "%s: Message more than StreamMaxLength (%ld) bytes - not scanned",
0a867b46
 					sendmailId, streamMaxLength);
0cb97bcb
 			if(!nflag)
 				smfi_addheader(ctx, "X-Virus-Status", "Not Scanned - StreamMaxLength exceeded");
39378e7f
 			clamfi_cleanup(ctx);	/* not needed, but just to be safe */
0a867b46
 			return SMFIS_ACCEPT;
 		}
0cb97bcb
 		if(!nflag)
 			smfi_addheader(ctx, "X-Virus-Status", "Not Scanned");
6489ba59
 
c96f7461
 		cli_warnmsg("%s: %s\n", sendmailId, mess);
e27af651
 		if(use_syslog)
c96f7461
 			syslog(LOG_ERR, "%s: %s\n", sendmailId, mess);
e27af651
 		clamfi_cleanup(ctx);
 		return cl_error;
 	}
 
62f5a55b
 	if((ptr = strstr(mess, "FOUND")) == NULL) {
3613bd91
 		if(!nflag)
40c9a608
 			smfi_addheader(ctx, "X-Virus-Status", "Clean");
b151ef55
 
 		/*
 		 * TODO: if privdata->from is NULL it's probably SPAM, and
 		 * me might consider bouncing it...
 		 */
3bc05064
 		if(use_syslog && logClean)
e2bb746e
 			/* Include the sendmail queue ID in the log */
 			syslog(LOG_NOTICE, "%s: clean message from %s",
c96f7461
 				sendmailId,
c6259ac5
 				(privdata->from) ? privdata->from : "an unknown sender");
e6bffccb
 
3166c010
 		if(privdata->body) {
e2bb746e
 			/*
 			 * Add a signature that all has been scanned OK
 			 */
cdbe607d
 			off_t len = updateSigFile();
e6bffccb
 
cdbe607d
 			if(len) {
 				assert(Sflag != 0);
e6bffccb
 
a121491a
 				privdata->body = cli_realloc(privdata->body, privdata->bodyLen + len);
 				if(privdata->body) {
 					memcpy(&privdata->body[privdata->bodyLen], signature, len);
 					smfi_replacebody(ctx, privdata->body, privdata->bodyLen + len);
 				}
cdbe607d
 			}
e6bffccb
 		}
b151ef55
 	} else {
dd68be92
 		char reject[1024];
97727aa0
 		char **to, *virusname;
62f5a55b
 
 		*ptr = '\0';	/* Remove the "FOUND" word */
b151ef55
 
97727aa0
 		/* skip over 'stream/filename: ' at the start */
 		if((virusname = strchr(mess, ':')) != NULL)
 			virusname = &virusname[2];
 		else
 			virusname = mess;
 
40c9a608
 		if(!nflag)
 			smfi_addheader(ctx, "X-Virus-Status", "Infected");
 
62f5a55b
 		if(use_syslog) {
 			/*
 			 * Setup err as a list of recipients
 			 */
 			char *err = (char *)cli_malloc(1024);
 			int i;
b151ef55
 
62f5a55b
 			if(err == NULL) {
 				clamfi_cleanup(ctx);
 				return cl_error;
 			}
063b6c33
 
62f5a55b
 			/*
 			 * Use snprintf rather than printf since we don't know the
 			 * length of privdata->from and may get a buffer overrun
 			 */
 			snprintf(err, 1023, "Intercepted virus from %s to",
 				privdata->from);
b151ef55
 
62f5a55b
 			ptr = strchr(err, '\0');
b151ef55
 
62f5a55b
 			i = 1024;
c6259ac5
 
62f5a55b
 			for(to = privdata->to; *to; to++) {
 				/*
 				 * Re-alloc if we are about run out of buffer space
 				 */
 				if(&ptr[strlen(*to) + 2] >= &err[i]) {
 					i += 1024;
a121491a
 					err = cli_realloc(err, i);
 					if(err == NULL) {
 						clamfi_cleanup(ctx);
 						return cl_error;
 					}
62f5a55b
 					ptr = strchr(err, '\0');
 				}
 				ptr = strrcpy(ptr, " ");
 				ptr = strrcpy(ptr, *to);
b151ef55
 			}
62f5a55b
 			(void)strcpy(ptr, "\n");
b151ef55
 
e2bb746e
 			/* Include the sendmail queue ID in the log */
97727aa0
 			syslog(LOG_NOTICE, "%s: %s%s", sendmailId, mess, err);
b151ef55
 #ifdef	CL_DEBUG
62f5a55b
 			cli_dbgmsg("%s\n", err);
b151ef55
 #endif
62f5a55b
 			free(err);
 		}
b151ef55
 
1c3f1ce1
 		if(!qflag) {
b696653a
 			char cmd[128];
64d9c7a1
 			FILE *sendmail;
b696653a
 
97727aa0
 			/*
 			 * If the oflag is given this sendmail command
 			 * will cause the mail being generated here to be
 			 * scanned. So if oflag is given we just put the
 			 * item in the queue so there's no scanning of two
 			 * messages at once. It'll still be scanned, but
 			 * not at the same time as the incoming message
 			 */
 			snprintf(cmd, sizeof(cmd) - 1,
c51c112c
 				(oflag || fflag) ? "%s -t -odq" : "%s -t",
 				SENDMAIL_BIN);
b696653a
 
 			sendmail = popen(cmd, "w");
 
1c3f1ce1
 			if(sendmail) {
b7f54bf2
 				const char *from;
 
 				/*
 				 * Try to determine who sent the message.
 				 * In the days of faked from addresses this is
 				 * not easy!
 				 */
 				if(privdata->from)
 					from = (strcmp(privdata->from, "<>") == 0) ?
 						smfi_getsymval(ctx, "_") :
 						privdata->from;
 				else
 					from = smfi_getsymval(ctx, "_");
 
dd0d5a8c
 				/*
 				 * TODO: Make this e-mail message customisable
 				 * perhaps by means of a template
 				 */
063b6c33
 				fprintf(sendmail, "From: %s\n", from);
1c3f1ce1
 				if(bflag) {
 					fprintf(sendmail, "To: %s\n", privdata->from);
 					fprintf(sendmail, "Cc: %s\n", postmaster);
 				} else
 					fprintf(sendmail, "To: %s\n", postmaster);
 
 				if(!pflag)
 					for(to = privdata->to; *to; to++)
 						fprintf(sendmail, "Cc: %s\n", *to);
9873b3c1
 				/*
d69535ae
 				 * Auto-submitted is still a draft, keep an
9873b3c1
 				 * eye on its format
 				 */
 				fputs("Auto-Submitted: auto-submitted (antivirus notify)\n", sendmail);
d69535ae
 				/* "Sergey Y. Afonin" <asy@kraft-s.ru> */
 				if((ptr = smfi_getsymval(ctx, "{_}")) != NULL)
 					fprintf(sendmail,
 						"X-Infected-Received-From: %s\n",
 						ptr);
1c3f1ce1
 				fputs("Subject: Virus intercepted\n\n", sendmail);
 
1392cf22
 				if((templatefile == NULL) ||
 				   (sendtemplate(templatefile, sendmail, mess) < 0)) {
 					if(bflag)
62f5a55b
 						fputs("A message you sent to\n", sendmail);
1392cf22
 					else if(pflag)
 						/*
 						 * The message is only going to the
 						 * postmaster, so include some useful
 						 * information
 						 */
62f5a55b
 						fprintf(sendmail, "The message %s sent from %s to\n",
1392cf22
 							sendmailId, from);
 					else
62f5a55b
 						fprintf(sendmail, "A message sent from %s to\n",
1392cf22
 							from);
 
 					for(to = privdata->to; *to; to++)
62f5a55b
 						fprintf(sendmail, "\t%s\n", *to);
97727aa0
 					fprintf(sendmail, "contained %sand has not been delivered.\n", virusname);
1392cf22
 
 					if(privdata->filename != NULL)
 						fprintf(sendmail, "\nThe message in question has been quarantined as %s\n", privdata->filename);
 
97727aa0
 					if(hflag) {
 						fprintf(sendmail, "\nThe message was received by %s from %s via %s\n\n",
 							smfi_getsymval(ctx, "j"), from,
 							smfi_getsymval(ctx, "_"));
 						fputs("For your information, the original message headers were:\n\n", sendmail);
 						header_list_print(privdata->headers, sendmail);
 					} else if(privdata->received)
063b6c33
 						/*
 						 * TODO: parse this to find
 						 * real infected machine.
 						 * Need to decide how to find
 						 * if it's a dynamic IP from a
 						 * dial up account in which
 						 * case there may not be much
 						 * we can do if that DHCP has
 						 * set the hostname...
 						 */
 						fprintf(sendmail, "\nThe infected machine is likely to be here:\n%s\t\n",
 							privdata->received);
 
d9b674b2
 				}
3454ad43
 
1c3f1ce1
 				pclose(sendmail);
 			}
b151ef55
 		}
3454ad43
 
 		if(privdata->filename) {
 			assert(quarantine_dir != NULL);
 
 			if(use_syslog)
 				syslog(LOG_NOTICE, "Quarantined infected mail as %s", privdata->filename);
 			/*
0cb97bcb
 			 * Cleanup filename here otherwise clamfi_free() will
 			 * delete the file that we wish to keep because it
 			 * is infected
3454ad43
 			 */
 			free(privdata->filename);
 			privdata->filename = NULL;
 		}
 
bb9979e6
 		if(quarantine) {
 			for(to = privdata->to; *to; to++) {
 				smfi_delrcpt(ctx, *to);
3454ad43
 				smfi_addheader(ctx, "X-Original-To", *to);
bb9979e6
 				free(*to);
 			}
 			free(privdata->to);
 			privdata->to = NULL;
c51c112c
 			/*
 			 * NOTE: on a closed relay this will not work
 			 * if the recipient is a remote address
 			 */
bb9979e6
 			if(smfi_addrcpt(ctx, quarantine) == MI_FAILURE) {
 				if(use_syslog)
 					syslog(LOG_DEBUG, "Can't set quarantine user %s", quarantine);
 				else
6489ba59
 					cli_warnmsg("Can't set quarantine user %s\n", quarantine);
c51c112c
 			} else {
 				char subject[128];
 
bb9979e6
 				/*
 				 * FIXME: doesn't work if there's no subject
 				 */
c51c112c
 				snprintf(subject, sizeof(subject) - 1,
 					"[Virus] %s", virusname);
 				smfi_chgheader(ctx, "Subject", 1, subject);
 			}
a121491a
 		} else if(rejectmail) {
 			if(privdata->discard)
 				rc = SMFIS_DISCARD;
 			else
 				rc = SMFIS_REJECT;	/* Delete the e-mail */
 		} else
a7164828
 			rc = SMFIS_DISCARD;
b151ef55
 
97727aa0
 		snprintf(reject, sizeof(reject) - 1, "%sdetected by ClamAV - http://www.clamav.net", virusname);
a121491a
 		smfi_setreply(ctx, (char *)privdata->rejectCode, "5.7.1", reject);
b151ef55
 	}
 	clamfi_cleanup(ctx);
 
 	return rc;
 }
 
 static sfsistat
 clamfi_abort(SMFICTX *ctx)
 {
 #ifdef	CL_DEBUG
 	if(use_syslog)
 		syslog(LOG_DEBUG, "clamfi_abort");
cbd7686b
 	cli_dbgmsg("clamfi_abort\n");
b151ef55
 #endif
 
 	/*
 	 * Unlock incase we're called during a cond_timedwait in envfrom
 	 *
d69535ae
 	 * TODO: There *must* be a tidier a safer way of doing this!
b151ef55
 	 */
d69535ae
 	if((max_children > 0) && (n_children >= max_children))
3a805bfd
 		(void)pthread_mutex_unlock(&n_children_mutex);
b151ef55
 
 	clamfi_cleanup(ctx);
 
b0a42ec6
 	return cl_error;
b151ef55
 }
 
 static sfsistat
 clamfi_close(SMFICTX *ctx)
 {
 	struct privdata *privdata = (struct privdata *)smfi_getpriv(ctx);
 
cbd7686b
 	cli_dbgmsg("clamfi_close\n");
0cb97bcb
 	if(privdata != NULL)
 		clamfi_cleanup(ctx);
b151ef55
 
 	if(logVerbose)
 		syslog(LOG_DEBUG, "clamfi_close");
 
 	return SMFIS_CONTINUE;
 }
 
 static void
 clamfi_cleanup(SMFICTX *ctx)
 {
 	struct privdata *privdata = (struct privdata *)smfi_getpriv(ctx);
 
3613bd91
 	if(privdata) {
64d5612d
 		clamfi_free(privdata);
 		smfi_setpriv(ctx, NULL);
 	}
 }
 
 static void
 clamfi_free(struct privdata *privdata)
 {
 	if(privdata) {
3166c010
 		if(privdata->body)
 			free(privdata->body);
 
3613bd91
 		if(privdata->dataSocket >= 0) {
 			close(privdata->dataSocket);
 			privdata->dataSocket = -1;
 		}
b151ef55
 
3454ad43
 		if(privdata->filename != NULL) {
0cb97bcb
 			if(unlink(privdata->filename) < 0) {
3454ad43
 				perror(privdata->filename);
0cb97bcb
 				if(use_syslog)
 					syslog(LOG_ERR,
 						"Can't remove clean file %s",
 						privdata->filename);
 			}
3454ad43
 			free(privdata->filename);
 			privdata->filename = NULL;
 		}
 
3613bd91
 		if(privdata->from) {
b151ef55
 #ifdef	CL_DEBUG
3613bd91
 			if(debug_level >= 9)
cbd7686b
 				cli_dbgmsg("Free privdata->from\n");
b151ef55
 #endif
3613bd91
 			free(privdata->from);
 			privdata->from = NULL;
 		}
b151ef55
 
3613bd91
 		if(privdata->to) {
 			char **to;
b151ef55
 
3613bd91
 			for(to = privdata->to; *to; to++) {
b151ef55
 #ifdef	CL_DEBUG
3613bd91
 				if(debug_level >= 9)
cbd7686b
 					cli_dbgmsg("Free *privdata->to\n");
b151ef55
 #endif
3613bd91
 				free(*to);
 			}
b151ef55
 #ifdef	CL_DEBUG
3613bd91
 			if(debug_level >= 9)
cbd7686b
 				cli_dbgmsg("Free privdata->to\n");
b151ef55
 #endif
3613bd91
 			free(privdata->to);
 			privdata->to = NULL;
 		}
b151ef55
 
3613bd91
 		if(privdata->cmdSocket >= 0) {
 			char buf[64];
b151ef55
 
3613bd91
 			/*
 			 * Flush the remote end so that clamd doesn't get a SIGPIPE
 			 */
d2efb3fa
 			while(clamd_recv(privdata->cmdSocket, buf, sizeof(buf)) > 0)
3613bd91
 				;
 			close(privdata->cmdSocket);
 			privdata->cmdSocket = -1;
 		}
d9b674b2
 		if(privdata->headers)
 			header_list_free(privdata->headers);
b151ef55
 
 #ifdef	CL_DEBUG
3613bd91
 		if(debug_level >= 9)
cbd7686b
 			cli_dbgmsg("Free privdata\n");
b151ef55
 #endif
97727aa0
 		if(privdata->received)
063b6c33
 			free(privdata->received);
3613bd91
 		free(privdata);
 	}
b151ef55
 
 	if(max_children > 0) {
 		pthread_mutex_lock(&n_children_mutex);
 		/*
 		 * Deliberately errs on the side of broadcasting too many times
 		 */
390a7661
 		if(n_children > 0)
 			--n_children;
b151ef55
 #ifdef	CL_DEBUG
cbd7686b
 		cli_dbgmsg("pthread_cond_broadcast\n");
b151ef55
 #endif
3a805bfd
 		pthread_cond_broadcast(&n_children_cond);
b151ef55
 #ifdef	CL_DEBUG
35d98cf9
 		cli_dbgmsg("<n_children = %d\n", n_children);
b151ef55
 #endif
 		pthread_mutex_unlock(&n_children_mutex);
 	}
 }
 
6489ba59
 /*
0cb97bcb
  * Returns < 0 for failure, otherwise the number of bytes sent
6489ba59
  */
b151ef55
 static int
0cb97bcb
 clamfi_send(struct privdata *privdata, size_t len, const char *format, ...)
b151ef55
 {
 	char output[BUFSIZ];
 	const char *ptr;
0cb97bcb
 	int ret = 0;
b151ef55
 
 	assert(format != NULL);
 
 	if(len > 0)
 		/*
 		 * It isn't a NUL terminated string. We have a set number of
 		 * bytes to output.
 		 */
 		ptr = format;
 	else {
 		va_list argp;
 
 		va_start(argp, format);
b90c8762
 		vsnprintf(output, sizeof(output) - 1, format, argp);
b151ef55
 		va_end(argp);
 
 		len = strlen(output);
 		ptr = output;
 	}
 #ifdef	CL_DEBUG
6489ba59
 	if(debug_level >= 9) {
 		time_t t;
 		const struct tm *tm;
 
 		time(&t);
 		tm = localtime(&t);
 
 		cli_dbgmsg("%d:%d:%d clamfi_send: len=%u bufsiz=%u, fd=%d\n",
 			tm->tm_hour, tm->tm_min, tm->tm_sec, len,
 			sizeof(output), privdata->dataSocket);
 	}
b151ef55
 #endif
 
 	while(len > 0) {
e2bb746e
 		const int nbytes = (quarantine_dir) ?
3454ad43
 			write(privdata->dataSocket, ptr, len) :
 			send(privdata->dataSocket, ptr, len, 0);
b151ef55
 
ea815cbc
 		assert(privdata->dataSocket >= 0);
 
b151ef55
 		if(nbytes == -1) {
f7925922
 			if(quarantine_dir) {
 				perror(privdata->filename);
 				if(use_syslog) {
 #ifdef HAVE_STRERROR_R
 					char buf[32];
 					strerror_r(errno, buf, sizeof(buf));
 					syslog(LOG_ERR,
 						"write failure (%u bytes) to %s: %s",
 						len, privdata->filename, buf);
 #else
 					syslog(LOG_ERR, "write failure (%u bytes) to %s: %s",
 						len, privdata->filename,
 						strerror(errno));
 #endif
 				}
 			} else {
 				if(errno == EINTR)
 					continue;
 				perror("send");
 				if(use_syslog) {
ea815cbc
 #ifdef HAVE_STRERROR_R
f7925922
 					char buf[32];
 					strerror_r(errno, buf, sizeof(buf));
 					syslog(LOG_ERR,
 						"write failure (%u bytes) to clamd: %s",
 						len, buf);
ea815cbc
 #else
f7925922
 					syslog(LOG_ERR, "write failure (%u bytes) to clamd: %s", len, strerror(errno));
ea815cbc
 #endif
f7925922
 				}
 				checkClamd();
ea815cbc
 			}
b151ef55
 
 			return -1;
 		}
0cb97bcb
 		ret += nbytes;
b151ef55
 		len -= nbytes;
 		ptr = &ptr[nbytes];
0cb97bcb
 
 		if(streamMaxLength > 0L) {
 			privdata->numBytes += nbytes;
 			if(privdata->numBytes >= streamMaxLength)
 				break;
 		}
b151ef55
 	}
0cb97bcb
 	return ret;
b151ef55
 }
 
 /*
  * Like strcpy, but return the END of the destination, allowing a quicker
  * means of adding to the end of a string than strcat
  */
 static char *
 strrcpy(char *dest, const char *source)
 {
 	/* Pre assertions */
 	assert(dest != NULL);
 	assert(source != NULL);
 	assert(dest != source);
 
 	while((*dest++ = *source++) != '\0')
 		;
 	return(--dest);
 }
d2efb3fa
 
 /*
  * Read from clamav - timeout if necessary
  */
 static int
 clamd_recv(int sock, char *buf, size_t len)
 {
 	fd_set rfds;
 	struct timeval tv;
 
cc511c7a
 	if(readTimeout == 0)
d2efb3fa
 		return recv(sock, buf, len, 0);
 
 	FD_ZERO(&rfds);
 	FD_SET(sock, &rfds);
 
cc511c7a
 	tv.tv_sec = readTimeout;
d2efb3fa
 	tv.tv_usec = 0;
 
 	switch(select(sock + 1, &rfds, NULL, NULL, &tv)) {
 		case -1:
 			perror("select");
 			return -1;
 		case 0:
 			if(use_syslog)
cc511c7a
 				syslog(LOG_ERR, "No data received from clamd in %d seconds\n", readTimeout);
d2efb3fa
 			return 0;
 	}
 	return recv(sock, buf, len, 0);
 }
cdbe607d
 
 /*
  * Read in the signature file
  */
 static off_t
 updateSigFile(void)
 {
 	struct stat statb;
 	int fd;
 
 	if(sigFilename == NULL)
 		/* nothing to read */
a121491a
 		return 0;
cdbe607d
 
 	if(stat(sigFilename, &statb) < 0) {
 		perror(sigFilename);
 		if(use_syslog)
c51c112c
 			syslog(LOG_ERR, "Can't stat %s", sigFilename);
cdbe607d
 		return 0;
 	}
 
 	if(statb.st_mtime <= signatureStamp)
 		return statb.st_size;	/* not changed */
 
 	fd = open(sigFilename, O_RDONLY);
 	if(fd < 0) {
 		perror(sigFilename);
 		if(use_syslog)
c51c112c
 			syslog(LOG_ERR, "Can't open %s", sigFilename);
cdbe607d
 		return 0;
 	}
 
 	signatureStamp = statb.st_mtime;
 
c63633c4
 	signature = cli_realloc(signature, statb.st_size);
cdbe607d
 	read(fd, signature, statb.st_size);
 	close(fd);
 
 	return statb.st_size;
 }
d9b674b2
 
 static header_list_t
8f1f6fb8
 header_list_new(void)
d9b674b2
 {
 	header_list_t ret;
 
 	ret = (header_list_t)cli_malloc(sizeof(struct header_list_struct));
063b6c33
 	if(ret) {
 		ret->first = NULL;
 		ret->last = NULL;
 	}
d9b674b2
 	return ret;
 }
 
 static void
 header_list_free(header_list_t list)
 {
 	struct header_node_t *iter;
 
 	iter = list->first;
 	while (iter) {
 		struct header_node_t *iter2 = iter->next;
 		free(iter->header);
 		free(iter);
 		iter = iter2;
 	}
 	free(list);
 }
 
 static void
 header_list_add(header_list_t list, const char *headerf, const char *headerv)
 {
 	char *header;
 	size_t len;
 	struct header_node_t *new_node;
 
71f25024
 	len = (size_t)(strlen(headerf) + strlen(headerv) + 3);
d9b674b2
 
 	header = (char *)cli_malloc(len);
063b6c33
 	if(header == NULL)
 		return;
 
0a867b46
 	sprintf(header, "%s: %s", headerf, headerv);
cbd7686b
 	new_node = (struct header_node_t *)cli_malloc(sizeof(struct header_node_t));
063b6c33
 	if(new_node == NULL) {
 		free(header);
 		return;
 	}
d9b674b2
 	new_node->header = header;
 	new_node->next = NULL;
 	if(!list->first)
 		list->first = new_node;
 	if(list->last)
 		list->last->next = new_node;
 
 	list->last = new_node;
 }
 
 static void
 header_list_print(header_list_t list, FILE *fp)
 {
 	const struct header_node_t *iter;
 
97727aa0
 	for(iter = list->first; iter; iter = iter->next) {
c51c112c
 		if(strncmp(iter->header, "From ", 5) == 0)
97727aa0
 			putc('>', fp);
d9b674b2
 		fprintf(fp, "%s\n", iter->header);
97727aa0
 	}
d9b674b2
 }
1392cf22
 
6489ba59
 /*
  * Establish a connection to clamd
  *	Returns success (1) or failure (0)
  */
 static int
 connect2clamd(struct privdata *privdata)
 {
 	char **to;
 
a121491a
 	assert(privdata != NULL);
6489ba59
 	assert(privdata->dataSocket == -1);
 	assert(privdata->from != NULL);
 	assert(privdata->to != NULL);
 
 #ifdef	CL_DEBUG
 	if((debug_level > 0) && use_syslog)
 		syslog(LOG_DEBUG, "connect2clamd");
 	if(debug_level >= 4)
 		cli_dbgmsg("connect2clamd\n");
 #endif
 
 	if(quarantine_dir) {
 		/*
 		 * quarantine_dir is specified
 		 * store message in a temporary file
 		 */
 		int ntries = 5;
063b6c33
 		long t;
 		int MM, YY, DD;
 		const struct tm *tm;
6489ba59
 
063b6c33
 		/*
 		 * Based on an idea by Christian Pelissier
 		 * <Christian.Pelissier@onera.fr>. Store different days
 		 * in different directories to make them easier to manage
 		 */
 		t = time((long *)0);
 		tm = localtime(&t);
 		MM = tm->tm_mon + 1;
 		YY = tm->tm_year - 100;
 		DD = tm->tm_mday;
 
 		privdata->filename = (char *)cli_malloc(strlen(quarantine_dir) + 19);
 
 		sprintf(privdata->filename, "%s/%02d%02d%02d", quarantine_dir,
97727aa0
 			YY, MM, DD);
063b6c33
 
 		(void)mkdir(privdata->filename, 0700);
6489ba59
 
 		do {
063b6c33
 			sprintf(privdata->filename,
 				"%s/%02d%02d%02d/msg.XXXXXX",
 				quarantine_dir, YY, MM, DD);
6489ba59
 #if	defined(C_LINUX) || defined(C_BSD) || defined(HAVE_MKSTEMP) || defined(C_SOLARIS)
 			privdata->dataSocket = mkstemp(privdata->filename);
 #else
 			if(mktemp(privdata->filename) == NULL) {
 				if(use_syslog)
 					syslog(LOG_ERR, "mktemp %s failed", privdata->filename);
 				return 0;
 			}
 			privdata->dataSocket = open(privdata->filename, O_CREAT|O_EXCL|O_WRONLY|O_TRUNC, 0600);
 #endif
 		} while((--ntries > 0) && (privdata->dataSocket < 0));
 
 		if(privdata->dataSocket < 0) {
a121491a
 			perror(privdata->filename);
6489ba59
 			if(use_syslog)
a121491a
 				syslog(LOG_ERR, "Temporary quarantine file %s creation failed", privdata->filename);
6489ba59
 			return 0;
 		}
39378e7f
 		privdata->serverNumber = -1;
6489ba59
 	} else {
 		int freeServer, nbytes;
 		struct sockaddr_in reply;
 		unsigned short port;
 		char buf[64];
 
 		assert(privdata->cmdSocket == -1);
 
 		/*
 		 * Create socket to talk to clamd. It will tell us the port to
 		 * use to send the data. That will require another socket.
 		 */
 		if(localSocket) {
 			struct sockaddr_un server;
 
 			memset((char *)&server, 0, sizeof(struct sockaddr_un));
 			server.sun_family = AF_UNIX;
7cc3891c
 			strncpy(server.sun_path, localSocket, sizeof(server.sun_path));
6489ba59
 
 			if((privdata->cmdSocket = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
 				perror("socket");
 				return 0;
 			}
 			if(connect(privdata->cmdSocket, (struct sockaddr *)&server, sizeof(struct sockaddr_un)) < 0) {
 				perror(localSocket);
 				return 0;
 			}
 			freeServer = 0;
39378e7f
 			privdata->serverNumber = -1;
6489ba59
 		} else {
 			struct sockaddr_in server;
 
 			memset((char *)&server, 0, sizeof(struct sockaddr_in));
 			server.sin_family = AF_INET;
 			server.sin_port = (in_port_t)htons(tcpSocket);
 
 			assert(serverIPs != NULL);
 
 			freeServer = findServer();
 			if(freeServer < 0)
 				return 0;
 
 			server.sin_addr.s_addr = serverIPs[freeServer];
 
 			if((privdata->cmdSocket = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
 				perror("socket");
 				return 0;
 			}
 			if(connect(privdata->cmdSocket, (struct sockaddr *)&server, sizeof(struct sockaddr_in)) < 0) {
 				perror("connect");
 				return 0;
 			}
39378e7f
 			privdata->serverNumber = freeServer;
6489ba59
 		}
 
 		/*
 		 * Create socket that we'll use to send the data to clamd
 		 */
 		if((privdata->dataSocket = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
 			perror("socket");
 			if(use_syslog)
 				syslog(LOG_ERR, "failed to create socket");
 			return 0;
 		}
 
 		shutdown(privdata->dataSocket, SHUT_RD);
 
 		if(send(privdata->cmdSocket, "STREAM\n", 7, 0) < 7) {
 			perror("send");
 			if(use_syslog)
 				syslog(LOG_ERR, "send failed to clamd");
 			return 0;
 		}
 
 		shutdown(privdata->cmdSocket, SHUT_WR);
 
 		nbytes = clamd_recv(privdata->cmdSocket, buf, sizeof(buf));
 		if(nbytes < 0) {
 			perror("recv");
 			if(use_syslog)
 				syslog(LOG_ERR, "recv failed from clamd getting PORT");
 			return 0;
 		}
 		buf[nbytes] = '\0';
 #ifdef	CL_DEBUG
 		if(debug_level >= 4)
 			cli_dbgmsg("Received: %s", buf);
 #endif
 		if(sscanf(buf, "PORT %hu\n", &port) != 1) {
 			if(use_syslog)
 				syslog(LOG_ERR, "Expected port information from clamd, got '%s'",
 					buf);
 			else
 				cli_warnmsg("Expected port information from clamd, got '%s'\n",
 					buf);
 			return 0;
 		}
 
 		memset((char *)&reply, 0, sizeof(struct sockaddr_in));
 		reply.sin_family = AF_INET;
 		reply.sin_port = (in_port_t)htons(port);
 
 		assert(serverIPs != NULL);
 
 		reply.sin_addr.s_addr = serverIPs[freeServer];
 
 #ifdef	CL_DEBUG
 		if(debug_level >= 4)
 			cli_dbgmsg("Connecting to local port %d\n", port);
 #endif
 
 		if(connect(privdata->dataSocket, (struct sockaddr *)&reply, sizeof(struct sockaddr_in)) < 0) {
 			perror("connect");
 
 			/* 0.4 - use better error message */
 			if(use_syslog) {
 #ifdef HAVE_STRERROR_R
 				strerror_r(errno, buf, sizeof(buf));
 				syslog(LOG_ERR,
 					"Failed to connect to port %d given by clamd: %s",
 					port, buf);
 #else
 				syslog(LOG_ERR, "Failed to connect to port %d given by clamd: %s", port, strerror(errno));
 #endif
 			}
 			return 0;
 		}
 	}
 
 	/*
 	 * TODO:
 	 *	Put from and to data into a buffer and call clamfi_send once
 	 * to save bandwidth when using TCP/IP to connect with a remote clamd
 	 */
 	clamfi_send(privdata, 0,
 		"Received: by clamav-milter\nFrom: %s\n",
 		privdata->from);
 
 	for(to = privdata->to; *to; to++)
0cb97bcb
 		if(clamfi_send(privdata, 0, "To: %s\n", *to) <= 0)
6489ba59
 			return 0;
 
 	cli_dbgmsg("connect2clamd OK\n");
 
 	return 1;
 }
062dddc9
 
 /*
  * If possible, check if clamd has died, and report if it has
  */
 static void
 checkClamd(void)
 {
 	pid_t pid;
 	int fd, nbytes;
 	char buf[9];
 
 	if(!localSocket)
ea815cbc
 		return;	/* communicating via TCP */
062dddc9
 
 	if(pidFile == NULL)
ea815cbc
 		return;	/* PidFile directive missing from clamav.conf */
062dddc9
 
 	fd = open(pidFile, O_RDONLY);
 	if(fd < 0) {
 		perror(pidFile);
 		if(use_syslog)
c51c112c
 			syslog(LOG_ERR, "Can't open %s", pidFile);
062dddc9
 		return;
 	}
 	nbytes = read(fd, buf, sizeof(buf) - 1);
b90c8762
 	if(nbytes < 0)
 		perror(pidFile);
 	else
 		buf[nbytes] = '\0';
062dddc9
 	close(fd);
 	pid = atoi(buf);
6e945c41
 	if((kill(pid, 0) < 0) && (errno == ESRCH)) {
 		if(use_syslog)
c51c112c
 			syslog(LOG_ERR, "Clamd (pid %d) seems to have died",
6e945c41
 				pid);
 		perror("clamd");
062dddc9
 	}
 }
1392cf22
 
 /*
  * Send a templated message about an intercepted message. Very basic for
  * now, just to prove it works, will enhance the flexability later, only
  * supports %v at present. And only one instance of %v at that
063b6c33
  *
  * TODO: more template features
  * TODO: allow filename to start with a '|' taken to mean the output of
  *	a program
1392cf22
  */
 static int
 sendtemplate(const char *filename, FILE *sendmail, const char *clamdMessage)
 {
 	FILE *fin = fopen(filename, "r");
 	struct stat statb;
 	char *buf, *ptr;
 	int rc;
 
 	if(fin == NULL) {
 		perror(filename);
 		if(use_syslog)
c51c112c
 			syslog(LOG_ERR, "Can't open e-mail template file %s",
1392cf22
 				filename);
 		return -1;
 	}
 
 	if(fstat(fileno(fin), &statb) < 0) {
 		/* File disappeared in race condition? */
 		perror(filename);
 		if(use_syslog)
c51c112c
 			syslog(LOG_ERR, "Can't stat e-mail template file %s",
1392cf22
 				filename);
 		fclose(fin);
 		return -1;
 	}
 	buf = cli_malloc(statb.st_size + 1);
 	if(buf == NULL) {
 		if(use_syslog)
c51c112c
 			syslog(LOG_ERR, "Out of memory");
1392cf22
 		fclose(fin);
 		return -1;
 	}
 	fread(buf, sizeof(char), statb.st_size, fin);
 	fclose(fin);
 	buf[statb.st_size] = '\0';
 
 	if((ptr = strstr(buf, "%v")) != NULL) {
 		*ptr = '\0';
 		ptr = &ptr[2];
 		fputs(buf, sendmail);
 		/* Need to peel out the virus name and just send that */
 		fputs(clamdMessage, sendmail);
 		rc = (fputs(ptr, sendmail) == EOF) ? -1 : 0;
 	} else
 		rc = (fputs(buf, sendmail) == EOF) ? -1 : 0;
 
 	free(buf);
 
 	return 0;
 }