shared/misc.c
7b304dee
 /*
206dbaef
  *  Copyright (C) 2013-2020 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
52cddcbc
  *  Copyright (C) 2007-2013 Sourcefire, Inc.
086eab5c
  *
  *  Authors: Tomasz Kojm
7b304dee
  *
  *  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.
7b304dee
  *
  *  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.
7b304dee
  */
 
 #if HAVE_CONFIG_H
 #include "clamav-config.h"
 #endif
 
 #include <stdio.h>
63abd169
 #include <stdlib.h>
72fd33c8
 #ifdef HAVE_UNISTD_H
63abd169
 #include <unistd.h>
3e499d06
 #endif
7b304dee
 #include <string.h>
7c225c08
 #include <time.h>
63abd169
 #include <sys/types.h>
 #include <sys/stat.h>
4cd80898
 #ifndef _WIN32
e114b109
 #include <sys/socket.h>
ec62e185
 #include <pwd.h>
 #include <grp.h>
 #include <sys/types.h>
4cd80898
 #endif
c6f15a5f
 #include <dirent.h>
63abd169
 #include <fcntl.h>
7bbd5f7f
 #include <ctype.h>
c6f15a5f
 #include <errno.h>
7b304dee
 
9e20cdf6
 // libclamav
 #include "clamav.h"
 #include "cvd.h"
 #include "others.h" /* for cli_rmdirs() */
 #include "regex/regex.h"
 #include "version.h"
2b259453
 
9e20cdf6
 #include "optparser.h"
 #include "output.h"
 #include "misc.h"
3e499d06
 
5b168b50
 #include <signal.h>
 
 #ifndef WIN32
 #include <sys/wait.h>
 #endif
 
add738d2
 #ifndef REPO_VERSION
 #define REPO_VERSION "exported"
 #endif
 
 const char *get_version(void)
 {
72fd33c8
     if (!strncmp("devel-", VERSION, 6) && strcmp("exported", REPO_VERSION)) {
         return REPO_VERSION "" VERSION_SUFFIX;
     }
     /* it is a release, or we have nothing better */
     return VERSION "" VERSION_SUFFIX;
add738d2
 }
9e20cdf6
 
60ba0f86
 char *freshdbdir(void)
 {
72fd33c8
     struct cl_cvd *d1, *d2;
     struct optstruct *opts;
     const struct optstruct *opt;
     const char *dbdir;
     char *retdir;
60ba0f86
 
     /* try to find the most up-to-date db directory */
     dbdir = cl_retdbdir();
72fd33c8
     if ((opts = optparse(CONFDIR_FRESHCLAM, 0, NULL, 0, OPT_FRESHCLAM, 0, NULL))) {
         if ((opt = optget(opts, "DatabaseDirectory"))->enabled) {
             if (strcmp(dbdir, opt->strarg)) {
                 char *daily = (char *)malloc(strlen(opt->strarg) + strlen(dbdir) + 30);
                 if (daily == NULL) {
                     fprintf(stderr, "Unable to allocate memory for db directory...\n");
                     return NULL;
                 }
                 sprintf(daily, "%s" PATHSEP "daily.cvd", opt->strarg);
                 if (access(daily, R_OK))
                     sprintf(daily, "%s" PATHSEP "daily.cld", opt->strarg);
 
                 if (!access(daily, R_OK) && (d1 = cl_cvdhead(daily))) {
                     sprintf(daily, "%s" PATHSEP "daily.cvd", dbdir);
                     if (access(daily, R_OK))
                         sprintf(daily, "%s" PATHSEP "daily.cld", dbdir);
 
                     if (!access(daily, R_OK) && (d2 = cl_cvdhead(daily))) {
                         free(daily);
                         if (d1->version > d2->version)
                             dbdir = opt->strarg;
                         cl_cvdfree(d2);
                     } else {
                         free(daily);
                         dbdir = opt->strarg;
                     }
                     cl_cvdfree(d1);
                 } else {
                     free(daily);
                 }
             }
         }
60ba0f86
     }
 
     retdir = strdup(dbdir);
 
72fd33c8
     if (opts)
         optfree(opts);
60ba0f86
 
     return retdir;
 }
 
 void print_version(const char *dbdir)
 {
72fd33c8
     char *fdbdir = NULL, *path;
     const char *pt;
     struct cl_cvd *daily;
     time_t db_time;
     unsigned int db_version = 0;
 
     if (dbdir)
         pt = dbdir;
60ba0f86
     else
72fd33c8
         pt = fdbdir = freshdbdir();
60ba0f86
 
72fd33c8
     if (!pt) {
         printf("ClamAV %s\n", get_version());
         return;
60ba0f86
     }
 
72fd33c8
     if (!(path = malloc(strlen(pt) + 11))) {
         if (!dbdir)
             free(fdbdir);
         return;
60ba0f86
     }
 
72fd33c8
     sprintf(path, "%s" PATHSEP "daily.cvd", pt);
     if (!access(path, R_OK)) {
         daily = cl_cvdhead(path);
         if (daily) {
             db_version = daily->version;
             db_time    = daily->stime;
             cl_cvdfree(daily);
         }
60ba0f86
     }
 
72fd33c8
     sprintf(path, "%s" PATHSEP "daily.cld", pt);
     if (!access(path, R_OK)) {
         daily = cl_cvdhead(path);
         if (daily) {
             if (daily->version > db_version) {
                 db_version = daily->version;
                 db_time    = daily->stime;
             }
             cl_cvdfree(daily);
         }
60ba0f86
     }
 
72fd33c8
     if (!dbdir)
         free(fdbdir);
60ba0f86
 
72fd33c8
     if (db_version) {
         printf("ClamAV %s/%u/%s", get_version(), db_version, ctime(&db_time));
60ba0f86
     } else {
72fd33c8
         printf("ClamAV %s\n", get_version());
60ba0f86
     }
 
     free(path);
 }
 
 int check_flevel(void)
 {
72fd33c8
     if (cl_retflevel() < CL_FLEVEL) {
         fprintf(stderr, "ERROR: This tool requires libclamav with functionality level %u or higher (current f-level: %u)\n", CL_FLEVEL, cl_retflevel());
         return 1;
60ba0f86
     }
     return 0;
 }
 
c2b6681b
 const char *filelist(const struct optstruct *opts, int *err)
 {
72fd33c8
     static char buff[1025];
     static unsigned int cnt = 0;
     const struct optstruct *opt;
     static FILE *fs = NULL;
     size_t len;
 
     if (!cnt && (opt = optget(opts, "file-list"))->enabled) {
         if (!fs) {
             fs = fopen(opt->strarg, "r");
             if (!fs) {
                 fprintf(stderr, "ERROR: --file-list: Can't open file %s\n", opt->strarg);
                 if (err)
                     *err = 54;
                 return NULL;
             }
         }
 
         if (fgets(buff, 1024, fs)) {
             buff[1024] = 0;
             len        = strlen(buff);
             if (!len) {
                 fclose(fs);
                 return NULL;
             }
             len--;
             while (len && ((buff[len] == '\n') || (buff[len] == '\r')))
                 buff[len--] = '\0';
             return buff;
         } else {
             fclose(fs);
             return NULL;
         }
c2b6681b
     }
 
     return opts->filename ? opts->filename[cnt++] : NULL;
 }
 
63abd169
 int filecopy(const char *src, const char *dest)
 {
081f6473
 #ifdef _WIN32
     return (!CopyFileA(src, dest, 0));
 #elif defined(C_DARWIN)
72fd33c8
     pid_t pid;
63abd169
 
c8e6cded
     /* On Mac OS X use ditto and copy resource fork, too. */
72fd33c8
     switch (pid = fork()) {
         case -1:
             return -1;
         case 0:
             execl("/usr/bin/ditto", "ditto", src, dest, NULL);
             perror("execl(ditto)");
             break;
         default:
             wait(NULL);
             return 0;
63abd169
     }
 
c8e6cded
     return -1;
63abd169
 
afff80ef
 #else /* C_DARWIN */
     return cli_filecopy(src, dest);
63abd169
 #endif
 }
5fabe557
 
b88a29d6
 #ifndef _WIN32
 int close_std_descriptors()
 {
72fd33c8
     int fds[3], i;
a889f40e
 
587d344b
     fds[0] = open("/dev/null", O_RDONLY);
     fds[1] = open("/dev/null", O_WRONLY);
     fds[2] = open("/dev/null", O_WRONLY);
72fd33c8
     if (fds[0] == -1 || fds[1] == -1 || fds[2] == -1) {
         fputs("Can't open /dev/null\n", stderr);
         for (i = 0; i <= 2; i++)
             if (fds[i] != -1)
                 close(fds[i]);
         return -1;
587d344b
     }
a889f40e
 
72fd33c8
     for (i = 0; i <= 2; i++) {
         if (dup2(fds[i], i) == -1) {
             fprintf(stderr, "dup2(%d, %d) failed\n", fds[i], i); /* may not be printed */
             for (i = 0; i <= 2; i++)
                 if (fds[i] != -1)
                     close(fds[i]);
             return -1;
         }
a889f40e
     }
 
72fd33c8
     for (i = 0; i <= 2; i++)
         if (fds[i] > 2)
             close(fds[i]);
587d344b
 
5b168b50
     return 0;
 }
 
b88a29d6
 int daemonize_all_return(void)
 {
5b168b50
     pid_t pid;
 
587d344b
     pid = fork();
 
b88a29d6
     if (0 == pid) {
5b168b50
         setsid();
     }
     return pid;
 }
 
b88a29d6
 int daemonize(void)
 {
5b168b50
     int ret = 0;
587d344b
 
5b168b50
     ret = close_std_descriptors();
b88a29d6
     if (ret) {
5b168b50
         return ret;
     }
 
b88a29d6
     ret       = daemonize_all_return();
     pid_t pid = (pid_t)ret;
5b168b50
     /*parent process.*/
b88a29d6
     if (pid > 0) {
72fd33c8
         exit(0);
5b168b50
     }
 
     return pid;
 }
a889f40e
 
b88a29d6
 static void daemonize_child_initialized_handler(int sig)
 {
5b168b50
     (void)(sig);
     exit(0);
 }
 
ec62e185
 int daemonize_parent_wait(const char * const user, const char * const log_file)
b88a29d6
 {
5b168b50
     int daemonizePid = daemonize_all_return();
     if (daemonizePid == -1) {
         return -1;
b88a29d6
     } else if (daemonizePid) { //parent
5b168b50
         /* The parent will wait until either the child process
          * exits, or signals the parent that it's initialization is
          * complete.  If it exits, it is due to an error condition,
          * so the parent should exit with the same error code as the child.
          * If the child signals the parent that initialization is complete, it
          * the parent will exit from the signal handler (initDoneSignalHandler)
          * with exit code 0.
          */
         struct sigaction sig;
         memset(&sig, 0, sizeof(sig));
         sigemptyset(&(sig.sa_mask));
         sig.sa_handler = daemonize_child_initialized_handler;
 
b88a29d6
         if (0 != sigaction(SIGINT, &sig, NULL)) {
5b168b50
             perror("sigaction");
             return -1;
         }
 
ec62e185
         if (NULL != user){
             if (drop_privileges(user, log_file)){
                 return -1;
             }
         }
 
5b168b50
         int exitStatus;
         wait(&exitStatus);
b88a29d6
         if (WIFEXITED(exitStatus)) { //error
5b168b50
             exitStatus = WEXITSTATUS(exitStatus);
             exit(exitStatus);
         }
     }
587d344b
     return 0;
a889f40e
 }
f45d19ac
 
b88a29d6
 void daemonize_signal_parent(pid_t parentPid)
 {
5b168b50
     close_std_descriptors();
b88a29d6
     kill(parentPid, SIGINT);
5b168b50
 }
ec62e185
 
 int drop_privileges( const char * const user_name, const char * const log_file) {
     int ret = 1;
 
     /*This function is called in a bunch of places, and rather than change the error checking
      * in every function, we are just going to return success if there is no work to do.
      */
     if ((0 == geteuid()) && (NULL != user_name)){
         struct passwd *user = NULL;
 
         if ((user = getpwnam(user_name)) == NULL) {
             logg("^Can't get information about user %s.\n", user_name);
             fprintf(stderr, "ERROR: Can't get information about user %s.\n", user_name);
             goto done;
         }
 
 #ifdef HAVE_INITGROUPS
         if (initgroups(user_name, user->pw_gid)) {
             fprintf(stderr, "ERROR: initgroups() failed.\n");
             logg("^initgroups() failed.\n");
             goto done;
         }
 #elif HAVE_SETGROUPS
         if (setgroups(1, &user->pw_gid)) {
             fprintf(stderr, "ERROR: setgroups() failed.\n");
             logg("^setgroups() failed.\n");
             goto done;
         }
b88a29d6
 #endif
5b168b50
 
ec62e185
         /*Change ownership of the log file to the user we are going to switch to.*/
         if (NULL != log_file){
             int ret = lchown(log_file, user->pw_uid, user->pw_gid);
             if (ret){
                 fprintf(stderr, "ERROR: lchown to user '%s' failed on\n", user->pw_name);
                 fprintf(stderr, "log file '%s'.\n", log_file);
                 fprintf(stderr, "Error was '%s'\n", strerror(errno));
                 logg("^lchown to user '%s' failed on log file '%s'.  Error was '%s'\n", 
                         user->pw_name, log_file, strerror(errno));
                 goto done;
             }
         }
 
         if (setgid(user->pw_gid)) {
             fprintf(stderr, "ERROR: setgid(%d) failed.\n", (int)user->pw_gid);
             logg("^setgid(%d) failed.\n", (int)user->pw_gid);
             goto done;
         }
 
         if (setuid(user->pw_uid)) {
             fprintf(stderr, "ERROR: setuid(%d) failed.\n", (int)user->pw_uid);
             logg("^setuid(%d) failed.\n", (int)user->pw_uid);
             goto done;
         }
     }
     ret = 0;
 
 done:
     return ret;
 }
 #endif /*_WIN32*/
 
f45d19ac
 int match_regex(const char *filename, const char *pattern)
 {
72fd33c8
     regex_t reg;
     int match, flags = REG_EXTENDED | REG_NOSUB;
     char fname[513];
b2354dc1
 #ifdef _WIN32
72fd33c8
     flags |= REG_ICASE; /* case insensitive on Windows */
f45d19ac
 #endif
72fd33c8
     if (cli_regcomp(&reg, pattern, flags) != 0)
         return 2;
 
     if (pattern[strlen(pattern) - 1] == *PATHSEP) {
         snprintf(fname, 511, "%s" PATHSEP, filename);
         fname[512] = 0;
     } else {
         strncpy(fname, filename, 513);
         fname[512] = '\0';
     }
 
     match = (cli_regexec(&reg, fname, 0, NULL, 0) == REG_NOMATCH) ? 0 : 1;
     cli_regfree(&reg);
     return match;
f45d19ac
 }
7a997ac9
 
72fd33c8
 int cli_is_abspath(const char *path)
 {
11195c0b
 #ifdef _WIN32
     int len = strlen(path);
72c63093
     return (len > 2 && path[0] == '\\' && path[1] == '\\') || (len >= 2 && ((*path >= 'a' && *path <= 'z') || (*path >= 'A' && *path <= 'Z')) && path[1] == ':');
11195c0b
 #else
     return *path == '/';
 #endif
 }
4dccd075
 
 unsigned int countlines(const char *filename)
 {
72fd33c8
     FILE *fh;
     char buff[1024];
     unsigned int lines = 0;
4dccd075
 
72fd33c8
     if ((fh = fopen(filename, "r")) == NULL)
         return 0;
4dccd075
 
72fd33c8
     while (fgets(buff, sizeof(buff), fh)) {
         if (buff[0] == '#') continue;
         lines++;
4dccd075
     }
 
     fclose(fh);
     return lines;
 }