/*
 *  Copyright (C) 2002 - 2004 Tomasz Kojm <tkojm@clamav.net>
 *			      Trog <trog@clamav.net>
 *
 *  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.
 */

#if HAVE_CONFIG_H
#include "clamav-config.h"
#endif

#include <pthread.h>
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>

#include "server.h"
#include "thrmgr.h"
#include "session.h"
#include "defaults.h"
#include "clamuko.h"
#include "others.h"
#include "memory.h"
#include "shared.h"
#include "output.h"

#define BUFFSIZE 1024
#define FALSE (0)
#define TRUE (1)
#define NUMBER_OF_THREADS 1


int progexit = 0;
pthread_mutex_t exit_mutex;
int reload = 0;
pthread_mutex_t reload_mutex;
int sighup = 0;

typedef struct client_conn_tag {
    int sd;
    int options;
    const struct cfgstruct *copt;
    const struct cl_node *root;
    const struct cl_limits *limits;
    pid_t mainpid;
} client_conn_t;


void sighandler_th(int sig)
{
    switch(sig) {
	case SIGINT:
	case SIGTERM:
	    progexit = 1;
	    break;

	case SIGSEGV:
	    logg("Segmentation fault :-( Bye..\n");
	    _exit(11); /* probably not reached at all */
	    break; /* not reached */

	case SIGHUP:
	    sighup = 1;
	    break;

	case SIGUSR2:
	    reload = 1;
	    break;

	default:
	    break; /* Take no action on other signals - e.g. SIGPIPE */
    }
}

static struct cl_node *reload_db(struct cl_node *root, const struct cfgstruct *copt, int do_check)
{
	const char *dbdir;
	int virnum=0, retval;
	struct cfgstruct *cpt;
	static struct cl_stat *dbstat=NULL;


    if(do_check) {
	if(dbstat == NULL) {
	    logg("No stats for Database check - forcing reload\n");
	    return root;
	}

	if(cl_statchkdir(dbstat) == 1) {
	    logg("SelfCheck: Database modification detected. Forcing reload.\n");
	    return root;
	} else {
	    logg("SelfCheck: Database status OK.\n");
	    return NULL;
	}
    }

    /* release old structure */
    if(root) {
	cl_free(root);
	root = NULL;
    }

    if((cpt = cfgopt(copt, "DatabaseDirectory")) || (cpt = cfgopt(copt, "DataDirectory"))) {
	dbdir = cpt->strarg;
    } else {
	dbdir = cl_retdbdir();
    }
    logg("Reading databases from %s\n", dbdir);

    if(dbstat == NULL) {
	dbstat = (struct cl_stat *) mmalloc(sizeof(struct cl_stat));
    } else {
	cl_statfree(dbstat);
    }

    memset(dbstat, 0, sizeof(struct cl_stat));
    cl_statinidir(dbdir, dbstat);
    if((retval = cl_loaddbdir(dbdir, &root, &virnum))) {
	logg("!reload db failed: %s\n", cl_strerror(retval));
	exit(-1);
    }

    if(!root) {
	logg("!load db failed: %s\n", cl_strerror(retval));
	exit(-1);
    }

    if((retval = cl_build(root)) != 0) {
	logg("!Database initialization error: can't build engine: %s\n",
	cl_strerror(retval));
	exit(-1);
    }
    logg("Database correctly reloaded (%d viruses)\n", virnum);

    return root;
}

int acceptloop_th(struct cl_node *root, const struct cfgstruct *copt)
{
	int new_sd, max_threads, stdopt;
	unsigned int options = 0;
	threadpool_t *thr_pool;
	struct sigaction sigact;
	mode_t old_umask;
	struct cl_limits limits;
	pthread_attr_t thattr;
	sigset_t sigset;
	client_conn_t *client_conn;
	struct cfgstruct *cpt;
#ifdef HAVE_STRERROR_R
	char buff[BUFFSIZE + 1];
#endif
	unsigned int selfchk;
	time_t start_time, current_time;
	pid_t mainpid;
	int idletimeout;

#if defined(C_BIGSTACK) || defined(C_BSD)
        size_t stacksize;
#endif

#ifdef CLAMUKO
	pthread_t clamuko_pid[NUMBER_OF_THREADS];
	pthread_attr_t clamuko_attr;
	struct thrarg tharg[NUMBER_OF_THREADS]; /* shut up gcc */
#endif
	memset(&sigact, 0, sizeof(struct sigaction));

    /* save the PID */
    mainpid = getpid();
    if((cpt = cfgopt(copt, "PidFile"))) {
	    FILE *fd;
	old_umask = umask(0006);
	if((fd = fopen(cpt->strarg, "w")) == NULL) {
	    logg("!Can't save PID in file %s\n", cpt->strarg);
	} else {
	    fprintf(fd, "%d", (int) mainpid);
	    fclose(fd);
	}
	umask(old_umask);
    }

    logg("*Listening daemon: PID: %d\n", getpid());
    if((cpt = cfgopt(copt, "MaxThreads"))) {
	max_threads = cpt->numarg;
    } else {
	max_threads = CL_DEFAULT_MAXTHREADS;
    }

    if(cfgopt(copt, "DisableDefaultScanOptions")) {
	logg("RECOMMENDED OPTIONS DISABLED.\n");
	stdopt = 0;
    } else {
	options |= CL_SCAN_STDOPT;
	stdopt = 1;
    }

    if(stdopt || cfgopt(copt, "ScanArchive") || cfgopt(copt, "ClamukoScanArchive")) {

	/* set up limits */
	memset(&limits, 0, sizeof(struct cl_limits));

	if((cpt = cfgopt(copt, "ArchiveMaxFileSize"))) {
	    if((limits.maxfilesize = cpt->numarg)) {
		logg("Archive: Archived file size limit set to %d bytes.\n", limits.maxfilesize);
	    } else {
		logg("^Archive: File size limit protection disabled.\n");
	    }
	} else {
	    limits.maxfilesize = 10485760;
	    logg("Archive: Archived file size limit set to %d bytes.\n", limits.maxfilesize);
	}

	if((cpt = cfgopt(copt, "ArchiveMaxRecursion"))) {
	    if((limits.maxreclevel = cpt->numarg)) {
		logg("Archive: Recursion level limit set to %d.\n", limits.maxreclevel);
	    } else {
		logg("^Archive: Recursion level limit protection disabled.\n");
	    }
	} else {
	    limits.maxreclevel = 8;
	    logg("Archive: Recursion level limit set to %d.\n", limits.maxreclevel);
	}

	if((cpt = cfgopt(copt, "ArchiveMaxFiles"))) {
	    if((limits.maxfiles = cpt->numarg)) {
		logg("Archive: Files limit set to %d.\n", limits.maxfiles);
	    } else {
		logg("^Archive: Files limit protection disabled.\n");
	    }
	} else {
	    limits.maxfiles = 1000;
	    logg("Archive: Files limit set to %d.\n", limits.maxfiles);
	}

	if((cpt = cfgopt(copt, "ArchiveMaxCompressionRatio"))) {
	    if((limits.maxratio = cpt->numarg)) {
		logg("Archive: Compression ratio limit set to %d.\n", limits.maxratio);
	    } else {
		logg("^Archive: Compression ratio limit disabled.\n");
	    }
	} else {
	    limits.maxratio = 250;
	    logg("Archive: Compression ratio limit set to %d.\n", limits.maxratio);
	}

	if(cfgopt(copt, "ArchiveLimitMemoryUsage")) {
	    limits.archivememlim = 1;
	    logg("Archive: Limited memory usage.\n");
	} else {
	    limits.archivememlim = 0;
	}

    }

    if(stdopt || cfgopt(copt, "ScanArchive")) {
	logg("Archive support enabled.\n");
	options |= CL_SCAN_ARCHIVE;

// 	if(cfgopt(copt, "ScanRAR")) {
// 	    logg("Archive: RAR support enabled.\n");
// 	} else {
// 	    logg("Archive: RAR support disabled.\n");
// 	    options |= CL_SCAN_DISABLERAR;
// 	}

	if(cfgopt(copt, "ArchiveBlockEncrypted")) {
	    logg("Archive: Blocking encrypted archives.\n");
	    options |= CL_SCAN_BLOCKENCRYPTED;
	}

	if(cfgopt(copt, "ArchiveBlockMax")) {
	    logg("Archive: Blocking archives that exceed limits.\n");
	    options |= CL_SCAN_BLOCKMAX;
	}

    } else {
	logg("Archive support disabled.\n");
    }

    if(stdopt || cfgopt(copt, "ScanPE")) {
	logg("Portable Executable support enabled.\n");
	options |= CL_SCAN_PE;

	if(cfgopt(copt, "DetectBrokenExecutables")) {
	    logg("Detection of broken executables enabled.\n");
	    options |= CL_SCAN_BLOCKBROKEN;
	}

    } else {
	logg("Portable Executable support disabled.\n");
    }

    if(stdopt || cfgopt(copt, "ScanMail")) {
	logg("Mail files support enabled.\n");
	options |= CL_SCAN_MAIL;

	if(cfgopt(copt, "MailFollowURLs")) {
	    logg("Mail: URL scanning enabled.\n");
	    options |= CL_SCAN_MAILURL;
	}

    } else {
	logg("Mail files support disabled.\n");
    }

    if(stdopt || cfgopt(copt, "ScanOLE2")) {
	logg("OLE2 support enabled.\n");
	options |= CL_SCAN_OLE2;
    } else {
	logg("OLE2 support disabled.\n");
    }

    if(stdopt || cfgopt(copt, "ScanHTML")) {
	logg("HTML support enabled.\n");
	options |= CL_SCAN_HTML;
    } else {
	logg("HTML support disabled.\n");
    }

    if((cpt = cfgopt(copt, "SelfCheck"))) {
	selfchk = cpt->numarg;
    } else {
	selfchk = CL_DEFAULT_SELFCHECK;
    }

    if(!selfchk) {
	logg("Self checking disabled.\n");
    } else {
	logg("Self checking every %d seconds.\n", selfchk);
    }


    if(cfgopt(copt, "ClamukoScanOnLine") || cfgopt(copt, "ClamukoScanOnAccess"))
#ifdef CLAMUKO
    {
    
	int i;
	for (i=0 ; i<NUMBER_OF_THREADS ; i++)
	{
		pthread_attr_init(&clamuko_attr);
		pthread_attr_setdetachstate(&clamuko_attr, PTHREAD_CREATE_JOINABLE);
		
	
	
		//tharg[i] = (struct thrarg *) mmalloc(sizeof(struct thrarg));
		tharg[i].copt = copt;
		tharg[i].root = root;
		tharg[i].limits = &limits;
		tharg[i].options = options;
		tharg[i].pid = i;
	
		pthread_create(&(clamuko_pid[i]), &clamuko_attr, clamukoth, &(tharg[i]));
/*
		/* set the id for the thread */
//		id[i].thread_id = i;

		/* set argc,argv for the thread */
//		id[i].argc = argc;
//		id[i].argv = argv;

		/* create the thread */
//		pthread_create(&(tid[i]), NULL, main_loop, &(id[i]));

	}
    	

    }
#else
	logg("Clamuko is not available.\n");
#endif

    logg("WARNING: Reached here.\n");

#ifdef CLAMUKO
    if(cfgopt(copt, "ClamukoScanOnLine") || cfgopt(copt, "ClamukoScanOnAccess")) {
	logg("Stopping Clamuko.\n");
	
	int i;	
	for (i=0 ; i<NUMBER_OF_THREADS ; i++)
	{
		/* wait for the thread to finish */
		//pthread_join(tid[i], NULL);
		//pthread_kill(clamuko_pid[i], SIGUSR1);
		pthread_join(clamuko_pid[i], NULL);

	}

/*	pthread_kill(clamuko_pid, SIGUSR1);
	pthread_join(clamuko_pid, NULL);*/
    }
#endif

    if((cpt = cfgopt(copt, "PidFile"))) {
	if(unlink(cpt->strarg) == -1)
	    logg("!Can't unlink the pid file %s\n", cpt->strarg);
	else
	    logg("Pid file removed.\n");
    }

    logg("Exiting (clean)\n");
    time(&current_time);
    logg("--- Stopped at %s", ctime(&current_time));

    return 0;
}
