clamd/clamd.c
e3aaff8e
 /*
e1cbc270
  *  Copyright (C) 2013-2019 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
  *  Copyright (C) 2007-2013 Sourcefire, Inc.
086eab5c
  *
  *  Authors: Tomasz Kojm
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
  */
 
98ac8d19
 #if HAVE_CONFIG_H
 #include "clamav-config.h"
 #endif
 
e3aaff8e
 #include <stdio.h>
 #include <stdlib.h>
a9ebff44
 #include <string.h>
67118e92
 #ifdef HAVE_UNISTD_H
e3aaff8e
 #include <unistd.h>
e0bb54d7
 #endif
 #ifndef _WIN32
e3aaff8e
 #include <sys/time.h>
9011cf1e
 #include <sys/resource.h>
67118e92
 #endif
e3aaff8e
 #include <sys/types.h>
 #include <sys/stat.h>
96b02502
 #include <fcntl.h>
e3aaff8e
 #include <time.h>
081f6473
 #ifdef HAVE_PWD_H
e3aaff8e
 #include <pwd.h>
081f6473
 #endif
 #ifdef HAVE_GRP_H
e3aaff8e
 #include <grp.h>
67118e92
 #endif
6a4dd9dc
 #include <signal.h>
b4b1a327
 #include <errno.h>
e3aaff8e
 
afb48b28
 #if defined(USE_SYSLOG) && !defined(C_AIX)
e3aaff8e
 #include <syslog.h>
 #endif
 
cea858e0
 #ifdef C_LINUX
 #include <sys/resource.h>
 #endif
 
bd8603aa
 #include "target.h"
 
 #include "libclamav/clamav.h"
 #include "libclamav/others.h"
3d53538b
 #include "libclamav/matcher-ac.h"
8cc8f810
 #include "libclamav/readdb.h"
bd8603aa
 
 #include "shared/output.h"
064b4a0c
 #include "shared/optparser.h"
bd8603aa
 #include "shared/misc.h"
 
 #include "server.h"
e3aaff8e
 #include "tcpserver.h"
 #include "localserver.h"
 #include "others.h"
afb48b28
 #include "shared.h"
769f37a6
 #include "scanner.h"
6d6e8271
 
58bcf502
 short debug_mode = 0, logok = 0;
b68375fd
 short foreground = -1;
0ae41a2d
 
fc83da82
 static void help(void)
bd8603aa
 {
     printf("\n");
e098cdc5
     printf("                      Clam AntiVirus: Daemon %s\n", get_version());
964a1e73
     printf("           By The ClamAV Team: https://www.clamav.net/about.html#credits\n");
e1cbc270
     printf("           (C) 2019 Cisco Systems, Inc.\n");
e098cdc5
     printf("\n");
     printf("    clamd [options]\n");
     printf("\n");
     printf("    --help                   -h             Show this help\n");
     printf("    --version                -V             Show version number\n");
83c3979f
     printf("    --foreground             -F             Run in foreground; do not daemonize\n");
e098cdc5
     printf("    --debug                                 Enable debug mode\n");
     printf("    --config-file=FILE       -c FILE        Read configuration from FILE\n");
     printf("\n");
     printf("Pass in - as the filename for stdin.\n");
     printf("\n");
bd8603aa
 }
 
064b4a0c
 static struct optstruct *opts;
f7019d13
 
 /* When running under valgrind and daemonizing, valgrind incorrectly reports
  * leaks from the engine, because it can't see that all the memory is still
  * reachable (some pointers are stored mangled in the JIT). 
  * So free the engine on exit from the parent too (during daemonize)
  */
 static struct cl_engine *gengine = NULL;
 static void free_engine(void)
 {
     if (gengine) {
14a7c47b
         cl_engine_free(gengine);
         gengine = NULL;
f7019d13
     }
 }
 
7b8edc5c
 int main(int argc, char **argv)
e3aaff8e
 {
14a7c47b
     static struct cl_engine *engine = NULL;
     const struct optstruct *opt;
288057e9
 #ifndef _WIN32
14a7c47b
     struct passwd *user = NULL;
     struct sigaction sa;
     struct rlimit rlim;
a9d3aa14
 #endif
14a7c47b
     time_t currtime;
     const char *dbdir, *cfgfile;
     char *pua_cats = NULL, *pt;
6df13d04
     int ret, tcpsock = 0, localsock = 0, min_port, max_port;
288057e9
     unsigned int sigs      = 0;
     int *lsockets          = NULL;
8c241c57
     unsigned int nlsockets = 0;
14a7c47b
     unsigned int dboptions = 0;
288057e9
     unsigned int i;
b68375fd
     int j;
     int num_fd;
c695dab4
 #ifdef C_LINUX
14a7c47b
     STATBUF sb;
c695dab4
 #endif
7b8edc5c
 
288057e9
     if (check_flevel())
14a7c47b
         exit(1);
bca0b679
 
be4bf7f4
 #ifndef _WIN32
a866b077
     memset(&sa, 0, sizeof(sa));
     sa.sa_handler = SIG_IGN;
     sigaction(SIGHUP, &sa, NULL);
     sigaction(SIGUSR2, &sa, NULL);
67118e92
 #endif
7b8edc5c
 
288057e9
     if ((opts = optparse(NULL, argc, argv, 1, OPT_CLAMD, 0, NULL)) == NULL) {
14a7c47b
         mprintf("!Can't parse command line options\n");
         return 1;
7b8edc5c
     }
e3aaff8e
 
288057e9
     if (optget(opts, "help")->enabled) {
14a7c47b
         help();
         optfree(opts);
         return 0;
e3aaff8e
     }
 
288057e9
     if (optget(opts, "debug")->enabled) {
cea858e0
 #if defined(C_LINUX)
14a7c47b
         /* njh@bandsman.co.uk: create a dump if needed */
         rlim.rlim_cur = rlim.rlim_max = RLIM_INFINITY;
288057e9
         if (setrlimit(RLIMIT_CORE, &rlim) < 0)
14a7c47b
             perror("setrlimit");
cea858e0
 #endif
14a7c47b
         debug_mode = 1;
cea858e0
     }
c238ac42
 
b68375fd
     /* check foreground option from command line to override config file */
288057e9
     for (j = 0; j < argc; j += 1) {
         if ((memcmp(argv[j], "--foreground", 12) == 0) || (memcmp(argv[j], "-F", 2) == 0)) {
b68375fd
             /* found */
             break;
         }
     }
 
288057e9
     if (j < argc) {
         if (optget(opts, "Foreground")->enabled) {
b68375fd
             foreground = 1;
288057e9
         } else {
b68375fd
             foreground = 0;
         }
     }
 
     num_fd = sd_listen_fds(0);
 
e3aaff8e
     /* parse the config file */
064b4a0c
     cfgfile = optget(opts, "config-file")->strarg;
288057e9
     pt      = strdup(cfgfile);
637d2461
     if (pt == NULL) {
288057e9
         fprintf(stderr, "ERROR: Unable to allocate memory for config file\n");
         return 1;
637d2461
     }
288057e9
     if ((opts = optparse(cfgfile, 0, NULL, 1, OPT_CLAMD, 0, opts)) == NULL) {
14a7c47b
         fprintf(stderr, "ERROR: Can't open/parse the config file %s\n", pt);
         free(pt);
         return 1;
e3aaff8e
     }
064b4a0c
     free(pt);
0aa3ba06
 
288057e9
     if (optget(opts, "version")->enabled) {
14a7c47b
         print_version(optget(opts, "DatabaseDirectory")->strarg);
         optfree(opts);
         return 0;
0aa3ba06
     }
 
0ae41a2d
     /* drop privileges */
b2354dc1
 #ifndef _WIN32
288057e9
     if (geteuid() == 0 && (opt = optget(opts, "User"))->enabled) {
         if ((user = getpwnam(opt->strarg)) == NULL) {
14a7c47b
             fprintf(stderr, "ERROR: Can't get information about user %s.\n", opt->strarg);
             optfree(opts);
             return 1;
         }
0ae41a2d
 
 #ifdef HAVE_INITGROUPS
288057e9
         if (initgroups(opt->strarg, user->pw_gid)) {
             fprintf(stderr, "ERROR: initgroups() failed.\n");
             optfree(opts);
             return 1;
         }
2ea4230d
 #elif HAVE_SETGROUPS
288057e9
         if (setgroups(1, &user->pw_gid)) {
             fprintf(stderr, "ERROR: setgroups() failed.\n");
             optfree(opts);
             return 1;
         }
0ae41a2d
 #endif
14a7c47b
 
288057e9
         if (setgid(user->pw_gid)) {
             fprintf(stderr, "ERROR: setgid(%d) failed.\n", (int)user->pw_gid);
14a7c47b
             optfree(opts);
             return 1;
         }
 
288057e9
         if (setuid(user->pw_uid)) {
             fprintf(stderr, "ERROR: setuid(%d) failed.\n", (int)user->pw_uid);
14a7c47b
             optfree(opts);
             return 1;
         }
0ae41a2d
     }
 #endif
 
e3aaff8e
     /* initialize logger */
288057e9
     logg_lock    = !optget(opts, "LogFileUnlock")->enabled;
     logg_time    = optget(opts, "LogTime")->enabled;
     logok        = optget(opts, "LogClean")->enabled;
     logg_size    = optget(opts, "LogFileMaxSize")->numarg;
064b4a0c
     logg_verbose = mprintf_verbose = optget(opts, "LogVerbose")->enabled;
42ccf9c2
     if (logg_size)
         logg_rotate = optget(opts, "LogRotate")->enabled;
af309677
     mprintf_send_timeout = optget(opts, "SendBufTimeout")->numarg;
e3aaff8e
 
6e3256f4
     do { /* logger initialized */
288057e9
         if ((opt = optget(opts, "LogFile"))->enabled) {
14a7c47b
             char timestr[32];
             logg_file = opt->strarg;
288057e9
             if (!cli_is_abspath(logg_file)) {
14a7c47b
                 fprintf(stderr, "ERROR: LogFile requires full path.\n");
                 ret = 1;
                 break;
             }
             time(&currtime);
288057e9
             if (logg("#+++ Started at %s", cli_ctime(&currtime, timestr, sizeof(timestr)))) {
14a7c47b
                 fprintf(stderr, "ERROR: Can't initialize the internal logger\n");
                 ret = 1;
                 break;
             }
         } else {
             logg_file = NULL;
         }
6e3256f4
 
288057e9
         if (optget(opts, "DevLiblog")->enabled)
14a7c47b
             cl_set_clcb_msg(msg_callback);
370892d0
 
288057e9
         if ((ret = cl_init(CL_INIT_DEFAULT))) {
14a7c47b
             logg("!Can't initialize libclamav: %s\n", cl_strerror(ret));
             ret = 1;
             break;
         }
 
288057e9
         if (optget(opts, "Debug")->enabled) {
14a7c47b
             /* enable debug messages in libclamav */
             cl_debug();
             logg_verbose = 2;
         }
370892d0
 
afb48b28
 #if defined(USE_SYSLOG) && !defined(C_AIX)
288057e9
         if (optget(opts, "LogSyslog")->enabled) {
14a7c47b
             int fac = LOG_LOCAL6;
 
             opt = optget(opts, "LogFacility");
288057e9
             if ((fac = logg_facility(opt->strarg)) == -1) {
14a7c47b
                 logg("!LogFacility: %s: No such facility.\n", opt->strarg);
                 ret = 1;
                 break;
             }
 
             openlog("clamd", LOG_PID, fac);
             logg_syslog = 1;
         }
e3aaff8e
 #endif
 
c695dab4
 #ifdef C_LINUX
14a7c47b
         procdev = 0;
288057e9
         if (CLAMSTAT("/proc", &sb) != -1 && !sb.st_size)
14a7c47b
             procdev = sb.st_dev;
c695dab4
 #endif
e3aaff8e
 
14a7c47b
         /* check socket type */
e3aaff8e
 
288057e9
         if (optget(opts, "TCPSocket")->enabled)
14a7c47b
             tcpsock = 1;
57358cc8
 
288057e9
         if (optget(opts, "LocalSocket")->enabled)
14a7c47b
             localsock = 1;
57358cc8
 
b68375fd
         logg("#Received %d file descriptor(s) from systemd.\n", num_fd);
 
288057e9
         if (!tcpsock && !localsock && num_fd == 0) {
14a7c47b
             logg("!Please define server type (local and/or TCP).\n");
             ret = 1;
             break;
         }
e3aaff8e
 
288057e9
         logg("#clamd daemon %s (OS: " TARGET_OS_TYPE ", ARCH: " TARGET_ARCH_TYPE ", CPU: " TARGET_CPU_TYPE ")\n", get_version());
50b26397
 
be4bf7f4
 #ifndef _WIN32
288057e9
         if (user)
14a7c47b
             logg("#Running as user %s (UID %u, GID %u)\n", user->pw_name, user->pw_uid, user->pw_gid);
a9d3aa14
 #endif
ab8d8f52
 
8b94e259
 #if defined(RLIMIT_DATA) && defined(C_BSD)
14a7c47b
         if (getrlimit(RLIMIT_DATA, &rlim) == 0) {
288057e9
             /* bb #1941.
14a7c47b
             * On 32-bit FreeBSD if you set ulimit -d to >2GB then mmap() will fail
             * too soon (after ~120 MB).
             * Set limit lower than 2G if on 32-bit */
288057e9
             uint64_t lim = rlim.rlim_cur;
             if (sizeof(void *) == 4 &&
                 lim > (1ULL << 31)) {
                 rlim.rlim_cur = 1ULL << 31;
                 if (setrlimit(RLIMIT_DATA, &rlim) < 0)
                     logg("!setrlimit(RLIMIT_DATA) failed: %s\n", strerror(errno));
                 else
                     logg("Running on 32-bit system, and RLIMIT_DATA > 2GB, lowering to 2GB!\n");
             }
14a7c47b
         }
9011cf1e
 #endif
 
288057e9
         if (logg_size)
059ca614
             logg("#Log file size limited to %lld bytes.\n", (long long int)logg_size);
14a7c47b
         else
             logg("#Log file size limit disabled.\n");
50b26397
 
14a7c47b
         min_port = optget(opts, "StreamMinPort")->numarg;
         max_port = optget(opts, "StreamMaxPort")->numarg;
         if (min_port < 1024 || min_port > max_port || max_port > 65535) {
             logg("!Invalid StreamMinPort/StreamMaxPort: %d, %d\n", min_port, max_port);
             ret = 1;
             break;
         }
949c6fe5
 
288057e9
         if (!(engine = cl_engine_new())) {
14a7c47b
             logg("!Can't initialize antivirus engine\n");
             ret = 1;
             break;
         }
370892d0
 
14a7c47b
         if (optget(opts, "disable-cache")->enabled)
             cl_engine_set_num(engine, CL_ENGINE_DISABLE_CACHE, 1);
 
         /* load the database(s) */
         dbdir = optget(opts, "DatabaseDirectory")->strarg;
         logg("#Reading databases from %s\n", dbdir);
 
288057e9
         if (optget(opts, "DetectPUA")->enabled) {
14a7c47b
             dboptions |= CL_DB_PUA;
 
288057e9
             if ((opt = optget(opts, "ExcludePUA"))->enabled) {
14a7c47b
                 dboptions |= CL_DB_PUA_EXCLUDE;
                 i = 0;
                 logg("#Excluded PUA categories:");
 
288057e9
                 while (opt) {
                     if (!(pua_cats = realloc(pua_cats, i + strlen(opt->strarg) + 3))) {
14a7c47b
                         logg("!Can't allocate memory for pua_cats\n");
                         cl_engine_free(engine);
                         ret = 1;
                         break;
                     }
 
                     logg("# %s", opt->strarg);
 
                     sprintf(pua_cats + i, ".%s", opt->strarg);
                     i += strlen(opt->strarg) + 1;
                     pua_cats[i] = 0;
288057e9
                     opt         = opt->nextarg;
14a7c47b
                 }
 
                 if (ret)
                     break;
 
                 logg("#\n");
288057e9
                 pua_cats[i]     = '.';
14a7c47b
                 pua_cats[i + 1] = 0;
             }
 
288057e9
             if ((opt = optget(opts, "IncludePUA"))->enabled) {
                 if (pua_cats) {
14a7c47b
                     logg("!ExcludePUA and IncludePUA cannot be used at the same time\n");
                     free(pua_cats);
                     ret = 1;
                     break;
                 }
 
                 dboptions |= CL_DB_PUA_INCLUDE;
                 i = 0;
                 logg("#Included PUA categories:");
288057e9
                 while (opt) {
                     if (!(pua_cats = realloc(pua_cats, i + strlen(opt->strarg) + 3))) {
14a7c47b
                         logg("!Can't allocate memory for pua_cats\n");
                         ret = 1;
                         break;
                     }
 
                     logg("# %s", opt->strarg);
 
                     sprintf(pua_cats + i, ".%s", opt->strarg);
                     i += strlen(opt->strarg) + 1;
                     pua_cats[i] = 0;
288057e9
                     opt         = opt->nextarg;
14a7c47b
                 }
 
                 if (ret)
                     break;
 
                 logg("#\n");
288057e9
                 pua_cats[i]     = '.';
14a7c47b
                 pua_cats[i + 1] = 0;
             }
 
288057e9
             if (pua_cats) {
                 if ((ret = cl_engine_set_str(engine, CL_ENGINE_PUA_CATEGORIES, pua_cats))) {
14a7c47b
                     logg("!cli_engine_set_str(CL_ENGINE_PUA_CATEGORIES) failed: %s\n", cl_strerror(ret));
                     free(pua_cats);
                     ret = 1;
                     break;
                 }
                 free(pua_cats);
             }
         } else {
             logg("#Not loading PUA signatures.\n");
         }
70edb085
 
288057e9
         if (optget(opts, "OfficialDatabaseOnly")->enabled) {
14a7c47b
             dboptions |= CL_DB_OFFICIAL_ONLY;
             logg("#Only loading official signatures.\n");
         }
208ceae5
 
14a7c47b
         /* set the temporary dir */
288057e9
         if ((opt = optget(opts, "TemporaryDirectory"))->enabled) {
             if ((ret = cl_engine_set_str(engine, CL_ENGINE_TMPDIR, opt->strarg))) {
14a7c47b
                 logg("!cli_engine_set_str(CL_ENGINE_TMPDIR) failed: %s\n", cl_strerror(ret));
                 ret = 1;
                 break;
             }
         }
33068e09
 
14a7c47b
         cl_engine_set_clcb_hash(engine, hash_callback);
 
1f1bf36b
         cl_engine_set_clcb_virus_found(engine, clamd_virus_found_cb);
 
288057e9
         if (optget(opts, "LeaveTemporaryFiles")->enabled)
14a7c47b
             cl_engine_set_num(engine, CL_ENGINE_KEEPTMP, 1);
 
288057e9
         if (optget(opts, "ForceToDisk")->enabled)
14a7c47b
             cl_engine_set_num(engine, CL_ENGINE_FORCETODISK, 1);
 
288057e9
         if (optget(opts, "PhishingSignatures")->enabled)
14a7c47b
             dboptions |= CL_DB_PHISHING;
         else
             logg("#Not loading phishing signatures.\n");
 
288057e9
         if (optget(opts, "Bytecode")->enabled) {
14a7c47b
             dboptions |= CL_DB_BYTECODE;
288057e9
             if ((opt = optget(opts, "BytecodeSecurity"))->enabled) {
14a7c47b
                 enum bytecode_security s;
 
                 if (!strcmp(opt->strarg, "TrustSigned")) {
                     s = CL_BYTECODE_TRUST_SIGNED;
                     logg("#Bytecode: Security mode set to \"TrustSigned\".\n");
                 } else if (!strcmp(opt->strarg, "Paranoid")) {
                     s = CL_BYTECODE_TRUST_NOTHING;
                     logg("#Bytecode: Security mode set to \"Paranoid\".\n");
                 } else {
                     logg("!Unable to parse bytecode security setting:%s\n",
288057e9
                          opt->strarg);
14a7c47b
                     ret = 1;
                     break;
                 }
 
                 if ((ret = cl_engine_set_num(engine, CL_ENGINE_BYTECODE_SECURITY, s))) {
                     logg("^Invalid bytecode security setting %s: %s\n", opt->strarg, cl_strerror(ret));
                     ret = 1;
                     break;
                 }
             }
288057e9
             if ((opt = optget(opts, "BytecodeUnsigned"))->enabled) {
14a7c47b
                 dboptions |= CL_DB_BYTECODE_UNSIGNED;
                 logg("#Bytecode: Enabled support for unsigned bytecode.\n");
             }
 
288057e9
             if ((opt = optget(opts, "BytecodeMode"))->enabled) {
14a7c47b
                 enum bytecode_mode mode;
 
                 if (!strcmp(opt->strarg, "ForceJIT"))
                     mode = CL_BYTECODE_MODE_JIT;
288057e9
                 else if (!strcmp(opt->strarg, "ForceInterpreter"))
14a7c47b
                     mode = CL_BYTECODE_MODE_INTERPRETER;
288057e9
                 else if (!strcmp(opt->strarg, "Test"))
14a7c47b
                     mode = CL_BYTECODE_MODE_TEST;
                 else
                     mode = CL_BYTECODE_MODE_AUTO;
                 cl_engine_set_num(engine, CL_ENGINE_BYTECODE_MODE, mode);
             }
 
288057e9
             if ((opt = optget(opts, "BytecodeTimeout"))->enabled) {
14a7c47b
                 cl_engine_set_num(engine, CL_ENGINE_BYTECODE_TIMEOUT, opt->numarg);
             }
         } else {
             logg("#Bytecode support disabled.\n");
         }
3d53538b
 
288057e9
         if (optget(opts, "PhishingScanURLs")->enabled)
14a7c47b
             dboptions |= CL_DB_PHISHING_URLS;
         else
             logg("#Disabling URL based phishing detection.\n");
3d53538b
 
288057e9
         if (optget(opts, "DevACOnly")->enabled) {
14a7c47b
             logg("#Only using the A-C matcher.\n");
             cl_engine_set_num(engine, CL_ENGINE_AC_ONLY, 1);
         }
e3aaff8e
 
288057e9
         if ((opt = optget(opts, "DevACDepth"))->enabled) {
14a7c47b
             cl_engine_set_num(engine, CL_ENGINE_AC_MAXDEPTH, opt->numarg);
288057e9
             logg("#Max A-C depth set to %u\n", (unsigned int)opt->numarg);
14a7c47b
         }
5cc4cb86
 
288057e9
         if ((ret = cl_load(dbdir, engine, &sigs, dboptions))) {
14a7c47b
             logg("!%s\n", cl_strerror(ret));
             ret = 1;
             break;
         }
e3aaff8e
 
288057e9
         if ((ret = statinidir_th(dbdir))) {
5327ca42
             logg("!%s\n", cl_strerror(ret));
             ret = 1;
             break;
         }
 
14a7c47b
         if (optget(opts, "DisableCertCheck")->enabled)
5eaf0b32
             cl_engine_set_num(engine, CL_ENGINE_DISABLE_PE_CERTS, 1);
57358cc8
 
14a7c47b
         logg("#Loaded %u signatures.\n", sigs);
 
e492c653
         /* pcre engine limits - required for cl_engine_compile */
288057e9
         if ((opt = optget(opts, "PCREMatchLimit"))->active) {
             if ((ret = cl_engine_set_num(engine, CL_ENGINE_PCRE_MATCH_LIMIT, opt->numarg))) {
e492c653
                 logg("!cli_engine_set_num(PCREMatchLimit) failed: %s\n", cl_strerror(ret));
                 cl_engine_free(engine);
                 return 1;
             }
         }
 
288057e9
         if ((opt = optget(opts, "PCRERecMatchLimit"))->active) {
             if ((ret = cl_engine_set_num(engine, CL_ENGINE_PCRE_RECMATCH_LIMIT, opt->numarg))) {
e492c653
                 logg("!cli_engine_set_num(PCRERecMatchLimit) failed: %s\n", cl_strerror(ret));
                 cl_engine_free(engine);
                 return 1;
             }
         }
 
288057e9
         if ((ret = cl_engine_compile(engine)) != 0) {
14a7c47b
             logg("!Database initialization error: %s\n", cl_strerror(ret));
757cf211
             ret = 1;
             break;
         }
14a7c47b
 
288057e9
         if (tcpsock || num_fd > 0) {
8c241c57
             opt = optget(opts, "TCPAddr");
             if (opt->enabled) {
                 int breakout = 0;
 
                 while (opt && opt->strarg) {
                     char *ipaddr = (!strcmp(opt->strarg, "all") ? NULL : opt->strarg);
 
                     if (tcpserver(&lsockets, &nlsockets, ipaddr, opts) == -1) {
288057e9
                         ret      = 1;
8c241c57
                         breakout = 1;
                         break;
                     }
 
                     opt = opt->nextarg;
                 }
 
                 if (breakout)
                     break;
             } else {
                 if (tcpserver(&lsockets, &nlsockets, NULL, opts) == -1) {
                     ret = 1;
                     break;
                 }
14a7c47b
             }
         }
 #ifndef _WIN32
288057e9
         if (localsock && num_fd == 0) {
8c241c57
             int *t;
14a7c47b
             mode_t sock_mode, umsk = umask(0777); /* socket is created with 000 to avoid races */
8c241c57
 
             t = realloc(lsockets, sizeof(int) * (nlsockets + 1));
             if (!(t)) {
                 ret = 1;
                 break;
             }
             lsockets = t;
 
14a7c47b
             if ((lsockets[nlsockets] = localserver(opts)) == -1) {
                 ret = 1;
                 umask(umsk);
                 break;
             }
             umask(umsk); /* restore umask */
 
288057e9
             if (optget(opts, "LocalSocketGroup")->enabled) {
                 char *gname    = optget(opts, "LocalSocketGroup")->strarg, *end;
14a7c47b
                 gid_t sock_gid = strtol(gname, &end, 10);
 
288057e9
                 if (*end) {
14a7c47b
                     struct group *pgrp = getgrnam(gname);
 
288057e9
                     if (!pgrp) {
14a7c47b
                         logg("!Unknown group %s\n", gname);
                         ret = 1;
                         break;
                     }
 
                     sock_gid = pgrp->gr_gid;
                 }
288057e9
                 if (chown(optget(opts, "LocalSocket")->strarg, -1, sock_gid)) {
14a7c47b
                     logg("!Failed to change socket ownership to group %s\n", gname);
                     ret = 1;
                     break;
                 }
             }
288057e9
             if (optget(opts, "LocalSocketMode")->enabled) {
14a7c47b
                 char *end;
 
                 sock_mode = strtol(optget(opts, "LocalSocketMode")->strarg, &end, 8);
 
288057e9
                 if (*end) {
14a7c47b
                     logg("!Invalid LocalSocketMode %s\n", optget(opts, "LocalSocketMode")->strarg);
                     ret = 1;
                     break;
                 }
             } else {
                 sock_mode = 0777 /* & ~umsk*/; /* conservative default: umask was 0 in clamd < 0.96 */
             }
 
288057e9
             if (chmod(optget(opts, "LocalSocket")->strarg, sock_mode & 0666)) {
14a7c47b
                 logg("!Cannot set socket permission to %s\n", optget(opts, "LocalSocketMode")->strarg);
                 ret = 1;
                 break;
             }
 
             nlsockets++;
         }
 
b68375fd
         /* check for local sockets passed by systemd */
288057e9
         if (num_fd > 0) {
b68375fd
             int *t;
             t = realloc(lsockets, sizeof(int) * (nlsockets + 1));
             if (!(t)) {
                 ret = 1;
                 break;
             }
             lsockets = t;
 
             lsockets[nlsockets] = localserver(opts);
288057e9
             if (lsockets[nlsockets] == -1) {
b68375fd
                 ret = 1;
                 break;
288057e9
             } else if (lsockets[nlsockets] > 0) {
b68375fd
                 nlsockets++;
             }
         }
 
14a7c47b
         /* fork into background */
288057e9
         if (foreground == -1) {
             if (optget(opts, "Foreground")->enabled) {
b68375fd
                 foreground = 1;
288057e9
             } else {
b68375fd
                 foreground = 0;
             }
         }
288057e9
         if (foreground == 0) {
 #ifdef C_BSD
14a7c47b
             /* workaround for OpenBSD bug, see https://wwws.clamav.net/bugzilla/show_bug.cgi?id=885 */
288057e9
             for (ret = 0; (unsigned int)ret < nlsockets; ret++) {
14a7c47b
                 if (fcntl(lsockets[ret], F_SETFL, fcntl(lsockets[ret], F_GETFL) | O_NONBLOCK) == -1) {
                     logg("!fcntl for lsockets[] failed\n");
                     close(lsockets[ret]);
                     ret = 1;
                     break;
                 }
             }
9a223418
 #endif
14a7c47b
             gengine = engine;
             atexit(free_engine);
288057e9
             if (daemonize() == -1) {
14a7c47b
                 logg("!daemonize() failed: %s\n", strerror(errno));
                 ret = 1;
                 break;
             }
             gengine = NULL;
9a223418
 #ifdef C_BSD
288057e9
             for (ret = 0; (unsigned int)ret < nlsockets; ret++) {
14a7c47b
                 if (fcntl(lsockets[ret], F_SETFL, fcntl(lsockets[ret], F_GETFL) & ~O_NONBLOCK) == -1) {
                     logg("!fcntl for lsockets[] failed\n");
                     close(lsockets[ret]);
                     ret = 1;
                     break;
                 }
             }
9a223418
 #endif
288057e9
             if (!debug_mode)
                 if (chdir("/") == -1)
14a7c47b
                     logg("^Can't change current working directory to root\n");
         }
be4bf7f4
 #endif
e979398c
 
f0e1c2e6
         if (nlsockets == 0) {
             logg("!Not listening on any interfaces\n");
             ret = 1;
             break;
         }
 
14a7c47b
         ret = recvloop_th(lsockets, nlsockets, engine, dboptions, opts);
e3aaff8e
 
6e3256f4
     } while (0);
 
288057e9
     if (num_fd == 0) {
b68375fd
         logg("*Closing the main socket%s.\n", (nlsockets > 1) ? "s" : "");
6e3256f4
 
b68375fd
         for (i = 0; i < nlsockets; i++) {
             closesocket(lsockets[i]);
         }
b2354dc1
 #ifndef _WIN32
288057e9
         if (nlsockets && localsock) {
b68375fd
             opt = optget(opts, "LocalSocket");
14a7c47b
 
288057e9
             if (unlink(opt->strarg) == -1)
b68375fd
                 logg("!Can't unlink the socket file %s\n", opt->strarg);
             else
                 logg("Socket file removed.\n");
         }
6e3256f4
 #endif
b68375fd
     }
6e3256f4
 
e580b6a2
     free(lsockets);
 
9e431a95
     logg_close();
064b4a0c
     optfree(opts);
e3aaff8e
 
bd8603aa
     return ret;
e3aaff8e
 }