clamav-devel/clamav-milter/clamav-milter.c
e3aaff8e
 /*
  * 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.
  *
7e10f99b
  * Install into /usr/local/sbin/clamav-milter
e3aaff8e
  *
  * See http://www.nmt.edu/~wcolburn/sendmail-8.12.5/libmilter/docs/sample.html
  *
81bdf63b
  * For installation instructions see the file INSTALL that came with this file
5b6bb93b
  *
2cd8b9d4
  * Change History:
  * $Log: clamav-milter.c,v $
e368b3dd
  * Revision 1.121  2004/08/26 10:22:00  nigelhorne
  * Fix overflow To:
  *
aead37b9
  * Revision 1.120  2004/08/25 11:44:56  nigelhorne
  * Tidy
  *
226d027a
  * Revision 1.119  2004/08/13 10:21:38  nigelhorne
  * Single thread through tcp_wrappers
  *
ff46437f
  * Revision 1.118  2004/08/12 12:18:45  nigelhorne
  * Fixed from
  *
eef726b0
  * Revision 1.117  2004/08/11 10:34:07  nigelhorne
  * Better isLocal handler
  *
6302a4f6
  * Revision 1.116  2004/08/07 13:10:33  nigelhorne
  * Better load balancing
  *
b475d5ea
  * Revision 1.115  2004/08/06 10:08:31  nigelhorne
  * Quarantined files now include the virus in the name
  *
734ea355
  * Revision 1.114  2004/08/05 07:44:28  nigelhorne
  * Better Template Handling
  *
dd2edd28
  * Revision 1.113  2004/07/30 14:34:56  nigelhorne
  * Handle changed clamd message
  *
7e4e3eba
  * Revision 1.112  2004/07/29 15:24:47  nigelhorne
  * Don't say waiting for some to exit if dont_wait is set
  *
452e28cb
  * Revision 1.111  2004/07/29 06:38:05  nigelhorne
  * GETHOSTBYNAME_R_6
  *
a0c42dae
  * Revision 1.110  2004/07/26 13:23:27  nigelhorne
  * Remove stream: from template %v
  *
1e2aaf5e
  * Revision 1.109  2004/07/25 11:51:42  nigelhorne
  * Fix crash if 1st host dies
  *
a166f2d4
  * Revision 1.108  2004/07/22 15:45:03  nigelhorne
  * Up-issue
  *
2a14f0d6
  * Revision 1.107  2004/07/22 09:14:32  nigelhorne
  * Use gethostbyname_r when available
  *
150789eb
  * Revision 1.106  2004/07/21 21:23:29  nigelhorne
  * Mutex gethostbyname result
  *
0fbdd75a
  * Revision 1.105  2004/07/21 17:46:06  nigelhorne
  * Added note about needing MILTER support in sendmail
  *
459b60af
  * Revision 1.104  2004/07/14 10:17:05  nigelhorne
  * Added dont-wait and advisory options
  *
9cbf69cc
  * Revision 1.103  2004/07/08 22:22:39  nigelhorne
  * Don't pass empty arguments to inet_ntop
  *
4a944387
  * Revision 1.102  2004/06/29 15:26:14  nigelhorne
  * Support the --timeout argument
  *
0cd0f0df
  * Revision 1.101  2004/06/29 10:04:47  nigelhorne
  * Up issued
  *
20bca05f
  * Revision 1.100  2004/06/29 08:27:02  nigelhorne
  * Up issued
  *
18c4370d
  * Revision 1.99  2004/06/28 08:30:18  nigelhorne
  * Don't error when creating the quarantine directory if it already exists
  *
05c5d068
  * Revision 1.98  2004/06/22 04:09:12  nigelhorne
  * Avoid unlocking unlocked mutex in clamfi_abort
  *
456edb55
  * Revision 1.97  2004/06/16 08:08:47  nigelhorne
  * Allow access to sendmail variables in the template file
  *
03d91eec
  * Revision 1.96  2004/06/14 14:34:15  nigelhorne
  * Added support for Windows SFU 3.5
  *
2d05ab2c
  * Revision 1.95  2004/06/14 09:05:49  nigelhorne
  * Up-issued
  *
cc71d7c2
  * Revision 1.94  2004/06/13 02:11:25  kojm
  * improve output
  *
08992bbd
  * Revision 1.93  2004/06/08 21:44:59  nigelhorne
  * Ensure --from takes an argument
  *
0d007d91
  * Revision 1.92  2004/06/03 13:14:08  nigelhorne
  * Up-issued
  *
0abc0a57
  * Revision 1.91  2004/05/25 16:24:21  nigelhorne
  * X-Virus-Scanned wasn't being added in maxstreamlength was exceeded
  *
81bdf63b
  * Revision 1.90  2004/05/24 17:05:18  nigelhorne
  * Include the hostname of the scanner in the headers
  *
ea4465c4
  * Revision 1.89  2004/05/21 09:14:57  nigelhorne
  * Handle --from, print error message if write to quarantine fails
  *
0c933aca
  * Revision 1.88  2004/05/16 08:25:09  nigelhorne
  * Up issue
  *
ba2dfeb2
  * Revision 1.87  2004/05/09 17:39:04  nigelhorne
  * Waiting threads weren't being woken up
  *
7d81c053
  * Revision 1.86  2004/05/06 11:25:20  nigelhorne
  * Some work on maxStreamLength
  *
d23d480c
  * Revision 1.85  2004/04/29 07:35:27  nigelhorne
  * Change from realloc to cli_realloc - keep assignment
  *
b5c80361
  * Revision 1.84  2004/04/28 14:28:29  nigelhorne
  * Various updates
  *
e84cbd98
  * Revision 1.83  2004/04/25 12:56:35  nigelhorne
  * Added --pidfile
  *
a321a25b
  * Revision 1.82  2004/04/23 09:13:30  nigelhorne
  * Better quarantine email subject
  *
736c8d91
  * Revision 1.81  2004/04/22 16:47:04  nigelhorne
  * Various changes
  *
144bc6cf
  * Revision 1.80  2004/04/21 15:27:02  nigelhorne
  * Various changes
  *
23248fbc
  * Revision 1.79  2004/04/20 14:15:01  nigelhorne
  * Sorted out X- headers and handle hostaddr == NULL
  *
08b0add9
  * Revision 1.78  2004/04/20 08:13:15  nigelhorne
  * Print better message if hostaddr is null
  *
502c8234
  * Revision 1.77  2004/04/19 22:11:20  nigelhorne
  * Many changes
  *
af73bfee
  * Revision 1.76  2004/04/19 13:28:41  nigelhorne
  * Started coding e-mail template support
  *
3ce543c7
  * Revision 1.75  2004/04/19 13:28:00  nigelhorne
  * Started coding e-mail template support
  *
6a54127a
  * Revision 1.74  2004/04/17 20:39:04  nigelhorne
  * Add the virus name into the 550 rejection if sent
  *
95df50d1
  * Revision 1.73  2004/04/15 09:53:25  nigelhorne
  * Handle systems without inet_ntop
  *
f9f239aa
  * Revision 1.72  2004/04/09 08:36:53  nigelhorne
  * Handle clamd giving up on StreamMaxLength before clamav-milter
  *
bb09a2f7
  * Revision 1.71  2004/04/08 13:14:07  nigelhorne
  * Code tidy up
  *
658f19f8
  * Revision 1.70  2004/04/06 22:43:43  kojm
  * reverse strlcpy/strlcat patch
  *
db1cae22
  * Revision 1.69  2004/04/06 12:14:52  kojm
  * use strlcpy/strlcat
  *
96f3d93b
  * Revision 1.68  2004/04/03 04:47:22  nigelhorne
  * Honour StreamMaxLength
  *
00727a0e
  * Revision 1.67  2004/04/01 15:34:00  nigelhorne
  * ThreadTimeout has been renamed ReadTimeout
  *
86b3e542
  * Revision 1.66  2004/03/31 20:48:03  nigelhorne
  * Config file has changed
  *
f7ab4278
  * Revision 1.65  2004/03/27 21:44:21  nigelhorne
  * Attempt to handle clamd quick timeout for slow remote sites
  *
8ac80fb8
  * Revision 1.64  2004/03/26 11:10:27  nigelhorne
  * Added debug information
  *
268a4f2d
  * Revision 1.63  2004/03/20 12:30:00  nigelhorne
  * strerror_r is confused on Linux
  *
46a4aaa1
  * Revision 1.62  2004/03/17 19:46:49  nigelhorne
  * Upissue to 0.70@
  *
a2f725f6
  * Revision 1.61  2004/03/15 19:54:12  kojm
  * 0.70-rc
  *
1070b274
  * Revision 1.60  2004/03/10 11:31:03  nigelhorne
  * Use HAVE_STRERROR_R
  *
5b6bb93b
  * Revision 1.59  2004/03/07 15:11:15  nigelhorne
  * Added more information to headers flag
  *
1f7a8360
  * Revision 1.58  2004/03/03 09:14:55  nigelhorne
  * Change way check for TCPwrappers on TCP/IP
  *
ecaaaf05
  * Revision 1.57  2004/02/27 15:27:11  nigelhorne
  * call checkClamd on start
  *
664f9ff6
  * Revision 1.56  2004/02/27 09:23:56  nigelhorne
  * Don't use TCP wrappers when UNIX domain sockets are used
  *
e84162a4
  * Revision 1.55  2004/02/22 22:53:50  nigelhorne
  * Handle ERROR message from clamd
  *
7e10f99b
  * Revision 1.54  2004/02/22 17:27:40  nigelhorne
  * Updated installation instructions now that privileges are dropped
  *
bd547be2
  * Revision 1.53  2004/02/21 11:03:23  nigelhorne
  * Error if quarantine-dir is publically accessable
  *
b5648b5a
  * Revision 1.52  2004/02/20 17:07:24  nigelhorne
  * Added checkClamd
  *
1fcdb893
  * Revision 1.51  2004/02/20 09:50:42  nigelhorne
  * Removed warnings added by new configuration script
  *
f9c88a98
  * Revision 1.50  2004/02/19 10:00:26  nigelhorne
  * Rework TCPWrappers support
  *
fdc6066a
  * Revision 1.49  2004/02/18 13:30:34  nigelhorne
  * Added dont-long-clean argument
  *
055404a5
  * Revision 1.48  2004/02/18 10:06:51  nigelhorne
  * Fix FreeBSD
  *
c54d7329
  * Revision 1.47  2004/02/16 11:55:24  nigelhorne
  * Added clamfi_free which helps with the tidying up
  *
3adce0a6
  * Revision 1.46  2004/02/16 09:39:22  nigelhorne
  * Upissued to 0.67
  *
b2fb75ea
  * Revision 1.45  2004/02/14 17:20:38  nigelhorne
  * Add TCPwrappers support
  *
9e1e77b9
  * Revision 1.44  2004/02/09 11:05:33  nigelhorne
  * Added Hflag
  *
7908713f
  * Revision 1.43  2004/02/07 12:16:20  nigelhorne
  * Added config.h
  *
d4b2e2e4
  * Revision 1.42  2004/02/02 13:44:31  nigelhorne
  * Include the ID of the message when warnings are sent to the postmaster-only
  *
3a03d183
  * Revision 1.41  2004/01/29 12:52:35  nigelhorne
  * Added --noreject flag
  *
952f2560
  * Revision 1.40  2004/01/28 15:55:59  nigelhorne
  * Fixed compilation error with --enable-debug
  *
e576bf42
  * Revision 1.39  2004/01/26 14:12:42  nigelhorne
  * Corrected endian problem (ntohs instead of htons)
  *
44d08756
  * Revision 1.38  2004/01/25 14:23:51  nigelhorne
  * Support multiple clamd servers
  *
0e244102
  * Revision 1.37  2004/01/24 18:09:39  nigelhorne
  * Allow clamd server name as well as IPaddress in -s option
  *
fa2c672a
  * Revision 1.36  2004/01/12 15:30:53  nigelhorne
  * FixStaleSocket no longer complains on ENOENT
  *
fe3d8be8
  * Revision 1.35  2004/01/10 16:22:14  nigelhorne
  * Added OpenBSD instructions and --signature-file
  *
2a2f7ff3
  * Revision 1.34  2003/12/31 14:46:35  nigelhorne
  * Include the sendmail queue ID in the log
  *
51b03ecb
  * Revision 1.33  2003/12/27 17:28:56  nigelhorne
  * Moved --sign data to private area
  *
fa9628f2
  * Revision 1.32  2003/12/22 14:05:31  nigelhorne
  * Added --sign option
  *
8ea7fdd0
  * Revision 1.31  2003/12/13 16:43:21  nigelhorne
  * Upissue
  *
98135801
  * Revision 1.30  2003/12/12 13:42:47  nigelhorne
  * alls to clamfi_cleanup were missing
  *
66ff992e
  * Revision 1.29  2003/12/10 12:00:39  nigelhorne
  * Timeout on waiting for data from clamd
  *
c9af1776
  * Revision 1.28  2003/12/09 09:22:14  nigelhorne
  * Use the location of sendmail discovered by configure
  *
332e6334
  * Revision 1.27  2003/12/05 19:14:07  nigelhorne
  * Set umask; handle unescaped From in mailboxes
  *
2defd014
  * Revision 1.26  2003/12/02 06:37:26  nigelhorne
  * Use setsid if setpgrp not present
  *
668c7570
  * Revision 1.25  2003/11/30 06:12:06  nigelhorne
  * Added --quarantine-dir option
  *
b312f172
  * Revision 1.24  2003/11/29 11:51:19  nigelhorne
  * Fix problem of possible confused pointers if large number of recipients given
  *
2f5f8390
  * Revision 1.23  2003/11/25 05:56:43  nigelhorne
  * Handle empty hostname or hostaddr
  *
3aa15b4c
  * Revision 1.22  2003/11/24 04:48:44  nigelhorne
  * Support AllowSupplementaryGroups
  *
e004f1c5
  * Revision 1.21  2003/11/22 11:47:45  nigelhorne
bd547be2
  * Drop root priviliges and support quarantine
e004f1c5
  *
dad136d5
  * Revision 1.20  2003/11/19 16:32:22  nigelhorne
  * Close cmdSocket earlier
  *
4d0bd1f7
  * Revision 1.19  2003/11/17 04:48:30  nigelhorne
  * Up issue to version 0.65
  *
d3f8fcf7
  * Revision 1.18  2003/11/11 08:19:20  nigelhorne
  * Handle % characters in e-mail addresses
  *
88f28d8c
  * Revision 1.17  2003/11/05 15:41:11  nigelhorne
  * Tidyup pthread_cond_timewait call
  *
68d5a5f3
  * Revision 1.16  2003/10/31 13:33:40  nigelhorne
  * Added dont scan on error flag
  *
198d714a
  * Revision 1.15  2003/10/22 19:44:01  nigelhorne
  * more calls to pthread_cond_broadcast
  *
a4371160
  * Revision 1.14  2003/10/12 08:37:21  nigelhorne
  * Uses VERSION command to get version information
  *
9148ec6d
  * Revision 1.13  2003/10/11 15:42:15  nigelhorne
  * Don't call clamdscan
  *
db035545
  * Revision 1.12  2003/10/05 17:30:04  nigelhorne
  * Only fix old socket when FixStaleSocket is set
  *
429f2e92
  * Revision 1.11  2003/10/05 13:57:47  nigelhorne
  * Fixed handling of MaxThreads
  *
6909adb8
  * Revision 1.10  2003/10/03 11:54:53  nigelhorne
  * Added white list of recipients
  *
b9d3b885
  * Revision 1.9  2003/09/30 11:53:55  nigelhorne
  * clamfi_envfrom was returning EX_TEMPFAIL in some places rather than SMFIS_TEMPFAIL
  *
9e7b0c12
  * Revision 1.8  2003/09/29 06:20:17  nigelhorne
  * max_children now overrides MaxThreads
  *
1c8d6635
  * Revision 1.7  2003/09/29 06:07:49  nigelhorne
  * Ensure remoteIP is set before usage
  *
2cd8b9d4
  * Revision 1.6  2003/09/28 16:37:23  nigelhorne
  * Added -f flag use MaxThreads if --max-children not set
e3aaff8e
  */
e368b3dd
 static	char	const	rcsid[] = "$Id: clamav-milter.c,v 1.121 2004/08/26 10:22:00 nigelhorne Exp $";
e3aaff8e
 
e368b3dd
 #define	CM_VERSION	"0.75m"
e3aaff8e
 
 /*#define	CONFDIR	"/usr/local/etc"*/
 
7908713f
 #if HAVE_CONFIG_H
 #include "clamav-config.h"
 #endif
 
e3aaff8e
 #include "defaults.h"
86b3e542
 #include "cfgparser.h"
e3aaff8e
 #include "../target.h"
44d08756
 #include "str.h"
1fcdb893
 #include "../libclamav/others.h"
20bca05f
 #include "../libclamav/strrcpy.h"
1fcdb893
 #include "clamav.h"
e3aaff8e
 
 #ifndef	CL_DEBUG
 #define	NDEBUG
 #endif
 
 #include <stdio.h>
 #include <sysexits.h>
332e6334
 #include <sys/types.h>
 #include <sys/stat.h>
e3aaff8e
 #include <syslog.h>
 #include <unistd.h>
 #include <stdlib.h>
 #include <string.h>
 #include <sys/wait.h>
 #include <assert.h>
1e2aaf5e
 #include <netinet/in.h>
e3aaff8e
 #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 <signal.h>
01ab0124
 #include <regex.h>
 #include <fcntl.h>
e004f1c5
 #include <pwd.h>
3aa15b4c
 #include <grp.h>
0e244102
 #include <netdb.h>
e3aaff8e
 
b2fb75ea
 #ifdef	WITH_TCPWRAP
 #include <tcpd.h>
f9c88a98
 
 int	allow_severity = LOG_DEBUG;
e84162a4
 int	deny_severity = LOG_NOTICE;
f9c88a98
 
b2fb75ea
 #endif
 
44d08756
 #if defined(CL_DEBUG) && defined(C_LINUX)
 #include <sys/resource.h>
 #endif
 
e3aaff8e
 #define _GNU_SOURCE
049a18b9
 #include "getopt.h"
e3aaff8e
 
c9af1776
 #ifndef	SENDMAIL_BIN
 #define	SENDMAIL_BIN	"/usr/lib/sendmail"
 #endif
 
b2fb75ea
 #ifndef HAVE_IN_PORT_T
 typedef	unsigned short	in_port_t;
 #endif
 
e3aaff8e
 /*
  * TODO: optional: xmessage on console when virus stopped (SNMP would be real nice!)
3aa15b4c
  *	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
e3aaff8e
  * TODO: build with libclamav.so rather than libclamav.a
00727a0e
  * TODO: Support LogTime and Logfile from the conf file
7908713f
  * 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.
3ce543c7
  * TODO: Encrypt mails sent to clamd to stop sniffers
502c8234
  * TODO: Test with IPv6
e3aaff8e
  */
 
9e1e77b9
 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;
 
e3aaff8e
 /*
eef726b0
  * Local addresses are those not scanned if --local is not set
  * 127.0.0.0 is not in this table since that's goverend by --outgoing
  * Andy Fiddaman <clam@fiddaman.net> added 69.254.0.0/16
  *	(Microsoft default DHCP)
  *
  * TODO: read this table in from a file (clamav.conf?)
  */
 #define PACKADDR(a, b, c, d) (((a) << 24) | ((b) << 16) | ((c) << 8) | (d))
 #define MAKEMASK(bits)       (0xffffffff << (bits))
 
 static const struct cidr_net {
 	uint32_t	base;
 	uint32_t	mask;
 } localNets[] = {
 	/*{ PACKADDR(127,   0,   0,   0), MAKEMASK(24) },	/*   127.0.0.0/24 */
 	{ PACKADDR(192, 168,   0,   0), MAKEMASK(16) },	/* 192.168.0.0/16 */
 	{ PACKADDR( 10,   0,   0,   0), MAKEMASK(24) },	/*    10.0.0.0/24 */
 	{ PACKADDR(172,  16,   0,   0), MAKEMASK(20) },	/*  172.16.0.0/20 */
 	{ PACKADDR(169,  254,  0,   0), MAKEMASK(16) },	/* 169.254.0.0/16 */
 	{ 0, 0 }
 };
 
 /*
e3aaff8e
  * 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 */
668c7570
 	char	*filename;	/* Where to store the message in quarantine */
51b03ecb
 	u_char	*body;		/* body of the message if Sflag is set */
 	size_t	bodyLen;	/* number of bytes in body */
9e1e77b9
 	header_list_t headers;	/* Message headers */
bb09a2f7
 	long	numBytes;	/* Number of bytes sent so far */
502c8234
 	char	*received;	/* keep track of received from */
b5c80361
 	const	char	*rejectCode;	/* 550 or 554? */
ba2dfeb2
 	char	*messageID;	/* sendmailID */
b5c80361
 	int	discard;	/*
 				 * looks like the remote end is playing ping
 				 * pong with us
 				 */
0abc0a57
 	int	serverNumber;	/* Index into serverIPs */
e3aaff8e
 };
 
44d08756
 static	int		pingServer(int serverNumber);
 static	int		findServer(void);
e3aaff8e
 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);
c54d7329
 static	void		clamfi_free(struct privdata *privdata);
7d81c053
 static	int		clamfi_send(struct privdata *privdata, size_t len, const char *format, ...);
fe3d8be8
 static	int		clamd_recv(int sock, char *buf, size_t len);
 static	off_t		updateSigFile(void);
9e1e77b9
 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);
f7ab4278
 static	int	connect2clamd(struct privdata *privdata);
b5648b5a
 static	void	checkClamd(void);
a0c42dae
 static	int	sendtemplate(SMFICTX *ctx, const char *filename, FILE *sendmail, const char *virusname);
b475d5ea
 static	int	qfile(struct privdata *privdata, const char *virusname);
459b60af
 static	void	setsubject(SMFICTX *ctx, const char *virusname);
734ea355
 static	int	clamfi_gethostbyname(const char *hostname, struct hostent *hp, char *buf, size_t len);
eef726b0
 static	int	isLocalAddr(in_addr_t addr);
e3aaff8e
 
a4371160
 static	char	clamav_version[128];
2cd8b9d4
 static	int	fflag = 0;	/* force a scan, whatever */
e3aaff8e
 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
 				 */
7a9b0f05
 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
 				 */
fa9628f2
 static	int	Sflag = 0;	/*
 				 * Add a signature to each message that
 				 * has been scanned
 				 */
fe3d8be8
 static	const	char	*sigFilename;	/*
 				 * File where the scanned message signature
 				 * can be found
 				 */
668c7570
 static	char	*quarantine;	/*
e004f1c5
 				 * If a virus is found in an email redirect
 				 * it to this account
 				 */
668c7570
 static	char	*quarantine_dir; /*
 				 * Path to store messages before scanning.
 				 * Infected ones will be left there.
 				 */
7418fb74
 static	int	nflag = 0;	/*
 				 * Don't add X-Virus-Scanned to header. Patch
 				 * from Dirk Meyer <dirk.meyer@dinoex.sub.org>
 				 */
3a03d183
 static	int	rejectmail = 1;	/*
 				 * Send a 550 rejection when a virus is
 				 * found
 				 */
9e1e77b9
 static	int	hflag = 0;	/*
 				 * Include original message headers in
 				 * report
 				 */
68d5a5f3
 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>
 				 */
96f3d93b
 static	int	readTimeout = CL_DEFAULT_SCANTIMEOUT; /*
66ff992e
 				 * number of seconds to wait for clamd to
00727a0e
 				 * respond, see ReadTimeout in clamav.conf
66ff992e
 				 */
bb09a2f7
 static	long	streamMaxLength = -1;	/* StreamMaxLength from clamav.conf */
fdc6066a
 static	int	logClean = 1;	/*
 				 * Add clean items to the log file
 				 */
fe3d8be8
 static	char	*signature = "-- \nScanned by ClamAv - http://www.clamav.net\n";
 static	time_t	signatureStamp;
3ce543c7
 static	char	*templatefile;	/* e-mail to be sent when virus detected */
e3aaff8e
 
 #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;
4a944387
 static	int	child_timeout = 60;	/* number of seconds to wait for
 					 * a child to die. Set to 0 to
 					 * wait forever
 					 */
459b60af
 static	int	dont_wait = 0;	/*
 				 * If 1 send retry later to the remote end
 				 * if max_chilren is exceeded, otherwise we
 				 * wait for the number to go down
 				 */
 static	int	advisory = 0;	/*
 				 * Run clamav-milter in advisory mode - viruses
 				 * are flagged rather than deleted. Incompatible
 				 * with quarantine options
 				 */
ff46437f
 static	short	use_syslog = 0;
b5648b5a
 static	const	char	*pidFile;
e3aaff8e
 static	int	logVerbose = 0;
 static	struct	cfgstruct	*copt;
664f9ff6
 static	const	char	*localSocket;	/* milter->clamd comms */
 static	in_port_t	tcpSocket;	/* milter->clamd comms */
 static	char	*port = NULL;	/* sendmail->milter comms */
44d08756
 static	const	char	*serverHostNames = "127.0.0.1";
 static	long	*serverIPs;	/* IPv4 only */
 static	int	numServers;	/* numer of elements in serverIPs */
049a18b9
 static	const	char	*postmaster = "postmaster";
502c8234
 static	const	char	*from = "MAILER-DAEMON";
e3aaff8e
 
3aa15b4c
 /*
ea4465c4
  * NULL terminated whitelist of target ("to") addresses that we do NOT scan
3aa15b4c
  * TODO: read in from a file
aead37b9
  * TODO: add white list of source e-mail addresses that we do NOT scan
7d81c053
  * TODO: items in the list should be regular expressions
3aa15b4c
  */
6909adb8
 static	const	char	*ignoredEmailAddresses[] = {
 	/*"Mailer-Daemon@bandsman.co.uk",
 	"postmaster@bandsman.co.uk",*/
 	NULL
 };
 
e3aaff8e
 static void
 help(void)
 {
 	printf("\n\tclamav-milter version %s\n", CM_VERSION);
3ce543c7
 	puts("\tCopyright (C) 2004 Nigel Horne <njh@despammed.com>\n");
e3aaff8e
 
459b60af
 	puts("\t--advisory\t\t-A\tFlag viruses rather than deleting them.");
e3aaff8e
 	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.");
fdc6066a
 	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.");
e004f1c5
 	puts("\t--dont-scan-on-error\t-d\tPass e-mails through unscanned if a system error occurs.");
459b60af
 	puts("\t--dont-wait\t\t\tAsk remote end to resend if max-children exceeded.");
502c8234
 	puts("\t--from=EMAIL\t\t-a EMAIL\tError messages come from here.");
e004f1c5
 	puts("\t--force-scan\t\t-f\tForce scan all messages (overrides (-o and -l).");
e3aaff8e
 	puts("\t--help\t\t\t-h\tThis message.");
9e1e77b9
 	puts("\t--headers\t\t-H\tInclude original message headers in the report.");
e3aaff8e
 	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.");
3a03d183
 	puts("\t--noreject\t\t-N\tDon't reject viruses, silently throw them away.");
23248fbc
 	puts("\t--noxheader\t\t-n\tSuppress X-Virus-Scanned/X-Virus-Status headers.");
e84cbd98
 	puts("\t--pidfile=FILE\t\t-i FILE\tLocation of pidfile.");
3aa15b4c
 	puts("\t--postmaster\t\t-p EMAIL\tPostmaster address [default=postmaster].");
e004f1c5
 	puts("\t--postmaster-only\t-P\tSend warnings only to the postmaster.");
7a9b0f05
 	puts("\t--quiet\t\t\t-q\tDon't send e-mail notifications of interceptions.");
3aa15b4c
 	puts("\t--quarantine=USER\t-Q EMAIL\tQuanrantine e-mail account.");
668c7570
 	puts("\t--quarantine-dir=DIR\t-U DIR\tDirectory to store infected emails.");
fdc6066a
 	puts("\t--server=SERVER\t\t-s SERVER\tHostname/IP address of server(s) running clamd (when using TCPsocket).");
fe3d8be8
 	puts("\t--sign\t\t\t-S\tAdd a hard-coded signature to each scanned message.");
502c8234
 	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.");
459b60af
 	puts("\t--timeout=SECS\t\t-T SECS\tTimeout waiting to childen to die.");
e3aaff8e
 	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
ff46437f
 	puts("\nFor more information type \"man clamav-milter\".");
 	puts("Report bugs to bugs@clamav.net.");
e3aaff8e
 }
 
 int
 main(int argc, char **argv)
 {
 	extern char *optarg;
 	const char *cfgfile = CL_DEFAULT_CFG;
 	struct cfgstruct *cpt;
668c7570
 	struct passwd *user;
e84cbd98
 	const char *pidfile = NULL;
e3aaff8e
 	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 */
 	};
 
44d08756
 #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
a4371160
 	/*
 	 * Temporarily enter guessed value into clamav_version, will
 	 * be overwritten later by the value returned by clamd
 	 */
9148ec6d
 	snprintf(clamav_version, sizeof(clamav_version),
 		"ClamAV version %s, clamav-milter version %s",
 		VERSION, CM_VERSION);
 
e3aaff8e
 	for(;;) {
 		int opt_index = 0;
 #ifdef	CL_DEBUG
459b60af
 		const char *args = "a:Abc:CDfF:lm:nNop:PqQ:dhHs:St:T:U:Vx:";
e3aaff8e
 #else
459b60af
 		const char *args = "a:Abc:CDfF:lm:nNop:PqQ:dhHs:St:T:U:V";
e3aaff8e
 #endif
e004f1c5
 
e3aaff8e
 		static struct option long_options[] = {
 			{
08992bbd
 				"from", 1, NULL, 'a'
502c8234
 			},
 			{
459b60af
 				"advisory", 0, NULL, 'A'
 			},
 			{
e3aaff8e
 				"bounce", 0, NULL, 'b'
 			},
 			{
 				"config-file", 1, NULL, 'c'
 			},
 			{
fdc6066a
 				"dont-log-clean", 0, NULL, 'C'
 			},
 			{
68d5a5f3
 				"dont-scan-on-error", 0, NULL, 'd'
 			},
 			{
459b60af
 				"dont-wait", 0, NULL, 'w'
 			},
 			{
44d08756
 				"debug", 0, NULL, 'D'
 			},
 			{
668c7570
 				"force-scan", 0, NULL, 'f'
2cd8b9d4
 			},
 			{
5b6bb93b
 				"headers", 0, NULL, 'H'
9e1e77b9
 			},
 			{
e3aaff8e
 				"help", 0, NULL, 'h'
 			},
 			{
e84cbd98
 				"pidfile", 1, NULL, 'i'
 			},
 			{
e3aaff8e
 				"local", 0, NULL, 'l'
 			},
 			{
3a03d183
 				"noreject", 0, NULL, 'N'
 			},
 			{
7418fb74
 				"noxheader", 0, NULL, 'n'
 			},
 			{
e3aaff8e
 				"outgoing", 0, NULL, 'o'
 			},
 			{
3aa15b4c
 				"postmaster", 1, NULL, 'p'
049a18b9
 			},
 			{
7a9b0f05
 				"postmaster-only", 0, NULL, 'P',
 			},
 			{
 				"quiet", 0, NULL, 'q'
 			},
 			{
e004f1c5
 				"quarantine", 1, NULL, 'Q',
 			},
 			{
668c7570
 				"quarantine-dir", 1, NULL, 'U',
 			},
 			{
e3aaff8e
 				"max-children", 1, NULL, 'm'
 			},
 			{
 				"server", 1, NULL, 's'
 			},
 			{
fe3d8be8
 				"sign", 0, NULL, 'S'
 			},
 			{
 				"signature-file", 1, NULL, 'F'
fa9628f2
 			},
 			{
3ce543c7
 				"template-file", 1, NULL, 't'
 			},
 			{
4a944387
 				"timeout", 1, NULL, 'T'
 			},
 			{
e3aaff8e
 				"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) {
502c8234
 			case 'a':	/* e-mail errors from here */
 				from = optarg;
 				break;
459b60af
 			case 'A':
 				advisory++;
 				smfilter.xxfi_flags |= SMFIF_CHGHDRS;
 				break;
e3aaff8e
 			case 'b':	/* bounce worms/viruses */
 				bflag++;
 				break;
 			case 'c':	/* where is clamav.conf? */
 				cfgfile = optarg;
 				break;
fdc6066a
 			case 'C':	/* dont log clean */
 				logClean = 0;
 				break;
68d5a5f3
 			case 'd':	/* don't scan on error */
 				cl_error = SMFIS_ACCEPT;
 				break;
44d08756
 			case 'D':	/* enable debug messages */
 				cl_debug();
 				break;
2cd8b9d4
 			case 'f':	/* force the scan */
 				fflag++;
 				break;
e3aaff8e
 			case 'h':
 				help();
 				return EX_OK;
9e1e77b9
 			case 'H':
 				hflag++;
 				break;
e84cbd98
 			case 'i':	/* pidfile */
 				pidfile = optarg;
 				break;
e3aaff8e
 			case 'l':	/* scan mail from the lan */
 				lflag++;
 				break;
049a18b9
 			case 'm':	/* maximum number of children */
 				max_children = atoi(optarg);
 				break;
7418fb74
 			case 'n':	/* don't add X-Virus-Scanned */
 				nflag++;
e004f1c5
 				smfilter.xxfi_flags &= ~SMFIF_ADDHDRS;
7418fb74
 				break;
3a03d183
 			case 'N':	/* Do we reject mail or silently drop it */
 				rejectmail = 0;
 				break;
e3aaff8e
 			case 'o':	/* scan outgoing mail */
 				oflag++;
 				break;
049a18b9
 			case 'p':	/* postmaster e-mail address */
 				postmaster = optarg;
e3aaff8e
 				break;
7a9b0f05
 			case 'P':	/* postmaster only */
 				pflag++;
 				break;
 			case 'q':	/* send NO notification email */
 				qflag++;
 				break;
e004f1c5
 			case 'Q':	/* quarantine e-mail address */
 				quarantine = optarg;
 				smfilter.xxfi_flags |= SMFIF_CHGHDRS|SMFIF_ADDRCPT|SMFIF_DELRCPT;
 				break;
e3aaff8e
 			case 's':	/* server running clamd */
44d08756
 				serverHostNames = optarg;
e3aaff8e
 				break;
fe3d8be8
 			case 'F':	/* signature file */
 				sigFilename = optarg;
 				signature = NULL;
 				/* fall through */
fa9628f2
 			case 'S':	/* sign */
 				smfilter.xxfi_flags |= SMFIF_CHGBODY;
 				Sflag++;
 				break;
3ce543c7
 			case 't':	/* e-mail template file */
 				templatefile = optarg;
 				break;
4a944387
 			case 'T':	/* time to wait for child to die */
 				child_timeout = atoi(optarg);
 				break;
668c7570
 			case 'U':	/* quarantine path */
 				quarantine_dir = optarg;
 				break;
e3aaff8e
 			case 'V':
9148ec6d
 				puts(clamav_version);
e3aaff8e
 				return EX_OK;
459b60af
 			case 'w':
 				dont_wait++;
 				break;
e3aaff8e
 #ifdef	CL_DEBUG
 			case 'x':
 				debug_level = atoi(optarg);
 				break;
 #endif
 			default:
 #ifdef	CL_DEBUG
44d08756
 				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]);
e3aaff8e
 #else
44d08756
 				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]);
e3aaff8e
 #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
 	 */
cc71d7c2
 	if((copt = parsecfg(cfgfile, 1)) == NULL) {
e3aaff8e
 		fprintf(stderr, "%s: Can't parse the config file %s\n",
 			argv[0], cfgfile);
 		return EX_CONFIG;
 	}
 
3aa15b4c
 	/*
 	 * 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;
 			}
e004f1c5
 
03d91eec
 			if(cfgopt(copt, "AllowSupplementaryGroups")) {
 #ifdef HAVE_INITGROUPS
 				if(initgroups(cpt->strarg, user->pw_gid) < 0) {
 					perror(cpt->strarg);
 					return EX_CONFIG;
 				}
 #else
 				fprintf(stderr, "%s: AllowSupplementaryGroups: initgroups not supported.\n",
 					argv[0]);
 				return EX_CONFIG;
 #endif
 			} else {
 #ifdef	HAVE_SETGROUPS
 				if(setgroups(1, &user->pw_gid) < 0) {
 					perror(cpt->strarg);
 					return EX_CONFIG;
 				}
 #endif
 			}
3aa15b4c
 
 			setgid(user->pw_gid);
ba2dfeb2
 			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);
3aa15b4c
 		} else
aead37b9
 			fprintf(stderr, "%s: running as root is not recommended (check \"User\" in clamav.conf)\n", argv[0]);
3aa15b4c
 	}
459b60af
 	if(advisory && quarantine) {
 		fprintf(stderr, "%s: Advisory mode doesn't work with quarantine mode\n", argv[0]);
 		return EX_USAGE;
 	}
bd547be2
 	if(quarantine_dir) {
 		struct stat statb;
 
459b60af
 		if(advisory) {
 			fprintf(stderr, "%s: Advisory mode doesn't work with quarantine directories\n", argv[0]);
 			return EX_USAGE;
 		}
bd547be2
 		if(access(quarantine_dir, W_OK) < 0) {
 			perror(quarantine_dir);
459b60af
 			return EX_USAGE;
bd547be2
 		}
 		if(stat(quarantine_dir, &statb) < 0) {
 			perror(quarantine_dir);
459b60af
 			return EX_USAGE;
bd547be2
 		}
 		/*
 		 * 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;
 		}
668c7570
 	}
e004f1c5
 
fe3d8be8
 	if(sigFilename && !updateSigFile())
 		return EX_USAGE;
 
0c933aca
 	if(templatefile && (access(templatefile, R_OK) < 0)) {
 		perror(templatefile);
 		return EX_CONFIG;
3ce543c7
 	}
 
e3aaff8e
 	if(!cfgopt(copt, "StreamSaveToDisk")) {
 		fprintf(stderr, "%s: StreamSavetoDisk not enabled in %s\n",
 			argv[0], cfgfile);
 		return EX_CONFIG;
 	}
 
 	if(!cfgopt(copt, "ScanMail")) {
96f3d93b
 		/*
 		 * In fact ScanMail isn't needed if this machine doesn't run
 		 * clamd.
 		 */
e3aaff8e
 		fprintf(stderr, "%s: ScanMail not enabled in %s\n",
 			argv[0], cfgfile);
 		return EX_CONFIG;
 	}
 
 	/*
2cd8b9d4
 	 * 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
 	 */
9e7b0c12
 	if((max_children == 0) && ((cpt = cfgopt(copt, "MaxThreads")) != NULL))
429f2e92
 		max_children = cpt->numarg;
2cd8b9d4
 
00727a0e
 	if((cpt = cfgopt(copt, "ReadTimeout")) != NULL) {
96f3d93b
 		readTimeout = cpt->numarg;
66ff992e
 
96f3d93b
 		if(readTimeout < 0) {
00727a0e
 			fprintf(stderr, "%s: ReadTimeout must not be negative in %s\n",
66ff992e
 				argv[0], cfgfile);
96f3d93b
 			return EX_CONFIG;
66ff992e
 		}
 	}
96f3d93b
 	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;
 		}
bb09a2f7
 		streamMaxLength = (long)cpt->numarg;
96f3d93b
 	}
2cd8b9d4
 	/*
e3aaff8e
 	 * Get the outgoing socket details - the way to talk to clamd
 	 */
a4371160
 	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;
 		}
e3aaff8e
 		/*
 		 * TODO: check --server hasn't been set
 		 */
 		localSocket = cpt->strarg;
44d08756
 		if(!pingServer(-1)) {
a4371160
 			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;
 		}
ea4465c4
 		/*if(quarantine_dir == NULL)
 			fprintf(stderr, "When using Localsocket in %s\nyou may improve performance if you use the --quarantine-dir option\n", cfgfile);*/
00727a0e
 
e84162a4
 		umask(077);
44d08756
 
 		serverIPs = (long *)cli_malloc(sizeof(long));
 		serverIPs[0] = inet_addr("127.0.0.1");
a4371160
 	} else if((cpt = cfgopt(copt, "TCPSocket")) != NULL) {
736c8d91
 		int i, activeServers;
44d08756
 
e3aaff8e
 		/*
 		 * TCPSocket is in fact a port number not a full socket
 		 */
668c7570
 		if(quarantine_dir) {
 			fprintf(stderr, "%s: --quarantine-dir not supported for remote scanning - use --quarantine\n", argv[0]);
 			return EX_CONFIG;
 		}
 
5b6bb93b
 		tcpSocket = (in_port_t)cpt->numarg;
44d08756
 
0e244102
 		/*
44d08756
 		 * cli_strtok's fieldno counts from 0
0e244102
 		 */
44d08756
 		for(;;) {
81bdf63b
 			char *hostname = cli_strtok(serverHostNames, numServers, ":");
44d08756
 			if(hostname == NULL)
 				break;
 			numServers++;
 			free(hostname);
0e244102
 		}
 
44d08756
 		cli_dbgmsg("numServers: %d\n", numServers);
668c7570
 
44d08756
 		serverIPs = (long *)cli_malloc(numServers * sizeof(long));
736c8d91
 		activeServers = 0;
44d08756
 
 		for(i = 0; i < numServers; i++) {
81bdf63b
 			char *hostname = cli_strtok(serverHostNames, i, ":");
44d08756
 
 			/*
 			 * 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]));
 			}
 
736c8d91
 			if(pingServer(i))
 				activeServers++;
 			else {
1e2aaf5e
 				cli_warnmsg("Can't talk to clamd server %s on port %d\n",
44d08756
 					hostname, tcpSocket);
 			}
 			free(hostname);
e3aaff8e
 		}
736c8d91
 		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;
 		}
e3aaff8e
 	} else {
 		fprintf(stderr, "%s: You must select server type (local/TCP) in %s\n",
 			argv[0], cfgfile);
 		return EX_CONFIG;
 	}
 
a4371160
 	if(!cfgopt(copt, "Foreground")) {
fe3d8be8
 #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
 
e3aaff8e
 		switch(fork()) {
 			case -1:
 				perror("fork");
 				return EX_TEMPFAIL;
 			case 0:	/* child */
 				break;
 			default:	/* parent */
 				return EX_OK;
 		}
a4371160
 		close(0);
b5c80361
 		open("/dev/null", O_RDONLY);
 
 #ifndef	CL_DEBUG
a4371160
 		close(1);
 		close(2);
144bc6cf
 		if((open("/dev/console", O_WRONLY) == 1) ||
 		   (open("/dev/null", O_WRONLY) == 1))
a4371160
 			dup(1);
b5c80361
 #endif
 
2defd014
 #ifdef HAVE_SETPGRP
 #ifdef SETPGRP_VOID
dad136d5
 		setpgrp();
2defd014
 #else
 		setpgrp(0,0);
 #endif
 #else
 #ifdef HAVE_SETSID
 		 setsid();
 #endif
 #endif
a4371160
 	}
e3aaff8e
 
b5648b5a
 	if((cpt = cfgopt(copt, "PidFile")) != NULL)
 		pidFile = cpt->strarg;
 
e3aaff8e
 	if(cfgopt(copt, "LogSyslog")) {
ba2dfeb2
 		if(cfgopt(copt, "LogVerbose"))
 			logVerbose = 1;
 		use_syslog = 1;
 
e3aaff8e
 		openlog("clamav-milter", LOG_CONS|LOG_PID, LOG_MAIL);
ba2dfeb2
 		if(logVerbose)
 			syslog(LOG_INFO, "Starting: %s", clamav_version);
 		else
226d027a
 			syslog(LOG_INFO, "%s", clamav_version);
e3aaff8e
 #ifdef	CL_DEBUG
 		if(debug_level > 0)
 			syslog(LOG_DEBUG, "Debugging is on");
 #endif
7a9b0f05
 	} else {
 		if(qflag)
ba2dfeb2
 			fprintf(stderr, "%s: (-q && !LogSyslog): warning - all interception message methods are off\n",
7a9b0f05
 				argv[0]);
e3aaff8e
 		use_syslog = 0;
7a9b0f05
 	}
e3aaff8e
 
e84cbd98
 	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);
 	}
 
db035545
 	if(cfgopt(copt, "FixStaleSocket")) {
 		/*
 		 * Get the incoming socket details - the way sendmail talks to
 		 * us
 		 *
3aa15b4c
 		 * TODO: There's a security problem here that'll need fixing if
 		 * the User entry of clamav.conf is not used
db035545
 		 */
 		if(strncasecmp(port, "unix:", 5) == 0) {
 			if(unlink(&port[5]) < 0)
fa2c672a
 				if(errno != ENOENT)
 					perror(&port[5]);
db035545
 		} else if(strncasecmp(port, "local:", 6) == 0) {
 			if(unlink(&port[6]) < 0)
fa2c672a
 				if(errno != ENOENT)
 					perror(&port[6]);
db035545
 		}
 	}
e3aaff8e
 
e84162a4
 	if(smfi_setconn(port) == MI_FAILURE) {
 		fprintf(stderr, "%s: smfi_setconn failed\n",
 			argv[0]);
 		return EX_SOFTWARE;
 	}
 
e3aaff8e
 	if(smfi_register(smfilter) == MI_FAILURE) {
f9c88a98
 		cli_errmsg("smfi_register failure\n");
e3aaff8e
 		return EX_UNAVAILABLE;
 	}
 
 	signal(SIGPIPE, SIG_IGN);
 
ba2dfeb2
 	if(logVerbose)
 		syslog(LOG_INFO, "Started: %s", clamav_version);
 
e3aaff8e
 	return smfi_main();
 }
 
 /*
  * Verify that the server is where we think it is
  * Returns true or false
44d08756
  *
736c8d91
  * serverNumber counts from 0, but is only used for TCPSocket
e3aaff8e
  */
 static int
44d08756
 pingServer(int serverNumber)
e3aaff8e
 {
a4371160
 	char *ptr;
e3aaff8e
 	int sock, nbytes;
a4371160
 	char buf[128];
e3aaff8e
 
a4371160
 	if(localSocket) {
 		struct sockaddr_un server;
e3aaff8e
 
a4371160
 		memset((char *)&server, 0, sizeof(struct sockaddr_un));
 		server.sun_family = AF_UNIX;
658f19f8
 		strncpy(server.sun_path, localSocket, sizeof(server.sun_path));
a4371160
 
 		if((sock = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
 			perror("socket");
 			return 0;
 		}
ecaaaf05
 		checkClamd();
a4371160
 		if(connect(sock, (struct sockaddr *)&server, sizeof(struct sockaddr_un)) < 0) {
 			perror(localSocket);
f7ab4278
 			close(sock);
a4371160
 			return 0;
 		}
 	} else {
 		struct sockaddr_in server;
 
 		memset((char *)&server, 0, sizeof(struct sockaddr_in));
 		server.sin_family = AF_INET;
5b6bb93b
 		server.sin_port = (in_port_t)htons(tcpSocket);
 
952f2560
 		assert(serverIPs != NULL);
44d08756
 		assert(serverIPs[0] != -1L);
0e244102
 
44d08756
 		server.sin_addr.s_addr = serverIPs[serverNumber];
a4371160
 
 		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");
00727a0e
 			close(sock);
a4371160
 			return 0;
 		}
e3aaff8e
 	}
a4371160
 
 	/*
 	 * 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) {
e3aaff8e
 		perror("send");
 		close(sock);
 		return 0;
 	}
 
 	shutdown(sock, SHUT_WR);
 
66ff992e
 	nbytes = clamd_recv(sock, buf, sizeof(buf));
e3aaff8e
 
 	close(sock);
 
 	if(nbytes < 0) {
 		perror("recv");
 		return 0;
 	}
66ff992e
 	if(nbytes == 0)
 		return 0;
 
e3aaff8e
 	buf[nbytes] = '\0';
 
a4371160
 	/* Remove the trailing new line from the reply */
 	if((ptr = strchr(buf, '\n')) != NULL)
 		*ptr = '\0';
 
 	/*
 	 * No real validation is done here
44d08756
 	 *
 	 * TODO: When connecting to more than one server, give a warning
 	 *	if they're running different versions, or if the virus DBs
aead37b9
 	 *	are out of date (say more than a month old)
a4371160
 	 */
 	snprintf(clamav_version, sizeof(clamav_version),
b2fb75ea
 		"%s, clamav-milter version %s",
a4371160
 		buf, CM_VERSION);
e004f1c5
 
a4371160
 	return 1;
e3aaff8e
 }
 
44d08756
 /*
736c8d91
  * 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
44d08756
  *
  * Return value is from 0 - index into serverIPs
736c8d91
  *
  * If the load balancing fails return the first server in the list, not
  * an error, to be on the safe side
44d08756
  */
 static int
 findServer(void)
 {
 	struct sockaddr_in *servers, *server;
1e2aaf5e
 	int *socks, maxsock = 0, i, j;
44d08756
 	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);
 
452e28cb
 	if(max_children > 0)
 		j = n_children - 1;	/* Don't worry about no lock */
 	else
6302a4f6
 		/*
 		 * cli_rndnum returns 0..(max-1) - the max argument is not
 		 * the maximum number you want it to return, it is in fact
 		 * one *more* than the maximum number you want it to return
 		 */
 		j = cli_rndnum(numServers);
1e2aaf5e
 
44d08756
 	for(i = 0, server = servers; i < numServers; i++, server++) {
 		int sock;
 
 		server->sin_family = AF_INET;
5b6bb93b
 		server->sin_port = (in_port_t)htons(tcpSocket);
1e2aaf5e
 		server->sin_addr.s_addr = serverIPs[(i + j) % numServers];
 
 		cli_dbgmsg("findServer: try server %d\n",
 			(i + j) % numServers);
44d08756
 
 		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)) {
1e2aaf5e
 			char *hostname = cli_strtok(serverHostNames, i, ":");
a321a25b
 			cli_warnmsg("Check clamd server %s - it may be down\n", hostname);
44d08756
 			if(use_syslog)
736c8d91
 				syslog(LOG_WARNING,
a321a25b
 					"Check clamd server %s - it may be down",
736c8d91
 					hostname);
f7ab4278
 			close(sock);
1e2aaf5e
 			free(hostname);
 			socks[i] = -1;
44d08756
 			continue;
 		}
 
 		shutdown(sock, SHUT_WR);
 
 		FD_SET(sock, &rfds);
 		if(sock > maxsock)
 			maxsock = sock;
 	}
 
 	free(servers);
 
96f3d93b
 	tv.tv_sec = readTimeout;
44d08756
 	tv.tv_usec = 0;
5b6bb93b
 
e368b3dd
 	if(maxsock == 0)
 		retval = 0;
 	else
 		retval = select(maxsock + 1, &rfds, NULL, NULL, &tv);
 
44d08756
 	if(retval < 0)
 		perror("select");
 
 	for(i = 0; i < numServers; i++)
 		if(socks[i] >= 0)
 			close(socks[i]);
 
 	if(retval == 0) {
e368b3dd
 		static time_t lasttime;
 		time_t thistime, diff;
 		static pthread_mutex_t time_mutex = PTHREAD_MUTEX_INITIALIZER;
 
 		/*
 		 * This is serious, we need to inform someone.
 		 * In the absence of SNMP the best way is by e-mail. We
 		 * don't want to flood so there's a need to restrict to
 		 * no more than say one message every 15 minutes
 		 */
44d08756
 		free(socks);
 		cli_dbgmsg("findServer: No response from any server\n");
 		if(use_syslog)
 			syslog(LOG_WARNING, "findServer: No response from any server");
e368b3dd
 
 		time(&thistime);
 		pthread_mutex_lock(&time_mutex);
 		diff = thistime - lasttime;
 		pthread_mutex_unlock(&time_mutex);
 
 		if(diff >= (time_t)(15 * 60)) {
 			char cmd[128];
 			FILE *sendmail;
 
 			snprintf(cmd, sizeof(cmd) - 1, "%s -t", SENDMAIL_BIN);
 
 			sendmail = popen(cmd, "w");
 
 			if(sendmail) {
 				fprintf(sendmail, "To: %s\n", postmaster);
 				fprintf(sendmail, "From: %s\n", postmaster);
 				fputs("Subject: ClamAV Down\n", sendmail);
 				fputs("Priority: High\n\n", sendmail);
 
 				fputs("This is an automatic message\n\n", sendmail);
 
 				if(numServers == 1)
 					fputs("The clamd program cannot be contacted.\n", sendmail);
 				else
 					fputs("No clamd server can be contacted.\n", sendmail);
 
 				fputs("Emails may not be being scanned, please check your servers.\n", sendmail);
 
 				if(pclose(sendmail) == 0) {
 					pthread_mutex_lock(&time_mutex);
 					time(&lasttime);
 					pthread_mutex_unlock(&time_mutex);
 				}
 			}
 		}
44d08756
 		return 0;
 	} else if(retval < 0) {
 		free(socks);
 		if(use_syslog)
a321a25b
 			syslog(LOG_ERR, "findServer: select failed");
44d08756
 		return 0;
 	}
 
 	for(i = 0; i < numServers; i++)
1e2aaf5e
 		if((socks[i] >= 0) && (FD_ISSET(socks[i], &rfds))) {
226d027a
 			const int s = (i + j) % numServers;
1e2aaf5e
 
44d08756
 			free(socks);
226d027a
 			cli_dbgmsg("findServer: using server %d\n", s);
 			return s;
44d08756
 		}
 
 	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;
 }
 
f7ab4278
 /*
  * Sendmail wants to establish a connection to us
  */
e3aaff8e
 static sfsistat
 clamfi_connect(SMFICTX *ctx, char *hostname, _SOCK_ADDR *hostaddr)
f7ab4278
 {
95df50d1
 #if	defined(HAVE_INET_NTOP) || defined(WITH_TCPWRAP)
f9c88a98
 	char ip[INET_ADDRSTRLEN];	/* IPv4 only */
95df50d1
 #endif
055404a5
 	char *remoteIP;
e3aaff8e
 
0fbdd75a
 	if(ctx == NULL) {
 		if(use_syslog)
 			syslog(LOG_ERR, "clamfi_connect: ctx is null");
 		return cl_error;
 	}
2f5f8390
 	if(hostname == NULL) {
 		if(use_syslog)
 			syslog(LOG_ERR, "clamfi_connect: hostname is null");
 		return cl_error;
 	}
9cbf69cc
 	if((hostaddr == NULL) || (&(((struct sockaddr_in *)(hostaddr))->sin_addr) == NULL))
23248fbc
 		/*
 		 * According to the sendmail API hostaddr is NULL if
 		 * "the type is not supported in the current version". What
0fbdd75a
 		 * the documentation doesn't say is the type of what.
23248fbc
 		 *
ba2dfeb2
 		 * Possibly the input is not a TCP/IP socket e.g. stdin?
23248fbc
 		 */
 		remoteIP = "127.0.0.1";
 	else {
95df50d1
 #ifdef HAVE_INET_NTOP
23248fbc
 		remoteIP = (char *)inet_ntop(AF_INET, &((struct sockaddr_in *)(hostaddr))->sin_addr, ip, sizeof(ip));
95df50d1
 #else
23248fbc
 		remoteIP = inet_ntoa(((struct sockaddr_in *)(hostaddr))->sin_addr);
95df50d1
 #endif
2f5f8390
 
23248fbc
 		if(remoteIP == NULL) {
 			if(use_syslog)
 				syslog(LOG_ERR, "clamfi_connect: remoteIP is null");
 			return cl_error;
 		}
2f5f8390
 	}
1c8d6635
 
01ab0124
 #ifdef	CL_DEBUG
2a2f7ff3
 	if(debug_level >= 4) {
 		if(use_syslog)
 			syslog(LOG_NOTICE, "clamfi_connect: connection from %s [%s]", hostname, remoteIP);
f9c88a98
 		cli_dbgmsg("clamfi_connect: connection from %s [%s]\n", hostname, remoteIP);
2a2f7ff3
 	}
01ab0124
 #endif
e3aaff8e
 
055404a5
 #ifdef	WITH_TCPWRAP
 	/*
 	 * Support /etc/hosts.allow and /etc/hosts.deny
 	 */
1f7a8360
 	if(strncasecmp(port, "inet:", 5) == 0) {
664f9ff6
 		const char *hostmail;
150789eb
 		struct hostent hostent;
734ea355
 		char buf[BUFSIZ];
226d027a
 		static pthread_mutex_t wrap_mutex = PTHREAD_MUTEX_INITIALIZER;
f9c88a98
 
5b6bb93b
 		/*
664f9ff6
 		 * Using TCP/IP for the sendmail->clamav-milter connection
 		 */
 		if((hostmail = smfi_getsymval(ctx, "{if_name}")) == NULL) {
 			if(use_syslog)
734ea355
 				syslog(LOG_ERR, "Can't get sendmail hostname");
144bc6cf
 			return cl_error;
664f9ff6
 		}
734ea355
 		if(clamfi_gethostbyname(hostmail, &hostent, buf, sizeof(buf)) != 0) {
150789eb
 			if(use_syslog)
 				syslog(LOG_WARNING, "Access Denied: Host Unknown (%s)", hostname);
 			return cl_error;
 		}
f9c88a98
 
144bc6cf
 #ifdef HAVE_INET_NTOP
734ea355
 		if(hostent.h_addr &&
 		   (inet_ntop(AF_INET, (struct in_addr *)hostent.h_addr, ip, sizeof(ip)) == NULL)) {
 			perror(hostent.h_name);
226d027a
 			/*strcpy(ip, (char *)inet_ntoa(*(struct in_addr *)hostent.h_addr));*/
ba2dfeb2
 			if(use_syslog)
734ea355
 				syslog(LOG_WARNING, "Access Denied: Can't get IP address for (%s)", hostent.h_name);
ba2dfeb2
 			return cl_error;
 		}
144bc6cf
 #else
734ea355
 		strncpy(ip, (char *)inet_ntoa(*(struct in_addr *)hostent.h_addr), sizeof(ip));
144bc6cf
 #endif
664f9ff6
 
 		/*
 		 * Ask is this is a allowed name or IP number
226d027a
 		 *
 		 * hosts_ctl uses strtok so it is not thread safe, see
 		 * hosts_access(3)
664f9ff6
 		 */
226d027a
 		pthread_mutex_lock(&wrap_mutex);
734ea355
 		if(!hosts_ctl("clamav-milter", hostent.h_name, ip, STRING_UNKNOWN)) {
226d027a
 			pthread_mutex_unlock(&wrap_mutex);
664f9ff6
 			if(use_syslog)
734ea355
 				syslog(LOG_WARNING, "Access Denied for %s[%s]", hostent.h_name, ip);
664f9ff6
 			return SMFIS_TEMPFAIL;
 		}
226d027a
 		pthread_mutex_unlock(&wrap_mutex);
055404a5
 	}
 #endif
 
2cd8b9d4
 	if(fflag)
 		/*
 		 * Patch from "Richard G. Roberto" <rgr@dedlegend.com>
 		 * Always scan whereever the message is from
 		 */
 		return SMFIS_CONTINUE;
 
e3aaff8e
 	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");
5b6bb93b
 			cli_dbgmsg("clamfi_connect: not scanning outgoing messages\n");
e3aaff8e
 #endif
 			return SMFIS_ACCEPT;
 		}
 
eef726b0
 	if((!lflag) && isLocalAddr(inet_addr(remoteIP))) {
e3aaff8e
 #ifdef	CL_DEBUG
eef726b0
 		if(use_syslog)
 			syslog(LOG_DEBUG, "clamfi_connect: not scanning local messages");
 		cli_dbgmsg("clamfi_connect: not scanning outgoing messages\n");
e3aaff8e
 #endif
eef726b0
 		return SMFIS_ACCEPT;
e3aaff8e
 	}
b2fb75ea
 
e3aaff8e
 	return SMFIS_CONTINUE;
 }
 
 static sfsistat
 clamfi_envfrom(SMFICTX *ctx, char **argv)
 {
 	struct privdata *privdata;
 
 	if(logVerbose)
 		syslog(LOG_DEBUG, "clamfi_envfrom: %s", argv[0]);
 
f7ab4278
 	cli_dbgmsg("clamfi_envfrom: %s\n", argv[0]);
e3aaff8e
 
 	if(max_children > 0) {
f7ab4278
 		int rc = 0;
e3aaff8e
 
 		pthread_mutex_lock(&n_children_mutex);
 
88f28d8c
 		/*
 		 * 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) {
e3aaff8e
 			struct timeval now;
 			struct timespec timeout;
 			struct timezone tz;
 
ba2dfeb2
 			if(use_syslog)
 				syslog(LOG_NOTICE,
7e4e3eba
 					((dont_wait) ?
 						"hit max-children limit (%u >= %u)" :
 						"hit max-children limit (%u >= %u): waiting for some to exit"),
ba2dfeb2
 					n_children, max_children);
 
459b60af
 			if(dont_wait) {
 				pthread_mutex_unlock(&n_children_mutex);
e368b3dd
 				smfi_setreply(ctx, "451", "4.3.2", "AV system temporarily overloaded - please try later");
459b60af
 				return SMFIS_TEMPFAIL;
 			}
e3aaff8e
 			/*
4a944387
 			 * Wait for an amount of time for a child to go (default
 			 * 60 seconds).
 			 *
e3aaff8e
 			 * Use pthread_cond_timedwait rather than
 			 * pthread_cond_wait since the sendmail which calls
4a944387
 			 * us will have a timeout that we don't want to exceed,
 			 * stops sendmail getting fidgety.
ba2dfeb2
 			 *
 			 * Patch from Damian Menscher <menscher@uiuc.edu> to
 			 * ensure it wakes up when a child goes away
e3aaff8e
 			 */
4a944387
 			if(child_timeout) {
 				gettimeofday(&now, &tz);
 				timeout.tv_sec = now.tv_sec + child_timeout;
 				timeout.tv_nsec = 0;
 			}
e3aaff8e
 
88f28d8c
 			do
4a944387
 				if(child_timeout == 0)
 					rc = pthread_cond_wait(&n_children_cond, &n_children_mutex);
 				else
 					rc = pthread_cond_timedwait(&n_children_cond, &n_children_mutex, &timeout);
ba2dfeb2
 			while((n_children >= max_children) && (rc != ETIMEDOUT));
e3aaff8e
 		}
 		n_children++;
 
f7ab4278
 		cli_dbgmsg(">n_children = %d\n", n_children);
e3aaff8e
 		pthread_mutex_unlock(&n_children_mutex);
 
4a944387
 		if(child_timeout && (rc == ETIMEDOUT)) {
e3aaff8e
 #ifdef	CL_DEBUG
 			if(use_syslog)
 				syslog(LOG_NOTICE, "Timeout waiting for a child to die");
 #endif
5b6bb93b
 			cli_dbgmsg("Timeout waiting for a child to die\n");
e3aaff8e
 		}
 	}
 
c54d7329
 	privdata = (struct privdata *)cli_calloc(1, sizeof(struct privdata));
502c8234
 	if(privdata == NULL)
08b0add9
 		return cl_error;
502c8234
 
e3aaff8e
 	privdata->dataSocket = -1;	/* 0.4 */
 	privdata->cmdSocket = -1;	/* 0.4 */
 
b5c80361
 	/*
 	 * 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";
 
e3aaff8e
 	privdata->from = strdup(argv[0]);
 
96f3d93b
 	if(hflag)
 		privdata->headers = header_list_new();
c54d7329
 
 	if(smfi_setpriv(ctx, privdata) == MI_SUCCESS)
 		return SMFIS_CONTINUE;
 
 	clamfi_free(privdata);
9e1e77b9
 
c54d7329
 	return cl_error;
e3aaff8e
 }
 
 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]);
 
f7ab4278
 	cli_dbgmsg("clamfi_envrcpt: %s\n", argv[0]);
e3aaff8e
 
 	if(privdata->to == NULL) {
5b6bb93b
 		privdata->to = cli_malloc(sizeof(char *) * 2);
e3aaff8e
 
 		assert(privdata->numTo == 0);
 	} else
8ac80fb8
 		privdata->to = cli_realloc(privdata->to, sizeof(char *) * (privdata->numTo + 2));
e3aaff8e
 
502c8234
 	if(privdata->to == NULL)
08b0add9
 		return cl_error;
502c8234
 
e3aaff8e
 	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)
f7ab4278
 		cli_dbgmsg("clamfi_header: %s: %s\n", headerf, headerv);
e3aaff8e
 	else
5b6bb93b
 		cli_dbgmsg("clamfi_header\n");
e3aaff8e
 #endif
 
b5c80361
 	/*
 	 * The DATA instruction from SMTP (RFC2821) must have been sent
 	 */
 	privdata->rejectCode = "554";
 
f7ab4278
 	if(privdata->dataSocket == -1)
 		/*
 		 * First header - make connection with clamd
 		 */
 		if(!connect2clamd(privdata)) {
 			clamfi_cleanup(ctx);
 			return cl_error;
 		}
 
7d81c053
 	if(clamfi_send(privdata, 0, "%s: %s\n", headerf, headerv) <= 0) {
e3aaff8e
 		clamfi_cleanup(ctx);
68d5a5f3
 		return cl_error;
e3aaff8e
 	}
9e1e77b9
 
 	if(hflag)
5b6bb93b
 		header_list_add(privdata->headers, headerf, headerv);
736c8d91
 	else if((strcasecmp(headerf, "Received") == 0) &&
b5c80361
 		(strncasecmp(headerv, "from ", 5) == 0)) {
736c8d91
 		if(privdata->received)
502c8234
 			free(privdata->received);
 		privdata->received = strdup(headerv);
 	}
 
b5c80361
 	if((strcasecmp(headerf, "Message-ID") == 0) &&
 	   (strncasecmp(headerv, "<MDAEMON", 8) == 0))
 		privdata->discard = 1;
 
e3aaff8e
 	return SMFIS_CONTINUE;
 }
 
b5c80361
 /*
  * At this point DATA will have been received, so we really ought to
  * send 554 back not 550
  */
e3aaff8e
 static sfsistat
 clamfi_eoh(SMFICTX *ctx)
 {
 	struct privdata *privdata = (struct privdata *)smfi_getpriv(ctx);
6909adb8
 	char **to;
e3aaff8e
 
 	if(logVerbose)
 		syslog(LOG_DEBUG, "clamfi_eoh");
 #ifdef	CL_DEBUG
f7ab4278
 	if(debug_level >= 4)
 		cli_dbgmsg("clamfi_eoh\n");
e3aaff8e
 #endif
 
b5c80361
 	/*
 	 * The DATA instruction from SMTP (RFC2821) must have been sent
 	 */
 	privdata->rejectCode = "554";
 
f7ab4278
 	if(privdata->dataSocket == -1)
 		/*
 		 * No headers - make connection with clamd
 		 */
 		if(!connect2clamd(privdata)) {
 			clamfi_cleanup(ctx);
 			return cl_error;
 		}
 
7d81c053
 	if(clamfi_send(privdata, 1, "\n") != 1) {
e3aaff8e
 		clamfi_cleanup(ctx);
68d5a5f3
 		return cl_error;
e3aaff8e
 	}
 
6909adb8
 	/*
 	 * 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)
00727a0e
 		syslog(LOG_NOTICE, "clamfi_eoh: ignoring whitelisted message");
6909adb8
 #ifdef	CL_DEBUG
00727a0e
 	cli_dbgmsg("clamfi_eoh: not scanning outgoing messages\n");
6909adb8
 #endif
 	clamfi_cleanup(ctx);
 
 	return SMFIS_ACCEPT;
e3aaff8e
 }
 
 static sfsistat
 clamfi_body(SMFICTX *ctx, u_char *bodyp, size_t len)
 {
 	struct privdata *privdata = (struct privdata *)smfi_getpriv(ctx);
7d81c053
 	int nbytes;
e3aaff8e
 
 	if(logVerbose)
 		syslog(LOG_DEBUG, "clamfi_envbody: %u bytes", len);
 #ifdef	CL_DEBUG
f7ab4278
 	cli_dbgmsg("clamfi_envbody: %u bytes\n", len);
e3aaff8e
 #endif
 
7d81c053
 	nbytes = clamfi_send(privdata, len, (char *)bodyp);
bb09a2f7
 	if(streamMaxLength > 0L) {
96f3d93b
 		if(privdata->numBytes > streamMaxLength) {
08b0add9
 			if(use_syslog) {
 				const char *sendmailId = smfi_getsymval(ctx, "i");
 				if(sendmailId == NULL)
 					sendmailId = "Unknown";
a321a25b
 				syslog(LOG_NOTICE, "%s: Message more than StreamMaxLength (%ld) bytes - not scanned",
08b0add9
 					sendmailId, streamMaxLength);
 			}
7d81c053
 			if(!nflag)
 				smfi_addheader(ctx, "X-Virus-Status", "Not Scanned - StreamMaxLength exceeded");
 
 			return SMFIS_ACCEPT;	/* clamfi_close will be called */
96f3d93b
 		}
 	}
7d81c053
 	if(nbytes < len) {
96f3d93b
 		clamfi_cleanup(ctx);	/* not needed, but just to be safe */
68d5a5f3
 		return cl_error;
e3aaff8e
 	}
fa9628f2
 	if(Sflag) {
51b03ecb
 		if(privdata->body) {
 			assert(privdata->bodyLen > 0);
b5c80361
 			privdata->body = cli_realloc(privdata->body, privdata->bodyLen + len);
51b03ecb
 			memcpy(&privdata->body[privdata->bodyLen], bodyp, len);
 			privdata->bodyLen += len;
fa9628f2
 		} else {
51b03ecb
 			assert(privdata->bodyLen == 0);
5b6bb93b
 			privdata->body = cli_malloc(len);
51b03ecb
 			memcpy(privdata->body, bodyp, len);
 			privdata->bodyLen = len;
fa9628f2
 		}
 	}
e3aaff8e
 	return SMFIS_CONTINUE;
 }
 
 static sfsistat
 clamfi_eom(SMFICTX *ctx)
 {
 	int rc = SMFIS_CONTINUE;
 	char *ptr;
86b3e542
 	const char *sendmailId;
e3aaff8e
 	struct privdata *privdata = (struct privdata *)smfi_getpriv(ctx);
 	char mess[128];
 
 	if(logVerbose)
 		syslog(LOG_DEBUG, "clamfi_eom");
 #ifdef	CL_DEBUG
5b6bb93b
 	cli_dbgmsg("clamfi_eom\n");
e3aaff8e
 	assert(privdata != NULL);
668c7570
 	assert((privdata->cmdSocket >= 0) || (privdata->filename != NULL));
 	assert(!((privdata->cmdSocket >= 0) && (privdata->filename != NULL)));
e3aaff8e
 	assert(privdata->dataSocket >= 0);
 #endif
 
 	close(privdata->dataSocket);
 	privdata->dataSocket = -1;
 
668c7570
 	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;
658f19f8
 		strncpy(server.sun_path, localSocket, sizeof(server.sun_path));
668c7570
 
 		if((privdata->cmdSocket = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
 			perror("socket");
98135801
 			clamfi_cleanup(ctx);
668c7570
 			return cl_error;
 		}
 		if(connect(privdata->cmdSocket, (struct sockaddr *)&server, sizeof(struct sockaddr_un)) < 0) {
 			perror(localSocket);
98135801
 			clamfi_cleanup(ctx);
668c7570
 			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);
 	}
 
66ff992e
 	if(clamd_recv(privdata->cmdSocket, mess, sizeof(mess)) > 0) {
e3aaff8e
 		if((ptr = strchr(mess, '\n')) != NULL)
 			*ptr = '\0';
 
 		if(logVerbose)
 			syslog(LOG_DEBUG, "clamfi_eom: read %s", mess);
f7ab4278
 		cli_dbgmsg("clamfi_eom: read %s\n", mess);
e3aaff8e
 	} else {
1e2aaf5e
 		/*
 		 * TODO: if more than one host has been specified, try
 		 * another one - setting cl_error to SMFIS_TEMPFAIL helps
 		 * by forcing a retry
 		 */
98135801
 		clamfi_cleanup(ctx);
e3aaff8e
 		syslog(LOG_NOTICE, "clamfi_eom: read nothing from clamd");
 #ifdef	CL_DEBUG
5b6bb93b
 		cli_dbgmsg("clamfi_eom: read nothing from clamd\n");
e3aaff8e
 #endif
66ff992e
 		return cl_error;
e3aaff8e
 	}
 
dad136d5
 	close(privdata->cmdSocket);
 	privdata->cmdSocket = -1;
 
86b3e542
 	sendmailId = smfi_getsymval(ctx, "i");
08b0add9
 	if(sendmailId == NULL)
 		sendmailId = "Unknown";
f7ab4278
 
81bdf63b
 	if(!nflag) {
 		char buf[1024];
 
 		/*
456edb55
 		 * Include the hostname where the scan took place
81bdf63b
 		 */
456edb55
 		if(localSocket) {
 			char hostname[32];
 
734ea355
 			if(gethostname(hostname, sizeof(hostname)) < 0) {
226d027a
 				const char *j = smfi_getsymval(ctx, "{j}");
734ea355
 
226d027a
 				if(j)
 					strncpy(hostname, j,
734ea355
 						sizeof(hostname) - 1);
 				else
 					strcpy(buf, "Error determining host");
 			} else if(strchr(hostname, '.') == NULL) {
 				/*
 				 * Determine fully qualified name
 				 */
 				struct hostent hostent;
 
 				if(clamfi_gethostbyname(hostname, &hostent, buf, sizeof(buf)) == 0)
 					strncpy(hostname, hostent.h_name, sizeof(hostname));
 			}
456edb55
 
0abc0a57
 			snprintf(buf, sizeof(buf) - 1, "%s\n\ton %s",
456edb55
 				clamav_version, hostname);
 		} else {
0abc0a57
 			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");
 		}
81bdf63b
 		smfi_addheader(ctx, "X-Virus-Scanned", buf);
 	}
23248fbc
 
86b3e542
 	if(strstr(mess, "ERROR") != NULL) {
dd2edd28
 		if(strstr(mess, "Size limit reached") != NULL) {
f9f239aa
 			/*
 			 * Clamd has stopped on StreamMaxLength before us
 			 */
 			if(use_syslog)
a321a25b
 				syslog(LOG_NOTICE, "%s: Message more than StreamMaxLength (%ld) bytes - not scanned",
f9f239aa
 					sendmailId, streamMaxLength);
7d81c053
 			if(!nflag)
 				smfi_addheader(ctx, "X-Virus-Status", "Not Scanned - StreamMaxLength exceeded");
0abc0a57
 			clamfi_cleanup(ctx);	/* not needed, but just to be safe */
f9f239aa
 			return SMFIS_ACCEPT;
 		}
7d81c053
 		if(!nflag)
 			smfi_addheader(ctx, "X-Virus-Status", "Not Scanned");
f7ab4278
 
86b3e542
 		cli_warnmsg("%s: %s\n", sendmailId, mess);
e84162a4
 		if(use_syslog)
86b3e542
 			syslog(LOG_ERR, "%s: %s\n", sendmailId, mess);
e84162a4
 		clamfi_cleanup(ctx);
 		return cl_error;
 	}
 
144bc6cf
 	if((ptr = strstr(mess, "FOUND")) == NULL) {
7418fb74
 		if(!nflag)
23248fbc
 			smfi_addheader(ctx, "X-Virus-Status", "Clean");
e3aaff8e
 
fdc6066a
 		if(use_syslog && logClean)
2a2f7ff3
 			/* Include the sendmail queue ID in the log */
 			syslog(LOG_NOTICE, "%s: clean message from %s",
86b3e542
 				sendmailId,
049a18b9
 				(privdata->from) ? privdata->from : "an unknown sender");
fa9628f2
 
51b03ecb
 		if(privdata->body) {
2a2f7ff3
 			/*
 			 * Add a signature that all has been scanned OK
 			 */
fe3d8be8
 			off_t len = updateSigFile();
fa9628f2
 
fe3d8be8
 			if(len) {
 				assert(Sflag != 0);
fa9628f2
 
b5c80361
 				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);
 				}
fe3d8be8
 			}
fa9628f2
 		}
e3aaff8e
 	} else {
6a54127a
 		char reject[1024];
736c8d91
 		char **to, *virusname;
144bc6cf
 
734ea355
 		/*
 		 Remove the "FOUND" word, and the space before it
 		 */
 		*--ptr = '\0';
e3aaff8e
 
736c8d91
 		/* skip over 'stream/filename: ' at the start */
 		if((virusname = strchr(mess, ':')) != NULL)
 			virusname = &virusname[2];
 		else
 			virusname = mess;
 
23248fbc
 		if(!nflag)
 			smfi_addheader(ctx, "X-Virus-Status", "Infected");
 
144bc6cf
 		if(use_syslog) {
 			/*
 			 * Setup err as a list of recipients
 			 */
 			char *err = (char *)cli_malloc(1024);
 			int i;
e3aaff8e
 
144bc6cf
 			if(err == NULL) {
 				clamfi_cleanup(ctx);
 				return cl_error;
 			}
502c8234
 
144bc6cf
 			/*
 			 * 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);
e3aaff8e
 
144bc6cf
 			ptr = strchr(err, '\0');
e3aaff8e
 
144bc6cf
 			i = 1024;
049a18b9
 
144bc6cf
 			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;
b5c80361
 					err = cli_realloc(err, i);
 					if(err == NULL) {
 						clamfi_cleanup(ctx);
 						return cl_error;
 					}
144bc6cf
 					ptr = strchr(err, '\0');
 				}
 				ptr = strrcpy(ptr, " ");
 				ptr = strrcpy(ptr, *to);
e3aaff8e
 			}
144bc6cf
 			(void)strcpy(ptr, "\n");
e3aaff8e
 
2a2f7ff3
 			/* Include the sendmail queue ID in the log */
eef726b0
 			syslog(LOG_NOTICE, "%s: %s %s", sendmailId, mess, err);
e3aaff8e
 #ifdef	CL_DEBUG
144bc6cf
 			cli_dbgmsg("%s\n", err);
e3aaff8e
 #endif
144bc6cf
 			free(err);
 		}
e3aaff8e
 
7a9b0f05
 		if(!qflag) {
c9af1776
 			char cmd[128];
1fcdb893
 			FILE *sendmail;
c9af1776
 
736c8d91
 			/*
 			 * 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
1e2aaf5e
 			 *
aead37b9
 			 * FIXME: there is a race condition here when sendmail
 			 * and clamav-milter run on the same machine. If the
1e2aaf5e
 			 * system is very overloaded this sendmail can
 			 * take a long time to start - and may even fail
 			 * is the LA is > REFUSE_LA. In all the time we're
 			 * taking to start this sendmail, the sendmail that's
 			 * started us may timeout waiting for a response and
 			 * let the virus through (albeit tagged with
 			 * X-Virus-Status: Infected) because we haven't
 			 * sent SMFIS_DISCARD or SMFIS_REJECT
736c8d91
 			 */
 			snprintf(cmd, sizeof(cmd) - 1,
a321a25b
 				(oflag || fflag) ? "%s -t -odq" : "%s -t",
 				SENDMAIL_BIN);
c9af1776
 
 			sendmail = popen(cmd, "w");
 
7a9b0f05
 			if(sendmail) {
502c8234
 				fprintf(sendmail, "From: %s\n", from);
7a9b0f05
 				if(bflag) {
b475d5ea
 					/*
 					 * Handle privdata->from not set,
 					 * "Denis Ustimenko" <den@uzsci.net>
 					 */
 					fprintf(sendmail, "To: %s\n",
 						(privdata->from) ?
 							privdata->from :
 							smfi_getsymval(ctx, "{mail_addr}"));
 
7a9b0f05
 					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);
00727a0e
 				/*
ba2dfeb2
 				 * Auto-submitted is still a draft, keep an
00727a0e
 				 * eye on its format
 				 */
 				fputs("Auto-Submitted: auto-submitted (antivirus notify)\n", sendmail);
ba2dfeb2
 				/* "Sergey Y. Afonin" <asy@kraft-s.ru> */
 				if((ptr = smfi_getsymval(ctx, "{_}")) != NULL)
 					fprintf(sendmail,
 						"X-Infected-Received-From: %s\n",
 						ptr);
7a9b0f05
 				fputs("Subject: Virus intercepted\n\n", sendmail);
 
3ce543c7
 				if((templatefile == NULL) ||
a0c42dae
 				   (sendtemplate(ctx, templatefile, sendmail, virusname) < 0)) {
e368b3dd
 					/*
ff46437f
 					 * Use our own hardcoded template
 					 */
 					const char *sender;
 
 					/*
 					 * Try to determine who sent the
 					 * message. In the days of faked from
 					 * addresses this is not easy!
 					 */
 					if(privdata->from)
 						sender = (strcmp(privdata->from, "<>") == 0) ?
 							smfi_getsymval(ctx, "_") :
 							privdata->from;
 					else
 						sender = smfi_getsymval(ctx, "_");
 
3ce543c7
 					if(bflag)
144bc6cf
 						fputs("A message you sent to\n", sendmail);
3ce543c7
 					else if(pflag)
 						/*
ff46437f
 						 * The message is only going to
 						 * the postmaster, so include
 						 * some useful information
3ce543c7
 						 */
144bc6cf
 						fprintf(sendmail, "The message %s sent from %s to\n",
ff46437f
 							sendmailId, sender);
3ce543c7
 					else
144bc6cf
 						fprintf(sendmail, "A message sent from %s to\n",
ff46437f
 							sender);
3ce543c7
 
 					for(to = privdata->to; *to; to++)
144bc6cf
 						fprintf(sendmail, "\t%s\n", *to);
734ea355
 					fprintf(sendmail, "contained %s and has not been delivered.\n", virusname);
3ce543c7
 
 					if(privdata->filename != NULL)
b475d5ea
 						if(qfile(privdata, virusname) == 0)
 							fprintf(sendmail, "\nThe message in question has been quarantined as %s\n", privdata->filename);
3ce543c7
 
736c8d91
 					if(hflag) {
 						fprintf(sendmail, "\nThe message was received by %s from %s via %s\n\n",
ff46437f
 							smfi_getsymval(ctx, "j"), sender,
736c8d91
 							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)
502c8234
 						/*
 						 * 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);
 
9e1e77b9
 				}
668c7570
 
7a9b0f05
 				pclose(sendmail);
 			}
e3aaff8e
 		}
668c7570
 
 		if(privdata->filename) {
 			assert(quarantine_dir != NULL);
 
 			if(use_syslog)
 				syslog(LOG_NOTICE, "Quarantined infected mail as %s", privdata->filename);
 			/*
7d81c053
 			 * Cleanup filename here otherwise clamfi_free() will
 			 * delete the file that we wish to keep because it
 			 * is infected
668c7570
 			 */
 			free(privdata->filename);
 			privdata->filename = NULL;
 		}
 
e004f1c5
 		if(quarantine) {
 			for(to = privdata->to; *to; to++) {
 				smfi_delrcpt(ctx, *to);
668c7570
 				smfi_addheader(ctx, "X-Original-To", *to);
e004f1c5
 				free(*to);
 			}
 			free(privdata->to);
 			privdata->to = NULL;
a321a25b
 			/*
 			 * NOTE: on a closed relay this will not work
 			 * if the recipient is a remote address
 			 */
e004f1c5
 			if(smfi_addrcpt(ctx, quarantine) == MI_FAILURE) {
 				if(use_syslog)
 					syslog(LOG_DEBUG, "Can't set quarantine user %s", quarantine);
 				else
f7ab4278
 					cli_warnmsg("Can't set quarantine user %s\n", quarantine);
459b60af
 			} else
 				setsubject(ctx, virusname);
 		} else if(advisory)
 			setsubject(ctx, virusname);
 		else if(rejectmail) {
b5c80361
 			if(privdata->discard)
 				rc = SMFIS_DISCARD;
 			else
 				rc = SMFIS_REJECT;	/* Delete the e-mail */
 		} else
3a03d183
 			rc = SMFIS_DISCARD;
e3aaff8e
 
734ea355
 		snprintf(reject, sizeof(reject) - 1, "%s detected by ClamAV - http://www.clamav.net", virusname);
b5c80361
 		smfi_setreply(ctx, (char *)privdata->rejectCode, "5.7.1", reject);
e3aaff8e
 	}
 	clamfi_cleanup(ctx);
 
 	return rc;
 }
 
 static sfsistat
 clamfi_abort(SMFICTX *ctx)
 {
 #ifdef	CL_DEBUG
 	if(use_syslog)
 		syslog(LOG_DEBUG, "clamfi_abort");
 #endif
 
08992bbd
 	cli_dbgmsg("clamfi_abort\n");
e3aaff8e
 	/*
 	 * Unlock incase we're called during a cond_timedwait in envfrom
 	 *
ba2dfeb2
 	 * TODO: There *must* be a tidier a safer way of doing this!
e3aaff8e
 	 */
05c5d068
 	if((max_children > 0) && (n_children >= max_children)) {
 		(void)pthread_mutex_trylock(&n_children_mutex);
88f28d8c
 		(void)pthread_mutex_unlock(&n_children_mutex);
05c5d068
 	}
e3aaff8e
 
 	clamfi_cleanup(ctx);
 
68d5a5f3
 	return cl_error;
e3aaff8e
 }
 
 static sfsistat
 clamfi_close(SMFICTX *ctx)
 {
 	struct privdata *privdata = (struct privdata *)smfi_getpriv(ctx);
 
5b6bb93b
 	cli_dbgmsg("clamfi_close\n");
7d81c053
 	if(privdata != NULL)
 		clamfi_cleanup(ctx);
e3aaff8e
 
 	if(logVerbose)
 		syslog(LOG_DEBUG, "clamfi_close");
 
 	return SMFIS_CONTINUE;
 }
 
 static void
 clamfi_cleanup(SMFICTX *ctx)
 {
 	struct privdata *privdata = (struct privdata *)smfi_getpriv(ctx);
 
7418fb74
 	if(privdata) {
c54d7329
 		clamfi_free(privdata);
 		smfi_setpriv(ctx, NULL);
 	}
 }
 
 static void
 clamfi_free(struct privdata *privdata)
 {
 	if(privdata) {
51b03ecb
 		if(privdata->body)
 			free(privdata->body);
 
7418fb74
 		if(privdata->dataSocket >= 0) {
 			close(privdata->dataSocket);
 			privdata->dataSocket = -1;
 		}
e3aaff8e
 
668c7570
 		if(privdata->filename != NULL) {
456edb55
 			/*
 			 * Don't print an error if the file hasn't been created
 			 * yet
 			 */
 			if((unlink(privdata->filename) < 0) && (errno != ENOENT)) {
668c7570
 				perror(privdata->filename);
7d81c053
 				if(use_syslog)
 					syslog(LOG_ERR,
 						"Can't remove clean file %s",
 						privdata->filename);
 			}
668c7570
 			free(privdata->filename);
 			privdata->filename = NULL;
 		}
 
7418fb74
 		if(privdata->from) {
e3aaff8e
 #ifdef	CL_DEBUG
7418fb74
 			if(debug_level >= 9)
5b6bb93b
 				cli_dbgmsg("Free privdata->from\n");
e3aaff8e
 #endif
7418fb74
 			free(privdata->from);
 			privdata->from = NULL;
 		}
e3aaff8e
 
7418fb74
 		if(privdata->to) {
 			char **to;
e3aaff8e
 
7418fb74
 			for(to = privdata->to; *to; to++) {
e3aaff8e
 #ifdef	CL_DEBUG
7418fb74
 				if(debug_level >= 9)
5b6bb93b
 					cli_dbgmsg("Free *privdata->to\n");
e3aaff8e
 #endif
7418fb74
 				free(*to);
 			}
e3aaff8e
 #ifdef	CL_DEBUG
7418fb74
 			if(debug_level >= 9)
5b6bb93b
 				cli_dbgmsg("Free privdata->to\n");
e3aaff8e
 #endif
7418fb74
 			free(privdata->to);
 			privdata->to = NULL;
 		}
e3aaff8e
 
7418fb74
 		if(privdata->cmdSocket >= 0) {
 			char buf[64];
e3aaff8e
 
7418fb74
 			/*
 			 * Flush the remote end so that clamd doesn't get a SIGPIPE
 			 */
66ff992e
 			while(clamd_recv(privdata->cmdSocket, buf, sizeof(buf)) > 0)
7418fb74
 				;
 			close(privdata->cmdSocket);
 			privdata->cmdSocket = -1;
 		}
9e1e77b9
 		if(privdata->headers)
 			header_list_free(privdata->headers);
e3aaff8e
 
 #ifdef	CL_DEBUG
7418fb74
 		if(debug_level >= 9)
5b6bb93b
 			cli_dbgmsg("Free privdata\n");
e3aaff8e
 #endif
736c8d91
 		if(privdata->received)
502c8234
 			free(privdata->received);
7418fb74
 		free(privdata);
 	}
e3aaff8e
 
 	if(max_children > 0) {
 		pthread_mutex_lock(&n_children_mutex);
 		/*
 		 * Deliberately errs on the side of broadcasting too many times
 		 */
198d714a
 		if(n_children > 0)
 			--n_children;
e3aaff8e
 #ifdef	CL_DEBUG
5b6bb93b
 		cli_dbgmsg("pthread_cond_broadcast\n");
e3aaff8e
 #endif
88f28d8c
 		pthread_cond_broadcast(&n_children_cond);
f9c88a98
 		cli_dbgmsg("<n_children = %d\n", n_children);
e3aaff8e
 		pthread_mutex_unlock(&n_children_mutex);
 	}
 }
 
f7ab4278
 /*
7d81c053
  * Returns < 0 for failure, otherwise the number of bytes sent
f7ab4278
  */
e3aaff8e
 static int
7d81c053
 clamfi_send(struct privdata *privdata, size_t len, const char *format, ...)
e3aaff8e
 {
 	char output[BUFSIZ];
 	const char *ptr;
7d81c053
 	int ret = 0;
e3aaff8e
 
 	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);
0c933aca
 		vsnprintf(output, sizeof(output) - 1, format, argp);
e3aaff8e
 		va_end(argp);
 
 		len = strlen(output);
 		ptr = output;
 	}
 #ifdef	CL_DEBUG
f7ab4278
 	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);
 	}
e3aaff8e
 #endif
 
 	while(len > 0) {
2a2f7ff3
 		const int nbytes = (quarantine_dir) ?
668c7570
 			write(privdata->dataSocket, ptr, len) :
 			send(privdata->dataSocket, ptr, len, 0);
e3aaff8e
 
8ac80fb8
 		assert(privdata->dataSocket >= 0);
 
e3aaff8e
 		if(nbytes == -1) {
ea4465c4
 			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) {
8ac80fb8
 #ifdef HAVE_STRERROR_R
ea4465c4
 					char buf[32];
 					strerror_r(errno, buf, sizeof(buf));
 					syslog(LOG_ERR,
 						"write failure (%u bytes) to clamd: %s",
 						len, buf);
8ac80fb8
 #else
ea4465c4
 					syslog(LOG_ERR, "write failure (%u bytes) to clamd: %s", len, strerror(errno));
8ac80fb8
 #endif
ea4465c4
 				}
 				checkClamd();
8ac80fb8
 			}
e3aaff8e
 
 			return -1;
 		}
7d81c053
 		ret += nbytes;
e3aaff8e
 		len -= nbytes;
 		ptr = &ptr[nbytes];
7d81c053
 
 		if(streamMaxLength > 0L) {
 			privdata->numBytes += nbytes;
 			if(privdata->numBytes >= streamMaxLength)
 				break;
 		}
e3aaff8e
 	}
7d81c053
 	return ret;
e3aaff8e
 }
 
 /*
  * Like strcpy, but return the END of the destination, allowing a quicker
  * means of adding to the end of a string than strcat
  */
20bca05f
 #if	0
e3aaff8e
 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);
 }
20bca05f
 #endif
66ff992e
 
 /*
  * Read from clamav - timeout if necessary
  */
 static int
 clamd_recv(int sock, char *buf, size_t len)
 {
 	fd_set rfds;
 	struct timeval tv;
 
96f3d93b
 	if(readTimeout == 0)
66ff992e
 		return recv(sock, buf, len, 0);
 
 	FD_ZERO(&rfds);
 	FD_SET(sock, &rfds);
 
96f3d93b
 	tv.tv_sec = readTimeout;
66ff992e
 	tv.tv_usec = 0;
 
 	switch(select(sock + 1, &rfds, NULL, NULL, &tv)) {
 		case -1:
 			perror("select");
 			return -1;
 		case 0:
 			if(use_syslog)
96f3d93b
 				syslog(LOG_ERR, "No data received from clamd in %d seconds\n", readTimeout);
66ff992e
 			return 0;
 	}
 	return recv(sock, buf, len, 0);
 }
fe3d8be8
 
 /*
  * Read in the signature file
  */
 static off_t
 updateSigFile(void)
 {
 	struct stat statb;
 	int fd;
 
 	if(sigFilename == NULL)
 		/* nothing to read */
b5c80361
 		return 0;
fe3d8be8
 
 	if(stat(sigFilename, &statb) < 0) {
 		perror(sigFilename);
 		if(use_syslog)
a321a25b
 			syslog(LOG_ERR, "Can't stat %s", sigFilename);
fe3d8be8
 		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)
a321a25b
 			syslog(LOG_ERR, "Can't open %s", sigFilename);
fe3d8be8
 		return 0;
 	}
 
 	signatureStamp = statb.st_mtime;
 
d23d480c
 	signature = cli_realloc(signature, statb.st_size);
456edb55
 	if(signature)
 		read(fd, signature, statb.st_size);
fe3d8be8
 	close(fd);
 
 	return statb.st_size;
 }
9e1e77b9
 
 static header_list_t
1f7a8360
 header_list_new(void)
9e1e77b9
 {
 	header_list_t ret;
 
 	ret = (header_list_t)cli_malloc(sizeof(struct header_list_struct));
502c8234
 	if(ret) {
 		ret->first = NULL;
 		ret->last = NULL;
 	}
9e1e77b9
 	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;
 
81bdf63b
 	len = (size_t)(strlen(headerf) + strlen(headerv) + 3);
9e1e77b9
 
 	header = (char *)cli_malloc(len);
502c8234
 	if(header == NULL)
 		return;
 
f9f239aa
 	sprintf(header, "%s: %s", headerf, headerv);
5b6bb93b
 	new_node = (struct header_node_t *)cli_malloc(sizeof(struct header_node_t));
502c8234
 	if(new_node == NULL) {
 		free(header);
 		return;
 	}
9e1e77b9
 	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;
 
736c8d91
 	for(iter = list->first; iter; iter = iter->next) {
a321a25b
 		if(strncmp(iter->header, "From ", 5) == 0)
736c8d91
 			putc('>', fp);
9e1e77b9
 		fprintf(fp, "%s\n", iter->header);
736c8d91
 	}
9e1e77b9
 }
3ce543c7
 
f7ab4278
 /*
  * Establish a connection to clamd
  *	Returns success (1) or failure (0)
  */
 static int
 connect2clamd(struct privdata *privdata)
 {
 	char **to;
aead37b9
 	char *msg;
 	int length;
f7ab4278
 
b5c80361
 	assert(privdata != NULL);
f7ab4278
 	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;
05c5d068
 		time_t t;
502c8234
 		int MM, YY, DD;
 		const struct tm *tm;
f7ab4278
 
502c8234
 		/*
 		 * Based on an idea by Christian Pelissier
 		 * <Christian.Pelissier@onera.fr>. Store different days
 		 * in different directories to make them easier to manage
 		 */
05c5d068
 		t = time((time_t *)0);
502c8234
 		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,
736c8d91
 			YY, MM, DD);
502c8234
 
18c4370d
 		if((mkdir(privdata->filename, 0700) < 0) && (errno != EEXIST)) {
456edb55
 			perror(privdata->filename);
 			if(use_syslog)
 				syslog(LOG_ERR, "mkdir %s failed", privdata->filename);
 			return 0;
 		}
f7ab4278
 
 		do {
502c8234
 			sprintf(privdata->filename,
 				"%s/%02d%02d%02d/msg.XXXXXX",
 				quarantine_dir, YY, MM, DD);
f7ab4278
 #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) {
b5c80361
 			perror(privdata->filename);
f7ab4278
 			if(use_syslog)
b5c80361
 				syslog(LOG_ERR, "Temporary quarantine file %s creation failed", privdata->filename);
f7ab4278
 			return 0;
 		}
0abc0a57
 		privdata->serverNumber = -1;
f7ab4278
 	} else {
 		int freeServer, nbytes;
 		struct sockaddr_in reply;
226d027a
 		unsigned short p;
f7ab4278
 		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;
658f19f8
 			strncpy(server.sun_path, localSocket, sizeof(server.sun_path));
f7ab4278
 
 			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;
0abc0a57
 			privdata->serverNumber = -1;
f7ab4278
 		} 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;
 			}
0abc0a57
 			privdata->serverNumber = freeServer;
f7ab4278
 		}
 
 		/*
 		 * 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
226d027a
 		if(sscanf(buf, "PORT %hu\n", &p) != 1) {
f7ab4278
 			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;
226d027a
 		reply.sin_port = (in_port_t)htons(p);
f7ab4278
 
 		assert(serverIPs != NULL);
 
 		reply.sin_addr.s_addr = serverIPs[freeServer];
 
 #ifdef	CL_DEBUG
 		if(debug_level >= 4)
226d027a
 			cli_dbgmsg("Connecting to local port %d\n", p);
f7ab4278
 #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",
226d027a
 					p, buf);
f7ab4278
 #else
226d027a
 				syslog(LOG_ERR, "Failed to connect to port %d given by clamd: %s", p, strerror(errno));
f7ab4278
 #endif
 			}
 			return 0;
 		}
 	}
 
 	/*
aead37b9
 	 * Combine the To and From into one clamfi_send to save bandwidth
 	 * when sending using TCP/IP to connect to a remote clamd, by band
 	 * width here I mean number of packets
f7ab4278
 	 */
aead37b9
 	length = strlen(privdata->from) + 34;
f7ab4278
 	for(to = privdata->to; *to; to++)
e368b3dd
 		length += strlen(*to) + 5;
aead37b9
 
 	msg = cli_malloc(length + 1);
 
 	if(msg) {
 		sprintf(msg, "Received: by clamav-milter\nFrom: %s\n",
 			privdata->from);
 
 		for(to = privdata->to; *to; to++) {
 			char *eom = strchr(msg, '\0');
 
 			sprintf(eom, "To: %s\n", *to);
 		}
 		if(clamfi_send(privdata, length, msg) != length) {
 			free(msg);
f7ab4278
 			return 0;
aead37b9
 		}
 		free(msg);
 	} else {
 		clamfi_send(privdata, 0,
 			"Received: by clamav-milter\nFrom: %s\n",
 			privdata->from);
 
 		for(to = privdata->to; *to; to++)
 			if(clamfi_send(privdata, 0, "To: %s\n", *to) <= 0)
 				return 0;
 	}
f7ab4278
 
 	cli_dbgmsg("connect2clamd OK\n");
 
 	return 1;
 }
b5648b5a
 
 /*
  * 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)
8ac80fb8
 		return;	/* communicating via TCP */
b5648b5a
 
 	if(pidFile == NULL)
8ac80fb8
 		return;	/* PidFile directive missing from clamav.conf */
b5648b5a
 
 	fd = open(pidFile, O_RDONLY);
 	if(fd < 0) {
 		perror(pidFile);
 		if(use_syslog)
a321a25b
 			syslog(LOG_ERR, "Can't open %s", pidFile);
b5648b5a
 		return;
 	}
 	nbytes = read(fd, buf, sizeof(buf) - 1);
0c933aca
 	if(nbytes < 0)
 		perror(pidFile);
 	else
 		buf[nbytes] = '\0';
b5648b5a
 	close(fd);
 	pid = atoi(buf);
ecaaaf05
 	if((kill(pid, 0) < 0) && (errno == ESRCH)) {
 		if(use_syslog)
a321a25b
 			syslog(LOG_ERR, "Clamd (pid %d) seems to have died",
ecaaaf05
 				pid);
 		perror("clamd");
b5648b5a
 	}
 }
3ce543c7
 
 /*
  * Send a templated message about an intercepted message. Very basic for
  * now, just to prove it works, will enhance the flexability later, only
734ea355
  * supports %v and $sendmail_variables$ at present.
502c8234
  *
  * TODO: more template features
  * TODO: allow filename to start with a '|' taken to mean the output of
  *	a program
3ce543c7
  */
 static int
a0c42dae
 sendtemplate(SMFICTX *ctx, const char *filename, FILE *sendmail, const char *virusname)
3ce543c7
 {
 	FILE *fin = fopen(filename, "r");
 	struct stat statb;
734ea355
 	char *buf, *ptr /* , *ptr2 */;
e368b3dd
 	struct privdata *privdata = (struct privdata *)smfi_getpriv(ctx);
3ce543c7
 
 	if(fin == NULL) {
 		perror(filename);
 		if(use_syslog)
a321a25b
 			syslog(LOG_ERR, "Can't open e-mail template file %s",
3ce543c7
 				filename);
 		return -1;
 	}
 
 	if(fstat(fileno(fin), &statb) < 0) {
 		/* File disappeared in race condition? */
 		perror(filename);
 		if(use_syslog)
a321a25b
 			syslog(LOG_ERR, "Can't stat e-mail template file %s",
3ce543c7
 				filename);
 		fclose(fin);
 		return -1;
 	}
 	buf = cli_malloc(statb.st_size + 1);
 	if(buf == NULL) {
456edb55
 		fclose(fin);
3ce543c7
 		if(use_syslog)
a321a25b
 			syslog(LOG_ERR, "Out of memory");
3ce543c7
 		return -1;
 	}
 	fread(buf, sizeof(char), statb.st_size, fin);
 	fclose(fin);
 	buf[statb.st_size] = '\0';
 
734ea355
 	for(ptr = buf; *ptr; ptr++)
e368b3dd
 		switch(*ptr) {
 			case '%': /* clamAV variable */
 				switch(*++ptr) {
 					case 'v':	/* virus name */
 						fputs(virusname, sendmail);
 						break;
 					case '%':
 						putc('%', sendmail);
 						break;
 					case 'h':	/* headers */
 						if(privdata)
 							header_list_print(privdata->headers, sendmail);
 						break;
 					case '\0':
 						putc('%', sendmail);
 						--ptr;
 						continue;
 					default:
 						syslog(LOG_ERR,
 							"%s: Unknown clamAV variable \"%c\"\n",
 							filename, *ptr);
 						break;
 				}
 			case '$': /* sendmail string */ {
 				const char *val;
 				char *end = strchr(++ptr, '$');
734ea355
 
e368b3dd
 				if(end == NULL) {
734ea355
 					syslog(LOG_ERR,
e368b3dd
 						"%s: Unterminated sendmail variable \"%s\"\n",
 							filename, ptr);
 					continue;
 				}
 				*end = '\0';
 
 				val = smfi_getsymval(ctx, ptr);
 				if(val == NULL) {
 					fputs(ptr, sendmail);
 					if(use_syslog)
 						syslog(LOG_ERR,
 							"%s: Unknown sendmail variable \"%s\"\n",
 							filename, ptr);
 				} else
 					fputs(val, sendmail);
 				ptr = end;
 			}
 			case '\\':
 				if(*++ptr == '\0') {
 					--ptr;
 					continue;
 				}
 				putc(*ptr, sendmail);
 				break;
 			default:
 				putc(*ptr, sendmail);
 		}
3ce543c7
 
 	free(buf);
 
e368b3dd
 
734ea355
 	return 0;
3ce543c7
 }
459b60af
 
 /*
b475d5ea
  * Keep the infected file in quarantine, return success (0) or failure
  */
 static int
 qfile(struct privdata *privdata, const char *virusname)
 {
aead37b9
 	char *newname, *ptr;
b475d5ea
 
 	assert(privdata != NULL);
 
 	if((privdata->filename == NULL) || (virusname == NULL))
 		return -1;
 
 	newname = cli_malloc(strlen(privdata->filename) + strlen(virusname) + 2);
 
 	if(newname == NULL)
 		return -1;
 
 	sprintf(newname, "%s.%s", privdata->filename, virusname);
aead37b9
 
 	/*
 	 * Strip out funnies that may be in the name of the virus, such as '/'
 	 * that would cause the quarantine to fail to save since the name
 	 * of the virus is included in the filename
 	 */
 	for(ptr = newname; *ptr; ptr++) {
 #if	defined(MSDOS) || defined(C_CYGWIN) || defined(WIN32)
 		if(strchr("/*?<>|\"+=,;: ", *ptr))
 #elif   defined(C_DARWIN)
 		if((*ptr == '/') || (*ptr >= '\200'))
 #else
 		if(*ptr == '/')
 #endif
 			*ptr = '_';
 	}
b475d5ea
 	if(link(privdata->filename, newname) < 0) {
 		perror(newname);
 		if(use_syslog)
 			syslog(LOG_WARNING, "Can't rename %s to %s",
 				privdata->filename, newname);
 		free(newname);
 		return -1;
 	}
 	free(privdata->filename);
 	privdata->filename = newname;
 
 	return 0;
 }
 
 /*
459b60af
  * Store the name of the virus in the subject of the e-mail
  */
 static void
 setsubject(SMFICTX *ctx, const char *virusname)
 {
 	char subject[128];
 
 	/*
b475d5ea
 	 * FIXME: doesn't work if there's no subject in the email
459b60af
 	 */
 	snprintf(subject, sizeof(subject) - 1, "[Virus] %s", virusname);
 	smfi_chgheader(ctx, "Subject", 1, subject);
 }
734ea355
 
 /*
  * TODO: gethostbyname_r is non-standard so different operating
  * systems do it in different ways. Need more examples
  *
  * Returns 0 for success
  */
 static int
 clamfi_gethostbyname(const char *hostname, struct hostent *hp, char *buf, size_t len)
 {
 #if	defined(HAVE_GETHOSTBYNAME_R_6)
 	/* e.g. Linux */
 	struct hostent *hp2;
 	int ret;
 
 	if((hostname == NULL) || (hp == NULL))
 		return -1;
 	if(gethostbyname_r(hostname, hp, buf, len, &hp2, &ret) < 0)
 		return errno;
 #elif	defined(HAVE_GETHOSTBYNAME_R_5)
 	/* e.g. BSD, Solaris, Cygwin */
 	int ret;
 
 	if((hostname == NULL) || (hp == NULL))
 		return -1;
 	if(gethostbyname_r(hostname, hp, buf, len, &ret) == NULL)
 		return errno;
 #elif	defined(HAVE_GETHOSTBYNAME_R_3)
 	/* e.g. HP/UX, AIX */
 	if((hostname == NULL) || (hp == NULL))
 		return -1;
 	if(gethostbyname_r(hostname, &hp, (struct hostent_data *)buf) < 0)
 		return errno;
 #else
 	/* Single thread the code */
 	struct hostent *hp2;
 	static pthread_mutex_t hostent_mutex = PTHREAD_MUTEX_INITIALIZER;
 
 	if((hostname == NULL) || (hp == NULL))
 		return -1;
 
 	pthread_mutex_lock(&hostent_mutex);
 	if((hp2 = gethostbyname(hostname)) == NULL) {
 		pthread_mutex_unlock(&hostent_mutex);
 		return errno;
 	}
 	memcpy(hp, hp2, sizeof(struct hostent));
 	pthread_mutex_unlock(&hostent_mutex);
 #endif
 
 	return 0;
 }
eef726b0
 
 /*
  * David Champion <dgc@uchicago.edu>
  *
  * Check whether addr is on network by applying netmasks.
  * addr must be a 32-bit integer-packed IPv4 address in network order.
  * For example:
  *     struct in_addr IPAddress;
  *     isLocal = isLocalAddr(IPAddress.s_addr);
  */
 static int
 isLocalAddr(in_addr_t addr)
 {
 	const struct cidr_net *net;
 
 	for(net = localNets; net->base; net++)
 		if(htonl(net->base & net->mask) == (addr & htonl(net->mask)))
 			return 1;
 
 	return 0;	/* is non-local */
 }