freshclam/freshclam.c
e3aaff8e
 /*
7b8edc5c
  *  Copyright (C) 2002 - 2006 Tomasz Kojm <tkojm@clamav.net>
e3aaff8e
  *
  *  This program is free software; you can redistribute it and/or modify
bb34cb31
  *  it under the terms of the GNU General Public License version 2 as
  *  published by the Free Software Foundation.
e3aaff8e
  *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
  *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
48b7b4a7
  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  *  MA 02110-1301, USA.
e3aaff8e
  */
97eb9786
 #ifdef	_MSC_VER
 #include <winsock.h>
 #endif
5ca6034b
 
6d6e8271
 #if HAVE_CONFIG_H
 #include "clamav-config.h"
 #endif
 
e3aaff8e
 #include <stdio.h>
 #include <stdlib.h>
97eb9786
 #ifdef	HAVE_UNISTD_H
e3aaff8e
 #include <unistd.h>
97eb9786
 #endif
e3aaff8e
 #include <string.h>
dd95cc2d
 #include <errno.h>
5ca6034b
 #include <signal.h>
8000d078
 #include <time.h>
e3aaff8e
 #include <sys/types.h>
97eb9786
 #ifndef	C_WINDOWS
5f0d9945
 #include <sys/wait.h>
97eb9786
 #endif
e3aaff8e
 #include <sys/stat.h>
 #include <fcntl.h>
97eb9786
 #ifndef	C_WINDOWS
e3aaff8e
 #include <pwd.h>
 #include <grp.h>
97eb9786
 #endif
e3aaff8e
 
afb48b28
 #if defined(USE_SYSLOG) && !defined(C_AIX)
fb787a06
 #include <syslog.h>
 #endif
 
cc71d7c2
 #include "target.h"
a889f40e
 #include "clamav.h"
 
3f7802c9
 #include "shared/optparser.h"
a889f40e
 #include "shared/output.h"
 #include "shared/misc.h"
 
5f0d9945
 #include "execute.h"
a889f40e
 #include "manager.h"
376307a0
 #include "mirman.h"
e3aaff8e
 
dd95cc2d
 static short terminate = 0;
5f0d9945
 extern int active_children;
dd95cc2d
 
a889f40e
 static short foreground = 1;
0ae41a2d
 
dd95cc2d
 static void daemon_sighandler(int sig) {
 
     switch(sig) {
97eb9786
 #ifdef	SIGCHLD
5f0d9945
 	case SIGCHLD:
 	    waitpid(-1, NULL, WNOHANG);
 	    active_children--;
 	    break;
97eb9786
 #endif
5f0d9945
 
97eb9786
 #ifdef	SIGALRM
95c4e7b0
 	case SIGALRM:
97eb9786
 		terminate = -1;
 	    break;
 #endif
 #ifdef	SIGUSR1
dd95cc2d
 	case SIGUSR1:
97eb9786
 		terminate = -1;
dd95cc2d
 	    break;
97eb9786
 #endif
dd95cc2d
 
97eb9786
 #ifdef	SIGHUP
dd95cc2d
 	case SIGHUP:
e3eaadd0
 	    terminate = -2;
dd95cc2d
 	    break;
97eb9786
 #endif
dd95cc2d
 
 	default:
 	    terminate = 1;
 	    break;
     }
e3eaadd0
 
dd95cc2d
     return;
 }
 
3f7802c9
 static void writepid(const char *pidfile)
a889f40e
 {
dd95cc2d
 	FILE *fd;
 	int old_umask;
     old_umask = umask(0006);
     if((fd = fopen(pidfile, "w")) == NULL) {
 	logg("!Can't save PID to file %s: %s\n", pidfile, strerror(errno));
     } else {
c32360c1
 	fprintf(fd, "%d", (int) getpid());
dd95cc2d
 	fclose(fd);
     }
     umask(old_umask);
 }
 
fc83da82
 static void help(void)
a889f40e
 {
     mprintf_stdout = 1;
 
     mprintf("\n");
add738d2
     mprintf("                   Clam AntiVirus: freshclam  %s\n", get_version());
6670464f
     printf("           By The ClamAV Team: http://www.clamav.net/team\n");
     printf("           (C) 2007-2009 Sourcefire, Inc. et al.\n\n");
a889f40e
 
     mprintf("    --help               -h              show help\n");
     mprintf("    --version            -V              print version number and exit\n");
     mprintf("    --verbose            -v              be verbose\n");
     mprintf("    --debug                              enable debug messages\n");
     mprintf("    --quiet                              only output error messages\n");
bcbe6ad7
     mprintf("    --no-warnings                        don't print and log warnings\n");
a889f40e
     mprintf("    --stdout                             write to stdout instead of stderr\n");
     mprintf("\n");
     mprintf("    --config-file=FILE                   read configuration from FILE.\n");
     mprintf("    --log=FILE           -l FILE         log into FILE\n");
     mprintf("    --daemon             -d              run in daemon mode\n");
     mprintf("    --pid=FILE           -p FILE         save daemon's pid in FILE\n");
     mprintf("    --user=USER          -u USER         run as USER\n");
     mprintf("    --no-dns                             force old non-DNS verification method\n");
     mprintf("    --checks=#n          -c #n           number of checks per day, 1 <= n <= 50\n");
     mprintf("    --datadir=DIRECTORY                  download new databases into DIRECTORY\n");
 #ifdef BUILD_CLAMD
     mprintf("    --daemon-notify[=/path/clamd.conf]   send RELOAD command to clamd\n");
 #endif
     mprintf("    --local-address=IP   -a IP           bind to IP for HTTP downloads\n");
     mprintf("    --on-update-execute=COMMAND          execute COMMAND after successful update\n");
     mprintf("    --on-error-execute=COMMAND           execute COMMAND if errors occured\n");
     mprintf("    --on-outdated-execute=COMMAND        execute COMMAND when software is outdated\n");
376307a0
     mprintf("    --list-mirrors                       print mirrors from mirrors.dat\n");
2fb80ebc
     mprintf("    --submit-stats[=/path/clamd.conf]    only submit detection statistics\n");
a889f40e
 
     mprintf("\n");
 }
 
3f7802c9
 static int download(const struct optstruct *opts, const char *datadir, const char *cfgfile)
a889f40e
 {
 	int ret = 0, try = 0, maxattempts = 0;
3f7802c9
 	const struct optstruct *opt;
a889f40e
 
 
3f7802c9
     maxattempts = optget(opts, "MaxAttempts")->numarg;
a889f40e
     logg("*Max retries == %d\n", maxattempts);
 
3f7802c9
     if(!(opt = optget(opts, "DatabaseMirror"))->enabled) {
acb827c6
 	logg("^You must specify at least one database mirror in %s\n", cfgfile);
a889f40e
 	return 56;
     } else {
3f7802c9
 	while(opt) {
 	    ret = downloadmanager(opts, opt->strarg, datadir, try == maxattempts - 1);
a889f40e
 	    alarm(0);
 
 	    if(ret == 52 || ret == 54 || ret == 58 || ret == 59) {
 		if(try < maxattempts - 1) {
 		    logg("Trying again in 5 secs...\n");
 		    try++;
 		    sleep(5);
 		    continue;
 		} else {
3f7802c9
 		    logg("Giving up on %s...\n", opt->strarg);
 		    opt = (struct optstruct *) opt->nextarg;
 		    if(!opt) {
acb827c6
 			logg("Update failed. Your network may be down or none of the mirrors listed in %s is working. Check http://www.clamav.net/support/mirror-problem for possible reasons.\n", cfgfile);
a889f40e
 		    }
 		    try = 0;
 		}
 
 	    } else {
 		return ret;
 	    }
 	}
     }
 
     return ret;
 }
 
7b8edc5c
 int main(int argc, char **argv)
e3aaff8e
 {
c32360c1
 	int ret = 52;
3f7802c9
 	const char *dbdir, *cfgfile, *arg = NULL, *pidfile = NULL;
 	char *pt;
 	struct optstruct *opts;
 	const struct optstruct *opt;
97eb9786
 #ifndef	C_WINDOWS
 	struct sigaction sigact;
 	struct sigaction oldact;
 #endif
6670d61d
 #if !defined(C_OS2) && !defined(C_WINDOWS)
3f7802c9
 	const char *dbowner;
95d401c4
 	struct passwd *user;
 #endif
c2a3cdf9
 	struct stat statbuf;
376307a0
 	struct mirdat mdat;
3f7802c9
 
 
a68d5e2f
     if((opts = optparse(NULL, argc, argv, 1, OPT_FRESHCLAM, 0, NULL)) == NULL) {
3f7802c9
 	mprintf("!Can't parse command line options\n");
 	return 1;
7b8edc5c
     }
e3aaff8e
 
3f7802c9
     if(optget(opts, "help")->enabled) {
ee039e40
     	help();
3f7802c9
 	optfree(opts);
a889f40e
 	return 0;
     }
 
95d401c4
     /* parse the config file */
3f7802c9
     cfgfile = optget(opts, "config-file")->strarg;
     pt = strdup(cfgfile);
a68d5e2f
     if((opts = optparse(cfgfile, 0, NULL, 1, OPT_FRESHCLAM, 0, opts)) == NULL) {
3f7802c9
 	fprintf(stderr, "ERROR: Can't open/parse the config file %s\n", pt);
 	free(pt);
 	return 1;
95d401c4
     }
3f7802c9
     free(pt);
95d401c4
 
3f7802c9
     dbdir = optget(opts, "DatabaseDirectory")->strarg;
0aa3ba06
 
3f7802c9
     if(optget(opts, "version")->enabled) {
 	print_version(dbdir);
 	optfree(opts);
0aa3ba06
 	return 0;
     }
 
69dfed42
 #ifdef C_WINDOWS
     if(!pthread_win32_process_attach_np()) {
 	mprintf("!Can't start the win32 pthreads layer\n");
3f7802c9
 	optfree(opts);
69dfed42
 	return 63;
     }
 #endif
 
3f7802c9
     if(optget(opts, "HTTPProxyPassword")->enabled) {
c2a3cdf9
 	if(stat(cfgfile, &statbuf) == -1) {
0ae41a2d
 	    logg("^Can't stat %s (critical error)\n", cfgfile);
3f7802c9
 	    optfree(opts);
c2a3cdf9
 	    return 56;
 	}
97eb9786
 
6670d61d
 #ifndef C_WINDOWS
c2a3cdf9
 	if(statbuf.st_mode & (S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH)) {
0ae41a2d
 	    logg("^Insecure permissions (for HTTPProxyPassword): %s must have no more than 0700 permissions.\n", cfgfile);
3f7802c9
 	    optfree(opts);
c2a3cdf9
 	    return 56;
 	}
b782aece
 #endif
c2a3cdf9
     }
af22ece1
 
6670d61d
 #if !defined(C_OS2) && !defined(C_WINDOWS)
c2a3cdf9
     /* freshclam shouldn't work with root privileges */
3f7802c9
     dbowner = optget(opts, "DatabaseOwner")->strarg;
95d401c4
 
11f30313
     if(!geteuid()) {
3f7802c9
 	if((user = getpwnam(dbowner)) == NULL) {
 	    logg("^Can't get information about user %s.\n", dbowner);
 	    optfree(opts);
a889f40e
 	    return 60;
e3aaff8e
 	}
 
3f7802c9
 	if(optget(opts, "AllowSupplementaryGroups")->enabled) {
fdeade2a
 #ifdef HAVE_INITGROUPS
3f7802c9
 	    if(initgroups(dbowner, user->pw_gid)) {
0ae41a2d
 		logg("^initgroups() failed.\n");
3f7802c9
 		optfree(opts);
a889f40e
 		return 61;
fdeade2a
 	    }
 #endif
 	} else {
a7d9bef2
 #ifdef HAVE_SETGROUPS
fdeade2a
 	    if(setgroups(1, &user->pw_gid)) {
0ae41a2d
 		logg("^setgroups() failed.\n");
3f7802c9
 		optfree(opts);
a889f40e
 		return 61;
fdeade2a
 	    }
a7d9bef2
 #endif
fdeade2a
 	}
9f51cb51
 
 	if(setgid(user->pw_gid)) {
0ae41a2d
 	    logg("^setgid(%d) failed.\n", (int) user->pw_gid);
3f7802c9
 	    optfree(opts);
a889f40e
 	    return 61;
9f51cb51
 	}
 
 	if(setuid(user->pw_uid)) {
0ae41a2d
 	    logg("^setuid(%d) failed.\n", (int) user->pw_uid);
3f7802c9
 	    optfree(opts);
a889f40e
 	    return 61;
9f51cb51
 	}
e3aaff8e
     }
 #endif
 
     /* initialize some important variables */
 
cd3898c7
     if(optget(opts, "Debug")->enabled || optget(opts, "debug")->enabled)
e4ae7726
 	cl_debug();
 
3f7802c9
     if(optget(opts, "verbose")->enabled)
58bcf502
 	mprintf_verbose = 1;
e3aaff8e
 
3f7802c9
     if(optget(opts, "quiet")->enabled)
58bcf502
 	mprintf_quiet = 1;
e3aaff8e
 
3f7802c9
     if(optget(opts, "no-warnings")->enabled) {
bcbe6ad7
 	mprintf_nowarn = 1;
 	logg_nowarn = 1;
     }
 
3f7802c9
     if(optget(opts, "stdout")->enabled)
58bcf502
 	mprintf_stdout = 1;
e3aaff8e
 
     /* initialize logger */
869d0fa5
     logg_verbose = mprintf_verbose ? 1 : optget(opts, "LogVerbose")->enabled;
3f7802c9
     logg_time = optget(opts, "LogTime")->enabled;
     logg_size = optget(opts, "LogFileMaxSize")->numarg;
fb787a06
 
3f7802c9
     if((opt = optget(opts, "UpdateLogFile"))->enabled) {
 	logg_file = opt->strarg; 
c0621522
 	if(logg("#--------------------------------------\n")) {
f0205a3c
 	    mprintf("!Problem with internal logger (UpdateLogFile = %s).\n", logg_file);
3f7802c9
 	    optfree(opts);
a889f40e
 	    return 62;
e3aaff8e
 	}
95d401c4
     } else
afb48b28
 	logg_file = NULL;
e3aaff8e
 
afb48b28
 #if defined(USE_SYSLOG) && !defined(C_AIX)
3f7802c9
     if(optget(opts, "LogSyslog")->enabled) {
c695dab4
 	    int fac = LOG_LOCAL6;
 
3f7802c9
 	if((opt = optget(opts, "LogFacility"))->enabled) {
 	    if((fac = logg_facility(opt->strarg)) == -1) {
 		mprintf("!LogFacility: %s: No such facility.\n", opt->strarg);
 		optfree(opts);
a889f40e
 		return 62;
c695dab4
 	    }
 	}
 
 	openlog("freshclam", LOG_PID, fac);
afb48b28
 	logg_syslog = 1;
58bcf502
     }
fb787a06
 #endif
 
95d401c4
     /* change the current working directory */
3f7802c9
     if(chdir(dbdir)) {
 	logg("Can't change dir to %s\n", dbdir);
 	optfree(opts);
a889f40e
 	return 50;
e3aaff8e
     } else
3f7802c9
 	logg("*Current working dir is %s\n", dbdir);
e3aaff8e
 
376307a0
 
3f7802c9
     if(optget(opts, "list-mirrors")->enabled) {
a7db63d1
 	if(mirman_read("mirrors.dat", &mdat, 1) == -1) {
376307a0
 	    printf("Can't read mirrors.dat\n");
3f7802c9
 	    optfree(opts);
376307a0
 	    return 55;
 	}
 	mirman_list(&mdat);
 	mirman_free(&mdat);
3f7802c9
 	optfree(opts);
376307a0
 	return 0;
     }
 
97eb9786
 #ifdef	C_WINDOWS
     {
 	    WSADATA wsaData;
 
 	if(WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) {
 	    logg("!Error at WSAStartup(): %d\n", WSAGetLastError());
3f7802c9
 	    optfree(opts);
97eb9786
 	    return 1;
 	}
     }
 #endif
 
3f7802c9
     if(optget(opts, "daemon")->enabled) {
e3aaff8e
 	    int bigsleep, checks;
97eb9786
 #ifndef	C_WINDOWS
85e6e26a
 	    time_t now, wakeup;
e3aaff8e
 
dd95cc2d
 	memset(&sigact, 0, sizeof(struct sigaction));
 	sigact.sa_handler = daemon_sighandler;
97eb9786
 #endif
af22ece1
 
3f7802c9
 	checks = optget(opts, "Checks")->numarg;
e3aaff8e
 
3e92581e
 	if(checks <= 0) {
0ae41a2d
 	    logg("^Number of checks must be a positive integer.\n");
3f7802c9
 	    optfree(opts);
a889f40e
 	    return 41;
e3aaff8e
 	}
 
8f3337f1
 	if(!optget(opts, "DNSDatabaseInfo")->enabled || optget(opts, "no-dns")->enabled) {
3e92581e
 	    if(checks > 50) {
0ae41a2d
 		logg("^Number of checks must be between 1 and 50.\n");
3f7802c9
 		optfree(opts);
a889f40e
 		return 41;
3e92581e
 	    }
 	}
 
95d401c4
 	bigsleep = 24 * 3600 / checks;
5951212c
 
b500915b
 #if !defined(C_OS2) && !defined(C_WINDOWS)
3f7802c9
 	if(!optget(opts, "Foreground")->enabled) {
587d344b
 	    if(daemonize() == -1) {
 		logg("!daemonize() failed\n");
3f7802c9
 		optfree(opts);
587d344b
 		return 70; /* FIXME */
 	    }
0ae41a2d
             foreground = 0;
a889f40e
 	    mprintf_disabled = 1;
0ae41a2d
         }
b500915b
 #endif
5951212c
 
3f7802c9
 	if((opt = optget(opts, "PidFile"))->enabled) {
 	    pidfile = opt->strarg;
dd95cc2d
 	    writepid(pidfile);
 	}
cc71d7c2
 
5f0d9945
 	active_children = 0;
 
add738d2
 	logg("#freshclam daemon %s (OS: "TARGET_OS_TYPE", ARCH: "TARGET_ARCH_TYPE", CPU: "TARGET_CPU_TYPE")\n", get_version());
e3aaff8e
 
97eb9786
 #ifdef	C_WINDOWS
 	signal(SIGINT, daemon_sighandler);
 	terminate = 0;
 #else
dd95cc2d
 	sigaction(SIGTERM, &sigact, NULL);
 	sigaction(SIGHUP, &sigact, NULL);
 	sigaction(SIGINT, &sigact, NULL);
5f0d9945
         sigaction(SIGCHLD, &sigact, NULL);
97eb9786
 #endif
cc71d7c2
 
dd95cc2d
 	while(!terminate) {
3f7802c9
 	    ret = download(opts, dbdir, cfgfile);
af22ece1
 
64fd0bfc
 	    if(ret <= 1) {
3f7802c9
 		if((opt = optget(opts, "SubmitDetectionStats"))->enabled)
 		    submitstats(opt->strarg, opts);
64fd0bfc
             } else  {
3f7802c9
 		if((opt = optget(opts, "OnErrorExecute"))->enabled)
 		    arg = opt->strarg;
af22ece1
 
5f0d9945
 		if(arg)
6d682a0f
 		    execute("OnErrorExecute", arg, opts);
770fb166
 
 		arg = NULL;
af22ece1
 	    }
e3aaff8e
 
c0621522
 	    logg("#--------------------------------------\n");
97eb9786
 #ifdef	SIGALRM
dd95cc2d
 	    sigaction(SIGALRM, &sigact, &oldact);
97eb9786
 #endif
 #ifdef	SIGUSR1
dd95cc2d
 	    sigaction(SIGUSR1, &sigact, &oldact);
97eb9786
 #endif
 
 #ifdef	C_WINDOWS
 	    sleep(bigsleep);
 #else   
85e6e26a
 	    time(&wakeup);
 	    wakeup += bigsleep;
dd95cc2d
 	    alarm(bigsleep);
85e6e26a
 	    do {
 		pause();
 		time(&now);
 	    } while (!terminate && now < wakeup);
e3eaadd0
 
85e6e26a
 	    if (terminate == -1) {
c9f58bf1
 		logg("Received signal: wake up\n");
85e6e26a
 		terminate = 0;
e3eaadd0
 	    } else if (terminate == -2) {
c9f58bf1
 		logg("Received signal: re-opening log file\n");
e3eaadd0
 		terminate = 0;
 		logg_close();
85e6e26a
 	    }
97eb9786
 #endif
e3eaadd0
 
97eb9786
 #ifdef	SIGALRM
dd95cc2d
 	    sigaction(SIGALRM, &oldact, NULL);
97eb9786
 #endif
 #ifdef	SIGUSR1
dd95cc2d
 	    sigaction(SIGUSR1, &oldact, NULL);
97eb9786
 #endif	    
e3aaff8e
 	}
 
64fd0bfc
     } else {
3f7802c9
 	if((opt = optget(opts, "submit-stats"))->active) {
 	    if(!optget(opts, "no-warnings")->enabled)
2fb80ebc
 		logg(" *** Virus databases are not updated in this mode ***\n");
3f7802c9
 	    ret = submitstats(opt->strarg, opts);
64fd0bfc
 	} else {
3f7802c9
 	    ret = download(opts, dbdir, cfgfile);
64fd0bfc
 
3f7802c9
 	    if((opt = optget(opts, "SubmitDetectionStats"))->enabled)
 		submitstats(opt->strarg, opts);
64fd0bfc
 	}
     }
e3aaff8e
 
770fb166
     if(ret > 1) {
3f7802c9
 	if((opt = optget(opts, "OnErrorExecute"))->enabled)
             execute("OnErrorExecute", opt->strarg, opts);
af22ece1
     }
770fb166
 
dd95cc2d
     if (pidfile) {
         unlink(pidfile);
     }
e3aaff8e
 
3f7802c9
     optfree(opts);
97eb9786
 
69dfed42
 #ifdef C_WINDOWS
     WSACleanup();
 
     if(!pthread_win32_process_detach_np()) {
 	mprintf("!Can't stop the win32 pthreads layer\n");
 	return 63;
     }
 #endif
 
2d70a403
     return(ret);
e3aaff8e
 }