示例#1
0
function CheckCMDLine()
{
    $unix = new unix();
    $PID_FILE = "/etc/artica-postfix/pids/" . basename(__FILE__) . ".pid";
    $pid = $unix->get_pid_from_file($PID_FILE);
    if ($unix->process_exists($pid)) {
        return;
    }
    @file_put_contents($PID_FILE, getmypid());
    if (system_is_overloaded()) {
        die;
    }
    $sock = new sockets();
    $ips = unserialize(base64_decode($sock->GET_INFO("RBLCheckIPList")));
    if (count($ips) > 0) {
        if ($GLOBALS["VERBOSE"]) {
            echo count($ips) . " elements to check\n";
        }
        if (is_array($ips)) {
            while (list($num, $ip) = each($ips)) {
                if ($GLOBALS["VERBOSE"]) {
                    echo "{$ip} element...\n";
                }
                ChecksDNSBL($ip, false, true);
            }
            ChecksDNSBL();
            return;
        }
    }
    ChecksDNSBL();
}
示例#2
0
function check()
{
    $EnablePhileSight = GET_INFO_DAEMON("EnablePhileSight");
    if ($EnablePhileSight == null) {
        $EnablePhileSight = 0;
    }
    if ($EnablePhileSight == 0) {
        writelogs("feature disabled, aborting...", __FUNCTION__, __FILE__, __LINE__);
        die;
    }
    if (system_is_overloaded()) {
        writelogs("System overloaded, aborting this feature for the moment", __FUNCTION__, __FILE__, __LINE__);
        die;
    }
    @mkdir("/opt/artica/philesight");
    $unix = new unix();
    $min = $unix->file_time_min("/opt/artica/philesight/database.db");
    $sock = new sockets();
    $rr = $sock->GET_INFO("PhileSizeRefreshEach");
    if ($rr == null) {
        $rr = 120;
    }
    if ($rr == "disable") {
        die;
    }
    writelogs("/opt/artica/philesight/database.db = {$min} minutes, {$rr} minutes to run", __FUNCTION__, __FILE__, __LINE__);
    if ($min >= $rr) {
        run();
    }
}
function purge()
{
    $unix = new unix();
    $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid";
    $pidtime = "/etc/artica-postfix/pids/exec.suricata.hourly.purge.time";
    $pid = $unix->get_pid_from_file($pidfile);
    if ($unix->process_exists($pid, basename(__FILE__))) {
        $time = $unix->PROCCESS_TIME_MIN($pid);
        echo "Starting......: " . date("H:i:s") . " [INIT]: Already Artica task running PID {$pid} since {$time}mn\n";
        return;
    }
    @file_put_contents($pidfile, getmypid());
    if (system_is_overloaded()) {
        return;
    }
    $timeExec = $unix->file_time_min($pidtime);
    if ($timeExec < 1440) {
        return;
    }
    @unlink($pidtime);
    @file_put_contents($pidtime, time());
    $q = new postgres_sql();
    $sock = new sockets();
    $SuricataPurge = intval($sock->GET_INFO("SuricataPurge"));
    if ($SuricataPurge == 0) {
        $SuricataPurge = 15;
    }
    $q->QUERY_SQL("DELETE FROM suricata_events WHERE zdate < NOW() - INTERVAL '{$SuricataPurge} days'");
}
function detect_kernels()
{
    $unix = new unix();
    if (!$GLOBALS["VERBOSE"]) {
        if (is_file("/usr/share/artica-postfix/ressources/logs/kernel.lst")) {
            if ($unix->file_time_min("/usr/share/artica-postfix/ressources/logs/kernel.lst") < 360) {
                die;
            }
        }
    }
    $users = new usersMenus();
    if ($users->LinuxDistriCode != "DEBIAN" && $users->LinuxDistriCode != "UBUNTU") {
        die;
    }
    $unix = new unix();
    $apt_cache = $unix->find_program("apt-cache");
    if ($apt_cache == null) {
        echo "Could not find apt-cache\n";
        die;
    }
    if (system_is_overloaded(basename(__FILE__))) {
        $unix->send_email_events("apt-cache aborted, system is overloaded..", "will restart analyzis in next cycle", "system");
        die;
    }
    echo "{$apt_cache} search linux-image\n";
    exec("{$apt_cache} search linux-image", $results);
    while (list($num, $val) = each($results)) {
        if (preg_match("#linux-image-([0-9\\.]+)-([0-9]+)-(.+?)\\s+-\\s+(.+?)\$#", $val, $re)) {
            $array["DPKG"][] = array("VERSION" => $re[1], "BUILD" => $re[2], "ARCH" => $re[3], "INFOS" => $re[4], "PACKAGE" => "linux-image-{$re[1]}-{$re[2]}-{$re[3]}", "FULL_VERSION" => "{$re[1]}-{$re[2]}-{$re[3]}");
        }
    }
    $array["INFOS"] = CpuFamilyInfos();
    @file_put_contents("/usr/share/artica-postfix/ressources/logs/kernel.lst", base64_encode(serialize($array)));
}
示例#5
0
function ParseAllcontacts()
{
    $unix = new unix();
    $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid";
    $pidtime = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".time";
    $pid = @file_get_contents($pidfile);
    if ($unix->process_exists($pid)) {
        return;
    }
    @file_put_contents($pidfile, getmypid());
    if ($unix->file_time_min($pidtime) < 120) {
        return;
    }
    @file_put_contents($pidtime, time());
    $ldap = new clladp();
    $suffix = $ldap->suffix;
    $arr = array("uid");
    $sr = @ldap_search($ldap->ldap_connection, "dc=organizations,{$suffix}", '(objectclass=userAccount)', $arr);
    if ($sr) {
        $hash = ldap_get_entries($ldap->ldap_connection, $sr);
        for ($i = 0; $i < $hash["count"]; $i++) {
            ParseContacts($hash[$i]["uid"][0]);
            if (system_is_overloaded(dirname(__FILE__))) {
                $unix->send_email_events(basename(__FILE__) . " Overloaded aborting task", "Zarafa contacts importation has been canceled due to overloaded system", "mailbox");
                return;
            }
            sleep(1);
        }
    }
}
function importActivedirectoryusers()
{
    $sock = new sockets();
    $EnableKerbAuth = $sock->GET_INFO("EnableKerbAuth");
    if (!is_numeric($EnableKerbAuth)) {
        $EnableKerbAuth = 0;
    }
    if ($EnableKerbAuth == 0) {
        return;
    }
    $unix = new unix();
    $user = new settings_inc();
    $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . ".pid";
    $pidTime = "/etc/artica-postfix/pids/" . basename(__FILE__) . ".time";
    $pid = $unix->get_pid_from_file($pidfile);
    if ($unix->process_exists($pid, basename(__FILE__))) {
        WriteMyLogs("Process {$pid} already exists", __FUNCTION__, __FILE__, __LINE__);
        return;
    }
    if (system_is_overloaded(basename(__FILE__))) {
        WriteMyLogs("Overloaded system, aborting", __FUNCTION__, __FILE__, __LINE__);
        return;
    }
    @file_put_contents($pidfile, getmypid());
    $TImeStamp = $unix->file_time_min($pidTime);
    if (!$GLOBALS["FORCE"]) {
        if ($TImeStamp < 20) {
            WriteMyLogs("Need 20mn, current={$TImeStamp}Mn executed by:{$GLOBALS["EXECUTOR"]} Params:{$GLOBALS["PARAMS"]}", __FUNCTION__, __FILE__, __LINE__);
            return;
        }
    }
    @unlink($pidTime);
    @file_put_contents($pidTime, time());
    $netbin = $unix->LOCATE_NET_BIN_PATH();
    $usermod = $unix->find_program("usermod");
    $chmod = $unix->find_program("chmod");
    if (!is_file($netbin)) {
        WriteMyLogs("net no such binary, aborting", __FUNCTION__, __FILE__, __LINE__);
        return;
    }
    if (is_dir("/var/run/samba/winbindd_privileged")) {
        shell_exec("{$usermod} -G winbindd_priv squid >/dev/null 2>&1");
        shell_exec("{$chmod} 0750 /var/run/samba/winbindd_privileged/ >/dev/null 2>&1");
    }
    $array = unserialize(base64_decode($sock->GET_INFO("KerbAuthInfos")));
    $domainUp = strtoupper($array["WINDOWS_DNS_SUFFIX"]);
    $domain_lower = strtolower($array["WINDOWS_DNS_SUFFIX"]);
    $adminpassword = $array["WINDOWS_SERVER_PASS"];
    $adminpassword = $unix->shellEscapeChars($adminpassword);
    $adminname = $array["WINDOWS_SERVER_ADMIN"];
    $ad_server = $array["WINDOWS_SERVER_NETBIOSNAME"];
    $GLOBALS["AUTHCMD"] = " -U {$adminname}%{$adminpassword}";
    getNetInfos();
    if (!isset($GLOBALS["LDAP_HOST"])) {
        WriteMyLogs("Unable to get ldap infos, aborting", __FUNCTION__, __FILE__, __LINE__);
        return;
    }
    GetUsersArray();
}
示例#7
0
function start_hour()
{
    $TimeFile = "/etc/artica-postfix/pids/" . basename(__FILE__) . ".time";
    $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . ".pid";
    $unix = new unix();
    $sock = new sockets();
    if (system_is_overloaded(basename(__FILE__))) {
        return;
    }
    $pid = @file_get_contents($pidfile);
    if ($pid < 100) {
        $pid = null;
    }
    if ($unix->process_exists($pid, basename(__FILE__))) {
        $timepid = $unix->PROCCESS_TIME_MIN($pid);
        if ($GLOBALS["VERBOSE"]) {
            echo "{$pid} already executed since {$timepid}Mn\n";
        }
        if (!$GLOBALS["FORCE"]) {
            if ($timepid < 14) {
                return;
            }
            $kill = $unix->find_program("kill");
            unix_system_kill_force($pid);
        }
    }
    @unlink($TimeFile);
    @file_put_contents($TimeFile, time());
    $hostname = $unix->hostname_g();
    $today = date("Y-m-d") . " 00:00:00";
    $postgres = new postgres_sql();
    $results = $postgres->QUERY_SQL("select date_trunc('H',zdate) + (round(extract('minute' from zdate)/15)*15) * '1 minute'::interval as time, sum(rx) as rx, sum(tx) as tx,eth from access_log WHERE proxyname='{$hostname}' AND zdate >'{$today}' group by time,eth");
    $c = 0;
    $f = array();
    while ($ligne = @pg_fetch_assoc($results)) {
        $time = $ligne["time"];
        $ETH = $ligne["eth"];
        if ($ETH == "lo") {
            continue;
        }
        $RX = $ligne["rx"];
        $TX = $ligne["tx"];
        $f[] = "('{$time}','{$ETH}','{$RX}','{$TX}')";
    }
    if (count($f) == 0) {
        return;
    }
    $q = new mysql();
    if ($q->TABLE_EXISTS("RXTX_HOUR", "artica_events")) {
        $q->QUERY_SQL("TRUNCATE TABLE `RXTX_HOUR`", "artica_events");
    }
    $sql = "CREATE TABLE IF NOT EXISTS `RXTX_HOUR`\n\t(`ZDATE` DATETIME,\n\t`RX` INT UNSIGNED NOT NULL DEFAULT 1,\n\t`TX` INT UNSIGNED NOT NULL DEFAULT 1,\n\t`ETH` VARCHAR(60),\n\tKEY `ZDATE`(`ZDATE`),\n\tKEY `RX`(`RX`),\n\tKEY `TX`(`TX`),\n\tKEY `ETH`(`ETH`) )  ENGINE = MYISAM;";
    $q->QUERY_SQL($sql, "artica_events");
    if (!$q->ok) {
        return;
    }
    $q->QUERY_SQL("INSERT IGNORE INTO RXTX_HOUR (ZDATE,ETH,RX,TX) VALUES " . @implode(",", $f), "artica_events");
    start_week();
}
示例#8
0
function parse_logs()
{
    $unix = new unix();
    $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid";
    $pidTime = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".time";
    if (!$GLOBALS["VERBOSE"]) {
        if ($unix->file_time_min($pidTime) < 45) {
            return;
        }
    }
    $pid = $unix->get_pid_from_file($pidfile);
    if ($unix->process_exists($pid, basename(__FILE__))) {
        $time = $unix->PROCCESS_TIME_MIN($pid);
        return;
    }
    @file_put_contents($pidfile, getmypid());
    @unlink($pidTime);
    @file_put_contents($pidTime, time());
    $sock = new sockets();
    $EnableNginxStats = $sock->GET_INFO("EnableNginxStats");
    if (!is_numeric($EnableNginxStats)) {
        $EnableNginxStats = 0;
    }
    if ($EnableNginxStats == 0) {
        return;
    }
    if (system_is_overloaded(basename(__FILE__))) {
        events("Overloaded system: {$GLOBALS["SYSTEM_INTERNAL_LOAD"]} aborting", __FUNCTION__, __LINE__);
        return;
    }
    $nice = EXEC_NICE();
    $sock = new sockets();
    $kill = $unix->find_program("kill");
    $NginxWorkLogsDir = $sock->GET_INFO("NginxWorkLogsDir");
    if ($NginxWorkLogsDir == null) {
        $NginxWorkLogsDir = "/home/nginx/logsWork";
    }
    $sys = new mysql_storelogs();
    $files = $unix->DirFiles($NginxWorkLogsDir, "-([0-9\\-]+)\\.log");
    while (list($filename, $line) = each($files)) {
        if (!preg_match("#^(.+?)-[0-9]+-[0-9]+-[0-9]+-[0-9]+\\.log\$#", $filename, $re)) {
            if ($GLOBALS["VERBOSE"]) {
                echo "{$filename}, skip\n";
            }
            continue;
        }
        $servername = $re[1];
        $fullpath = "{$NginxWorkLogsDir}/{$filename}";
        ParseFile($servername, $fullpath);
    }
    $php = $unix->LOCATE_PHP5_BIN();
    $nohup = $unix->find_program("nohup");
    shell_exec("{$nohup} {$php} " . __FILE__ . " --hosts >/dev/null 2>&1 &");
    shell_exec("{$nohup} {$php} " . dirname(__FILE__) . "/exec.nginx-stats-day.php >/dev/null 2>&1 &");
}
function ScanFoldders()
{
    $sock = new sockets();
    $unix = new unix();
    $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid";
    $timefile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".time";
    $pid = file_get_contents("{$pidfile}");
    if ($GLOBALS["VERBOSE"]) {
        echo "{$timefile}\n";
    }
    if (system_is_overloaded(basename(__FILE__))) {
        die;
    }
    if ($unix->process_exists($pid, basename(__FILE__))) {
        $timeMin = $unix->PROCCESS_TIME_MIN($pid);
        if ($timeMin > 240) {
            system_admin_events("Too many TTL, {$pid} will be killed", __FUNCTION__, __FILE__, __LINE__, "logrotate");
            $kill = $unix->find_program("kill");
            unix_system_kill_force($pid);
        } else {
            die;
        }
    }
    if (!$GLOBALS["FORCE"]) {
        $TimeExec = $unix->file_time_min($timefile);
        if ($TimeExec < 240) {
            return;
        }
    }
    @unlink($timefile);
    @file_put_contents($timefile, time());
    $LogRotatePath = $sock->GET_INFO("LogRotatePath");
    $SystemLogsPath = $sock->GET_INFO("SystemLogsPath");
    $BackupMaxDaysDir = $sock->GET_INFO("BackupMaxDaysDir");
    $maillogStoragePath = trim(@file_get_contents("/etc/artica-postfix/settings/Daemons/maillogStoragePath"));
    if ($GLOBALS["VERBOSE"]) {
        echo "Starting Main\n";
    }
    $q = new mysql();
    $q->QUERY_SQL("DROP TABLE `sysstorestatus`", "artica_events");
    $sql = "CREATE TABLE IF NOT EXISTS `sysstorestatus` (\n\t\t\t  `filepath` VARCHAR(255) NOT NULL,\n\t\t\t  `filesize`  BIGINT UNSIGNED NOT NULL,\n\t\t\t  `zDate` DATETIME,\n\t\t\t  PRIMARY KEY (`filepath`),\n\t\t\t  KEY `zDate` (`zDate`),\n\t\t\t  KEY `filesize` (`filesize`)\n\t\t\n\t\t\t)";
    $q->QUERY_SQL($sql, "artica_events");
    if (!$q->ok) {
        echo $q->mysql_error;
        return;
    }
    ScanThis("/home/postfix/maillog");
    ScanThis("/home/logrotate");
    ScanThis("/home/logrotate_backup");
    ScanThis("/home/logs-backup");
    ScanThis("/home/backup/postfix");
    ScanThis($LogRotatePath);
    ScanThis($SystemLogsPath);
    ScanThis($maillogStoragePath);
}
示例#10
0
function update()
{
    if (system_is_overloaded()) {
        return;
    }
    $unix = new unix();
    $sock = new sockets();
    $pidfile = "/etc/artica-postfix/pids/exec.ipblock.php.update.pid";
    $pidtime = "/etc/artica-postfix/pids/exec.ipblock.php.update.time";
    $pid = @file_get_contents($pidfile);
    if (!$GLOBALS["FORCE"]) {
        if ($unix->process_exists($pid)) {
            echo "Already running pid {$pid}\n";
            return;
        }
    }
    include_once dirname(__FILE__) . '/ressources/class.ccurl.inc';
    if (!is_file($pidtime)) {
        @file_put_contents($pidtime, time());
    }
    if (!$GLOBALS["FORCE"]) {
        if ($unix->file_time_min($pidtime) > 720) {
            @unlink($pidtime);
            @file_put_contents($pidtime, time());
            return;
        }
    }
    @file_put_contents($pidfile, getmypid());
    $EnableIpBlocks = intval($sock->GET_INFO("EnableIpBlocks"));
    if ($EnableIpBlocks == 0) {
        return;
    }
    $DIR_TEMP = $unix->TEMP_DIR();
    $curl = new ccurl("http://www.ipdeny.com/ipblocks/data/countries/all-zones.tar.gz");
    if (!$curl->GetFile("{$DIR_TEMP}/all-zones.tar.gz")) {
        system_admin_events(0, "Fatal, Unable to download all-zones.tar.gz from ipdeny.com", __FILE__, __LINE__);
        return;
    }
    $OldMd5 = $sock->GET_INFO("IpBlocksMD5");
    $md5File = md5_file("{$DIR_TEMP}/all-zones.tar.gz");
    if ($md5File == $OldMd5) {
        ipblocks();
        return;
    }
    $tar = $unix->find_program("tar");
    @mkdir("/home/artica/ipblocks", 0755, true);
    shell_exec("{$tar} xf {$DIR_TEMP}/all-zones.tar.gz -C  /home/artica/ipblocks/");
    if (ipblocks()) {
        $sock->SET_INFO("IpBlocksMD5", "{$md5File}");
        system_admin_events(0, "Restarting Firewall in order to refresh countries blocking");
    }
}
示例#11
0
function scan()
{
    if (system_is_overloaded(basename(__FILE__))) {
        apache_admin_mysql(0, "Overloaded system, retry next time....", null, __FILE__, __LINE__);
        return;
    }
    $pidtime = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".time";
    $pidFile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid";
    $unix = new unix();
    $pid = $unix->get_pid_from_file($pidFile);
    if ($unix->process_exists($pid)) {
        events("A process, {$pid} Already exists...");
        return;
    }
    $GLOBALS["MYHOSTNAME_PROXY"] = $unix->hostname_g();
    @file_put_contents($pidFile, getmypid());
    $time = $unix->file_time_min($pidtime);
    if (!$GLOBALS["VERBOSE"]) {
        if ($time < 5) {
            events("{$time}mn, require minimal 5mn");
            return;
        }
    }
    $q = new mysql_squid_builder();
    $q->QUERY_SQL("CREATE TABLE IF NOT EXISTS `dashboard_apache_sizes` ( `TIME` DATETIME,\n\t\t\t`zmd5` VARCHAR(90) NOT NULL PRIMARY KEY,\n\t\t\t`SITENAME` VARCHAR(128),\n\t\t\t`SIZE` BIGINT UNSIGNED, `RQS` BIGINT UNSIGNED,\n\t\t\tKEY `TIME` (`TIME`),\n\t\t\tKEY `SIZE` (`SIZE`),\n\t\t\tKEY `RQS` (`RQS`)\n\t\t\t) ENGINE=MYISAM;");
    if (!$q->ok) {
        apache_admin_mysql(0, "Fatal MySQL error", $q->mysql_error, __FILE__, __LINE__);
        return;
    }
    if (!is_file("/home/apache/artica-stats/requests.log")) {
        echo "/home/apache/artica-stats/requests.log no such file...\n";
        return;
    }
    @mkdir("/home/apache/artica-stats/works", 0755, true);
    if (is_file("/home/apache/artica-stats/works/apache.log")) {
        echo "Parse /home/apache/artica-stats/works/apache.log\n";
        Parse("/home/apache/artica-stats/works/apache.log");
        return;
    }
    if (!@copy("/home/apache/artica-stats/requests.log", "/home/apache/artica-stats/works/apache.log")) {
        echo "Copy failed\n";
        return;
    }
    if (!is_file("/home/apache/artica-stats/works/apache.log")) {
        echo "/home/apache/artica-stats/works/apache.log no such file...\n";
        return;
    }
    @unlink("/home/apache/artica-stats/requests.log");
    echo "Parse /home/apache/artica-stats/works/apache.log\n";
    Parse("/home/apache/artica-stats/works/apache.log");
    CLEAN_MYSQL();
}
示例#12
0
function launch_tests()
{
    $unix = new unix();
    $php = $unix->LOCATE_PHP5_BIN();
    $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid";
    $pid = $unix->get_pid_from_file($pidfile);
    if ($unix->process_exists($pid, basename(__FILE__))) {
        return;
    }
    if (system_is_overloaded(basename(__FILE__))) {
        system_admin_events("Overloaded, aborting task...", __FUNCTION__, __FILE__, __LINE__, "system");
        $unix->THREAD_COMMAND_SET("{$php} " . __FILE__);
        return;
    }
    @file_put_contents($pidfile, getmypid());
    $datafile = "/etc/artica-postfix/settings/Daemons/HdparmInfos";
    writelogs("Testing hard drives ({$datafile})", __FUNCTION__, __FILE__, __LINE__);
    $timenum = file_time_min($datafile);
    if (is_file($datafile)) {
        if (file_time_min($datafile) < 61) {
            writelogs("{$timenum}Mn executed, waiting 60Mn", __FUNCTION__, __FILE__, __LINE__);
            die;
        }
    }
    if ($GLOBALS["FIND_HDPARM"] == null) {
        writelogs("Unable to stat 'hdparm'", __FUNCTION__, __FILE__, __LINE__);
        die;
    }
    $disks = GetDisks();
    if (!is_array($disks)) {
        return null;
    }
    while (list($index, $line) = each($disks)) {
        unset($results);
        exec("{$GLOBALS["FIND_HDPARM"]} -t {$index}", $results);
        while (list($num, $line_result) = each($results)) {
            if (preg_match("#=\\s+([0-9\\.]+)\\s+MB\\/sec\$#", $line_result, $re)) {
                if (preg_match("#.+?\\/(.+)\$#", $index, $ri)) {
                    system_admin_events("{$ri[1]}:{$re[1]}MB/sec", __FUNCTION__, __FILE__, __LINE__, "system");
                    writelogs("testing disk {$ri[1]}:{$re[1]}MB/sec...", __FUNCTION__, __FILE__, __LINE__);
                    $array[$ri[1]] = $re[1];
                }
            }
        }
    }
    @unlink($datafile);
    @file_put_contents($datafile, base64_encode(serialize($array)));
    if (!is_file($datafile)) {
        writelogs("{$datafile} no such file or directory", __FUNCTION__, __FILE__, __LINE__);
    }
}
function parseQueue()
{
    $unix = new unix();
    $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid";
    $pid = $unix->get_pid_from_file($pidfile);
    $sock = new sockets();
    if ($unix->process_exists($pid, basename(__FILE__))) {
        $pidTime = $unix->PROCCESS_TIME_MIN($pid);
        events("Already process PID: {$pid} running since {$pidTime} minutes", __FUNCTION__, __FILE__, __LINE__, "postfix-stats");
        return;
    }
    @file_put_contents($pidfile, getmypid());
    if (system_is_overloaded(basename(__FILE__))) {
        events("Overloaded system, aborting", __FUNCTION__, __FILE__, __LINE__, "postfix-stats");
        return;
    }
    $EnableArticaSMTPStatistics = $sock->GET_INFO("EnableArticaSMTPStatistics");
    if (!is_numeric($EnableArticaSMTPStatistics)) {
        $EnableArticaSMTPStatistics = 0;
    }
    $directory = "/var/log/artica-mail";
    if (!is_dir($directory)) {
        return;
    }
    if (!($handle = @opendir($directory))) {
        return;
    }
    $q = new mysql_postfix_builder();
    $q->CheckTables();
    events("open {$directory}");
    while (false !== ($filename = readdir($handle))) {
        if ($EnableArticaSMTPStatistics == 0) {
            @unlink("{$directory}/{$filename}");
            continue;
        }
        if (!preg_match("#(.+?)\\.[0-9]+\\.aws#", $filename, $re)) {
            continue;
        }
        $instancename = $re[1];
        ParseFile("{$directory}/{$filename}");
        if (system_is_overloaded(basename(__FILE__))) {
            system_admin_events("Overloaded system, aborting", __FUNCTION__, __FILE__, __LINE__, "postfix-stats");
            return;
        }
    }
}
示例#14
0
function parse_hours()
{
    $unix = new unix();
    $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid";
    $pidTime = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".time";
    if (!$GLOBALS["VERBOSE"]) {
        if ($unix->file_time_min($pidTime) < 60) {
            return;
        }
    }
    $pid = $unix->get_pid_from_file($pidfile);
    if ($unix->process_exists($pid, basename(__FILE__))) {
        $time = $unix->PROCCESS_TIME_MIN($pid);
        return;
    }
    @file_put_contents($pidfile, getmypid());
    @unlink($pidTime);
    @file_put_contents($pidTime, time());
    $sock = new sockets();
    $EnableNginxStats = $sock->GET_INFO("EnableNginxStats");
    if (!is_numeric($EnableNginxStats)) {
        $EnableNginxStats = 0;
    }
    if ($EnableNginxStats == 0) {
        return;
    }
    if (system_is_overloaded(basename(__FILE__))) {
        events("Overloaded system: {$GLOBALS["SYSTEM_INTERNAL_LOAD"]} aborting", __FUNCTION__, __LINE__);
        return;
    }
    $FALSES["information_schema"] = true;
    $FALSES["mysql"] = true;
    $q = new nginx_stats();
    $DATABASE_LIST_SIMPLE = $q->DATABASE_LIST_SIMPLE();
    while (list($db, $b) = each($DATABASE_LIST_SIMPLE)) {
        if (isset($FALSES[$db])) {
            continue;
        }
        if ($GLOBALS["VERBOSE"]) {
            echo "Parsing database {$db}\n";
        }
        parse_database($db);
    }
}
示例#15
0
function start()
{
    // /etc/artica-postfix/pids/exec.loadavg.php.start.time
    $unix = new unix();
    $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid";
    $pidfileTime = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".time";
    if ($GLOBALS["VERBOSE"]) {
        echo "{$pidfileTime}\n";
    }
    if (!$GLOBALS["VERBOSE"]) {
        if ($unix->file_time_min($pidfileTime) < 59) {
            return;
        }
    }
    $pid = @file_get_contents($pidfile);
    if ($pid < 100) {
        $pid = null;
    }
    if ($unix->process_exists($pid, basename(__FILE__))) {
        $timepid = $unix->PROCCESS_TIME_MIN($pid);
        if ($GLOBALS["VERBOSE"]) {
            echo "{$pid} already executed since {$timepid}Mn\n";
        }
        if ($timepid < 15) {
            return;
        }
        $kill = $unix->find_program("kill");
        unix_system_kill_force($pid);
    }
    @file_put_contents($pidfile, getmypid());
    if (system_is_overloaded()) {
        if ($GLOBALS["VERBOSE"]) {
            echo "Overloaded\n";
        }
        die;
    }
    @unlink($pidfileTime);
    @file_put_contents($pidfileTime, time());
    if ($GLOBALS["VERBOSE"]) {
        echo "cpustats\n";
    }
    cpustats();
}
function tables_hours()
{
    $unix = new unix();
    $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid";
    $timefile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".time";
    if ($GLOBALS["VERBOSE"]) {
        echo "timefile={$timefile}\n";
    }
    $pid = @file_get_contents($pidfile);
    if (!$GLOBALS["FORCE"]) {
        if ($pid < 100) {
            $pid = null;
        }
        $unix = new unix();
        if ($unix->process_exists($pid, basename(__FILE__))) {
            if ($GLOBALS["VERBOSE"]) {
                echo "Already executed pid {$pid}\n";
            }
            return;
        }
        $timeexec = $unix->file_time_min($timefile);
        if ($timeexec < 60) {
            if ($GLOBALS["VERBOSE"]) {
                echo "Only each 60mn - current {$timeexec}mn, use --force to bypass\n";
            }
            return;
        }
        $mypid = getmypid();
        @file_put_contents($pidfile, $mypid);
    }
    @unlink($timefile);
    @file_put_contents($timefile, time());
    $sock = new sockets();
    $GLOBALS["Q"] = new mysql_squid_builder();
    $prefix = date("YmdH");
    $currenttable = "ngixattck_{$prefix}";
    if ($GLOBALS["VERBOSE"]) {
        echo "Current Table: {$currenttable}\n";
    }
    $tablesBrutes = $GLOBALS["Q"]->LIST_TABLES_NGINX_BLOCKED_RT();
    while (list($tablename, $none) = each($tablesBrutes)) {
        if ($tablename == $currenttable) {
            if ($GLOBALS["VERBOSE"]) {
                echo "Skip table: {$tablename}\n";
            }
            continue;
        }
        $t = time();
        if ($GLOBALS["VERBOSE"]) {
            echo "_table_hours_perform({$tablename})\n";
        }
        if (_table_hours_perform($tablename)) {
            $took = $unix->distanceOfTimeInWords($t, time());
            if ($GLOBALS["VERBOSE"]) {
                echo "Remove table: {$tablename}\n";
            }
            $GLOBALS["Q"]->QUERY_SQL("DROP TABLE `{$tablename}`");
            if (system_is_overloaded()) {
                ufdbguard_admin_events("Fatal: Overloaded system: {$GLOBALS["SYSTEM_INTERNAL_LOAD"]} sleeping stopping function", __FUNCTION__, __FILE__, __LINE__, "stats");
                return true;
            }
        }
    }
}
示例#17
0
    repair_corrupted();
    die;
}
if ($argv[1] == "--clean-tmd") {
    clean_tmd();
    die;
}
$unix = new unix();
$pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . ".MAIN.pid";
$pidfileTime = "/etc/artica-postfix/pids/" . basename(__FILE__) . ".MAIN.pid.time";
$pid = $unix->get_pid_from_file($pidfile);
if ($unix->process_exists($pid, basename(__FILE__))) {
    system_admin_events("Already process {$pid} exists", __FUNCTION__, __FILE__, __LINE__, "clean");
    die;
}
if (system_is_overloaded()) {
    system_admin_events("Overloaded system, aborting task", __FUNCTION__, __FILE__, __LINE__, "clean");
}
$t = time();
system_admin_events("Starting cleaning ipband table...", __FUNCTION__, __FILE__, __LINE__, "clean");
ipband_clean();
system_admin_events("Starting cleaning events table...", __FUNCTION__, __FILE__, __LINE__, "clean");
CleanEvents();
system_admin_events("Starting cleaning maillog table...", __FUNCTION__, __FILE__, __LINE__, "clean");
clean_maillogs();
system_admin_events("Starting cleaning squid statistics table...", __FUNCTION__, __FILE__, __LINE__, "clean");
clean_squid_stats_dbs();
clean_squid_stats_no_items();
$took = $unix->distanceOfTimeInWords($t, time(), true);
system_admin_events("Finish, took {$took}", __FUNCTION__, __FILE__, __LINE__, "clean");
function ipband_clean()
示例#18
0
include_once dirname(__FILE__) . '/framework/class.unix.inc';
include_once dirname(__FILE__) . '/ressources/class.http.pear.inc';
include_once dirname(__FILE__) . '/ressources/class.artica-meta.inc';
include_once dirname(__FILE__) . '/ressources/class.os.system.inc';
include_once dirname(__FILE__) . '/ressources/class.system.network.inc';
include_once dirname(__FILE__) . '/ressources/class.squid.inc';
if (posix_getuid() != 0) {
    die("Cannot be used in web server mode\n\n");
}
if (preg_match("#--verbose#", implode(" ", $argv))) {
    $GLOBALS["VERBOSE"] = true;
}
if (preg_match("#--force#", implode(" ", $argv))) {
    $GLOBALS["FORCE"] = true;
}
if (system_is_overloaded(basename(__FILE__))) {
    echo "Overloaded, die()";
    die;
}
$GLOBALS["MAXTTL"] = 15;
if ($argv[1] == "--register") {
    register();
    exit;
}
if ($argv[1] == "--register-server") {
    register_server();
    exit;
}
if ($argv[1] == "--join") {
    register_server();
    exit;
示例#19
0
function xtart()
{
    if (!isset($GLOBALS["ARTICALOGDIR"])) {
        $GLOBALS["ARTICALOGDIR"] = @file_get_contents("/etc/artica-postfix/settings/Daemons/ArticaLogDir");
        if ($GLOBALS["ARTICALOGDIR"] == null) {
            $GLOBALS["ARTICALOGDIR"] = "/var/log/artica-postfix";
        }
    }
    $unix = new unix();
    $binfile = "/usr/share/artica-postfix/bin/seeker";
    if (!is_file($binfile)) {
        build_progress("{failed}", 110);
        events("Unable to stat {$binfile}");
        return;
    }
    $php = $unix->LOCATE_PHP5_BIN();
    $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid";
    $pidTime = "/etc/artica-postfix/pids/exec.seeker.php.xtart.time";
    $pid = $unix->get_pid_from_file($pidfile);
    if ($unix->process_exists($pid, basename(__FILE__))) {
        events("Already process executed pid {$pid}");
        return;
    }
    if (system_is_overloaded(basename(__FILE__))) {
        events("Overloaded system, schedule it later", __LINE__);
        $unix->THREAD_COMMAND_SET("{$php} " . __FILE__);
        build_progress("{failed} Overloaded", 110);
        return;
    }
    @file_put_contents($pidfile, getmypid());
    $timefile = $unix->file_time_min($pidTime);
    $DisksBenchs = intval(@file_get_contents("/etc/artica-postfix/settings/Daemons/DisksBenchs"));
    $DisksBenchs = $DisksBenchs * 60;
    if (!$GLOBALS["FORCE"]) {
        if ($timefile < $DisksBenchs) {
            events("{$timefile}mn, require at least {$DisksBenchs}mn", __LINE__);
            return;
        }
    }
    @unlink($pidTime);
    @file_put_contents($pidTime, time());
    build_progress("{scanning} {disks}", 10);
    $fdisk = $unix->find_program("fdisk");
    exec("{$fdisk} -l 2>&1", $results);
    $DISKS = array();
    while (list($index, $line) = each($results)) {
        $line = trim($line);
        if ($line == null) {
            continue;
        }
        if (preg_match("#^(Disque|Disk)\\s+\\/([a-zA-Z0-9\\-\\_\\/\\.]+).*?:\\s+[0-9]+.*?(bytes|octets)#", $line, $re)) {
            $DISKS["/" . $re[2]] = true;
        }
    }
    if (count($DISKS) == 0) {
        build_progress("{scanning} {disks} {failed}", 110);
        events("Unable to detect disks");
        $unix->ToSyslog("Unable to detect disks");
        system_admin_events("Unable to detect disks\n" . @implode("\n", $results), __FUNCTION__, __FILE__, __LINE__, "system");
        return;
    }
    $RUN = false;
    while (list($disk, $line) = each($DISKS)) {
        $results = array();
        @chmod("{$binfile}", 0755);
        $cmd = "{$binfile} \"" . trim($disk) . "\" 2>&1";
        build_progress("{scanning} {$disk}", 60);
        events("{$cmd}");
        exec($cmd, $results);
        while (list($index, $line) = each($results)) {
            $line = trim($line);
            echo "***: {$line}\n";
            $md5 = md5("{$disk}" . time());
            if ($line == null) {
                continue;
            }
            if (!preg_match("#^Results:\\s+([0-9]+)\\s+seeks.*?,\\s+([0-9\\.]+)\\s+ms#", $line, $re)) {
                continue;
            }
            $seeks = $re[1];
            $ms = $re[2];
            events("{$disk} {$seeks} seeks, {$ms} ms", __LINE__);
            $array = array();
            @mkdir("{$GLOBALS["ARTICALOGDIR"]}/seeker-queue", 0755, true);
            $array["SEEKS"] = $seeks;
            $array["DISK"] = $disk;
            $array["MS"] = $ms;
            $array["time"] = time();
            $unix->ToSyslog("Bench disk {$disk} {$ms} ms for {$seeks} seeks");
            events("{$GLOBALS["ARTICALOGDIR"]}/seeker-queue/{$md5}.ay", __LINE__);
            @file_put_contents("{$GLOBALS["ARTICALOGDIR"]}/seeker-queue/{$md5}.ay", serialize($array));
            $RUN = true;
            break;
        }
    }
    if ($RUN) {
        $php = $unix->LOCATE_PHP5_BIN();
        $nohup = $unix->find_program("nohup");
        build_progress("{analyze}", 90);
        $cmd = "{$php} " . dirname(__FILE__) . "/exec.syslog-engine.php --seeker";
        events($cmd);
        system($cmd);
    }
    build_progress("{done}", 100);
}
示例#20
0
function postqueue()
{
    $unix = new unix();
    if (!$GLOBALS["FORCE"]) {
        $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid";
        $pid = @file_get_contents($pidfile);
        if ($unix->process_exists($pid)) {
            echo __FUNCTION__ . " already executed pid {$pid}\n";
            return;
        }
        @file_put_contents($pidfile, getmypid());
    }
    if (system_is_overloaded()) {
        return;
    }
    $DirPath = "{$GLOBALS["ARTICALOGDIR"]}/postqueue";
    if (!($handle = opendir($DirPath))) {
        if ($GLOBALS["VERBOSE"]) {
            echo "{$DirPath} ERROR\n";
        }
        return;
    }
    $c = 0;
    while (false !== ($file = readdir($handle))) {
        if ($file == ".") {
            continue;
        }
        if ($file == "..") {
            continue;
        }
        if (is_dir("{$DirPath}/{$file}")) {
            if ($GLOBALS["VERBOSE"]) {
                echo "{$DirPath}/{$file} -> DIR\n";
            }
            continue;
        }
        $filename = "{$DirPath}/{$file}";
        $time = $unix->file_time_min($filename);
        if ($time > 180) {
            @unlink($filename);
            continue;
        }
        $c++;
    }
    if ($c == 0) {
        return;
    }
    $q = new mysql();
    $q->QUERY_SQL("truncate table postqueue", "artica_events");
    if (!($handle = opendir($DirPath))) {
        if ($GLOBALS["VERBOSE"]) {
            echo "{$DirPath} ERROR\n";
        }
        return;
    }
    $c = 0;
    while (false !== ($file = readdir($handle))) {
        if ($file == ".") {
            continue;
        }
        if ($file == "..") {
            continue;
        }
        if (is_dir("{$DirPath}/{$file}")) {
            if ($GLOBALS["VERBOSE"]) {
                echo "{$DirPath}/{$file} -> DIR\n";
            }
            continue;
        }
        $filename = "{$DirPath}/{$file}";
        if (postqueue_parse($filename)) {
            events("postqueue():: Success parsing " . basename($filename));
            @unlink($filename);
        }
    }
    shell_exec($unix->LOCATE_PHP5_BIN() . " /usr/share/artica-postfix/exec.watchdog.postfix.queue.php >/dev/null 2>&1 &");
}
示例#21
0
function ActiveDirectoryToMysql()
{
    $sock = new sockets();
    $EnableManageUsersTroughActiveDirectory = $sock->GET_INFO("EnableManageUsersTroughActiveDirectory");
    if (!is_numeric($EnableManageUsersTroughActiveDirectory)) {
        $EnableManageUsersTroughActiveDirectory = 0;
    }
    if ($EnableManageUsersTroughActiveDirectory == 0) {
        die;
    }
    $unix = new unix();
    $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . ".pid";
    $pidTime = "/etc/artica-postfix/pids/" . basename(__FILE__) . ".time";
    $oldpid = $unix->get_pid_from_file($pidfile);
    $sock = new sockets();
    $ActiveDirectoryMysqlSinc = $sock->GET_INFO($ActiveDirectoryMysqlSinc);
    if (!is_numeric($ActiveDirectoryMysqlSinc)) {
        $ActiveDirectoryMysqlSinc = 5;
    }
    if ($ActiveDirectoryMysqlSinc == 0) {
        $ActiveDirectoryMysqlSinc = 1;
    }
    $ActiveDirectoryMysqlSinc = $ActiveDirectoryMysqlSinc * 60;
    if ($unix->process_exists($oldpid, basename(__FILE__))) {
        writelogs("Process {$oldpid} already exists", __FUNCTION__, __FILE__, __LINE__);
        return;
    }
    if (system_is_overloaded(basename(__FILE__))) {
        writelogs("Overloaded system, aborting", __FUNCTION__, __FILE__, __LINE__);
        return;
    }
    @file_put_contents($pidfile, getmypid());
    if (!$GLOBALS["FORCE"]) {
        if ($unix->file_time_min($pidTime) < $ActiveDirectoryMysqlSinc) {
            return;
        }
    }
    @unlink($pidTime);
    @file_put_contents($pidTime, time());
    $t1 = time();
    $ldap = new ldapAD();
    $hash = $ldap->Ldap_search($ldap->suffix, "(objectClass=organizationalUnit)", array("name", "ou", "dn"), 5000);
    if (!is_numeric($hash["count"])) {
        $hash["count"] = 0;
    }
    if ($hash["count"] == 0) {
        return;
    }
    $q = new mysql();
    $q->QUERY_SQL("TRUNCATE TABLE `activedirectory_users`", "artica_backup");
    if (!$q->ok) {
        $unix->send_email_events("ActiveDirectory: mysql error {$q->mysql_error}", "process aborted. Will restart in next cycle", "system");
        return;
    }
    $q->QUERY_SQL("TRUNCATE TABLE `activedirectory_groups`", "artica_backup");
    $q->QUERY_SQL("TRUNCATE TABLE `activedirectory_groupsNames`", "artica_backup");
    $sql = "SELECT ou,dn,enabled,OnlyBranch FROM activedirectory_orgs ORDER BY ou";
    $results = $q->QUERY_SQL($sql, "artica_backup");
    $BranchsInMyql = mysql_num_rows($results);
    while ($ligne = @mysql_fetch_array($results, MYSQL_ASSOC)) {
        $OUCONFIG[$ligne["dn"]]["PARAMS"]["ENABLED"] = $ligne["enabled"];
        $OUCONFIG[$ligne["dn"]]["PARAMS"]["OnlyBranch"] = $ligne["OnlyBranch"];
    }
    $GLOBALS["MEMORY_COUNT_USERS"] = 0;
    $GLOBALS["MEMORY_COUNT_GROUPS"] = 0;
    for ($i = 0; $i < $hash["count"]; $i++) {
        $OrganizationDN = utf8_encode($hash[$i]["dn"]);
        if (isset($OUCONFIG[$OrganizationDN])) {
            if ($OUCONFIG[$OrganizationDN]["PARAMS"]["ENABLED"] == 0) {
                echo "Importing users from {$hash[$i]["ou"][0]} {$OrganizationDN} aborted (disabled)\n";
                continue;
            }
        }
        if ($BranchsInMyql > 0) {
            if (!isset($OUCONFIG[$OrganizationDN])) {
                echo "Importing users from {$hash[$i]["ou"][0]} {$OrganizationDN} is not in mysql database (disabled)\n";
                continue;
            }
        }
        $OnlyBranch = $OUCONFIG[$OrganizationDN]["PARAMS"]["OnlyBranch"];
        $dn = utf8_encode($hash[$i]["dn"]);
        $ou = utf8_encode($hash[$i]["ou"][0]);
        $dn = addslashes($dn);
        $ou = addslashes($ou);
        $sql = "INSERT IGNORE INTO activedirectory_orgs (ou,dn) VALUES('{$ou}','{$dn}')";
        $q->QUERY_SQL($sql, "artica_backup");
        echo "Importing users from {$hash[$i]["ou"][0]} {$hash[$i]["dn"]} OnlyBranch={$OnlyBranch}\n";
        importuser($hash[$i]["dn"], $ou, $OnlyBranch);
    }
    if ($GLOBALS["MEMORY_COUNT_USERS"] == 0) {
        @unlink($pidTime);
    }
    checksGroups();
    $distanceOfTimeInWords = $unix->distanceOfTimeInWords($t1, time());
    $unix->send_email_events("ActiveDirectory: {$GLOBALS["MEMORY_COUNT_USERS"]} members / {$GLOBALS["MEMORY_COUNT_GROUPS"]} groups imported", "These items has been imported into the cache database in {$distanceOfTimeInWords}", "system");
}
示例#22
0
function mailarchives()
{
    if (!$GLOBALS["POSTFIX_INSTALLED"]) {
        return;
    }
    $array[] = "exec.mailarchive.php";
    $array[] = "exec.mailbackup.php";
    $array[] = "exec.fetchmail.sql.php";
    while (list($index, $file) = each($array)) {
        if (system_is_overloaded()) {
            events(__FUNCTION__ . ":: die, overloaded");
            die;
        }
        $cmd = "{$GLOBALS["PHP5"]} /usr/share/artica-postfix/{$file}";
        events("schedule {$cmd}", __FUNCTION__, __LINE__);
        $GLOBALS["CMDS"][] = $cmd;
    }
    if ($GLOBALS["VERBOSE"]) {
        events(__FUNCTION__ . ":: die...");
    }
}
示例#23
0
function UFDBGUARD_COMPILE_ALL_CATEGORIES()
{
    $sock = new sockets();
    if (system_is_overloaded(basename(__FILE__))) {
        squid_admin_mysql(1, "Overloaded system: {$GLOBALS["SYSTEM_INTERNAL_LOAD"]}, aborting recompiling personal categories", null, __FILE__, __LINE__);
        die;
    }
    $EnableRemoteStatisticsAppliance = $sock->GET_INFO("EnableRemoteStatisticsAppliance");
    if (!is_numeric($EnableRemoteStatisticsAppliance)) {
        $EnableRemoteStatisticsAppliance = 0;
    }
    $UseRemoteUfdbguardService = $sock->GET_INFO("UseRemoteUfdbguardService");
    if (!is_numeric($UseRemoteUfdbguardService)) {
        $UseRemoteUfdbguardService = 0;
    }
    if ($EnableRemoteStatisticsAppliance == 1) {
        return;
    }
    if ($UseRemoteUfdbguardService == 1) {
        return;
    }
    if ($EnableRemoteStatisticsAppliance == 1) {
        return;
    }
    $unix = new unix();
    $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid";
    $pid = @file_get_contents($pidfile);
    if ($unix->process_exists($pid, basename(__FILE__))) {
        return;
    }
    @file_put_contents($pidfile, getmypid());
    $sock = new sockets();
    $EnableRemoteStatisticsAppliance = $sock->GET_INFO("EnableRemoteStatisticsAppliance");
    if (!is_numeric($EnableRemoteStatisticsAppliance)) {
        $EnableRemoteStatisticsAppliance = 0;
    }
    if ($EnableRemoteStatisticsAppliance == 1) {
        UFDBGUARD_DOWNLOAD_ALL_CATEGORIES();
        return;
    }
    $EnableWebProxyStatsAppliance = $sock->GET_INFO("EnableWebProxyStatsAppliance");
    if (!is_numeric($EnableWebProxyStatsAppliance)) {
        $EnableWebProxyStatsAppliance = 0;
    }
    $q = new mysql_squid_builder();
    $t = time();
    $cats = $q->LIST_TABLES_CATEGORIES();
    $ufdb = new compile_ufdbguard();
    while (list($table, $line) = each($cats)) {
        if (preg_match("#categoryuris_#", $table)) {
            continue;
        }
        $category = $q->tablename_tocat($table);
        if ($category == null) {
            squid_admin_mysql(1, "Compilation failed for table {$table}, unable to determine category", null, __FILE__, __LINE__);
            continue;
        }
        $ufdb->compile_category($category);
    }
    $ttook = $unix->distanceOfTimeInWords($t, time(), true);
    squid_admin_mysql(2, "All personal categories are compiled ({$ttook})", @implode("\n", $cats), __FILE__, __LINE__, "global-compile");
    if ($EnableWebProxyStatsAppliance == 1) {
        CompressCategories();
        return;
    }
}
示例#24
0
function CleanLogs($aspid = false)
{
    $timefile = "/etc/artica-postfix/pids/exec.clean.logs.php.CleanLogs.time";
    if (!$aspid) {
        $maxtime = 480;
        $unix = new unix();
        $pidpath = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid";
        $pid = @file_get_contents($pidpath);
        if ($unix->process_exists($pid)) {
            $unix->events(basename(__FILE__) . ":: " . __FUNCTION__ . " Already process {$pid} running.. Aborting");
            return;
        }
        @file_put_contents($pidpath, getmypid());
        $timeOfFile = $unix->file_time_min($timefile);
        $unix->events("CleanLogs():: Time {$timeOfFile}/{$maxtime}");
        if ($timeOfFile < $maxtime) {
            $unix->events("CleanLogs():: Aborting");
            return;
        }
    }
    @unlink($timefile);
    @file_put_contents($timefile, time());
    cleanRoot();
    maillog();
    MakeSpace();
    cleanRoot();
    CheckSingle_logfile("/var/log/php.log", 102400);
    CheckSingle_logfile("/opt/squidsql/error.log", 51200);
    CheckSingle_logfile("/var/log/atop.log", 1024);
    CheckSingle_logfile("/var/log/php5-fpm.log", 1024);
    CheckSingle_logfile("/var/log/artica-squid-stats.log", 10240);
    CheckSingle_logfile("/var/log/atop.log", 10240);
    CheckSingle_logfile("/var/log/apache2/access-common.log", 204800);
    wrong_number();
    Clean_tmp_path();
    CleanOldInstall();
    LogRotateTimeAndSize("/var/log/samba");
    if (system_is_overloaded(dirname(__FILE__))) {
        $unix->send_email_events("logs cleaner task aborting, system is overloaded", "stopped after CleanOldInstall()\nWill restart in next cycle...", "system");
        return;
    }
    CleanBindLogs();
    if (system_is_overloaded(dirname(__FILE__))) {
        $unix->send_email_events("logs cleaner task aborting, system is overloaded", "stopped after CleanBindLogs()\nWill restart in next cycle...", "system");
        return;
    }
    $unix->events(basename(__FILE__) . ":: " . __FUNCTION__ . " Cleaning Clamav bases");
    CleanClamav();
    if (system_is_overloaded(dirname(__FILE__))) {
        $unix->send_email_events("logs cleaner task aborting, system is overloaded", "stopped after CleanClamav()\nWill restart in next cycle...", "system");
        return;
    }
    $size = str_replace("&nbsp;", " ", FormatBytes($GLOBALS["DELETED_SIZE"]));
    echo "{$size} cleaned :  {$GLOBALS["DELETED_FILES"]} files\n";
    if ($GLOBALS["DELETED_SIZE"] > 500) {
        send_email_events("{$size} logs files cleaned", "{$GLOBALS["DELETED_FILES"]} files cleaned for {$size} free disk space:\n\n\t\t" . @implode("\n", $GLOBALS["UNLINKED"]), "logs_cleaning");
    }
    $GLOBALS["DELETED_SIZE"] = 0;
    $GLOBALS["DELETED_FILES"] = 0;
    $unix->events(basename(__FILE__) . ":: " . __FUNCTION__ . " initalize");
    init();
    $unix->events(basename(__FILE__) . ":: " . __FUNCTION__ . " cleanTmplogs()");
    cleanTmplogs();
    if (system_is_overloaded(dirname(__FILE__))) {
        $unix->send_email_events("logs cleaner task aborting, system is overloaded", "stopped after cleanTmplogs()\nWill restart in next cycle...", "system");
        return;
    }
    $unix->events(basename(__FILE__) . ":: " . __FUNCTION__ . " Cleaning /opt/artica/tmp");
    CleanDirLogs('/opt/artica/tmp');
    if (system_is_overloaded(dirname(__FILE__))) {
        $unix->send_email_events("logs cleaner task aborting, system is overloaded", "stopped after CleanDirLogs(/opt/artica/tmp)\nWill restart in next cycle...", "system");
        return;
    }
    $unix->events(basename(__FILE__) . ":: " . __FUNCTION__ . " Cleaning /opt/artica/install");
    CleanDirLogs('/opt/artica/install');
    if (system_is_overloaded(dirname(__FILE__))) {
        $unix->send_email_events("logs cleaner task aborting, system is overloaded", "stopped after CleanDirLogs(/opt/artica/install)\nWill restart in next cycle...", "system");
        return;
    }
    $unix->events(basename(__FILE__) . ":: " . __FUNCTION__ . " Cleaning phplogs");
    phplogs();
    if (system_is_overloaded(dirname(__FILE__))) {
        $unix->send_email_events("logs cleaner task aborting, system is overloaded", "stopped after phplogs()\nWill restart in next cycle...", "system");
        return;
    }
    $unix->events(basename(__FILE__) . ":: " . __FUNCTION__ . " Cleaning /opt/openemm/tomcat/logs");
    CleanDirLogs('/opt/openemm/tomcat/logs');
    $unix->events(basename(__FILE__) . ":: " . __FUNCTION__ . " Cleaning PHP Sessions");
    sessions_clean();
    $unix->events(basename(__FILE__) . ":: " . __FUNCTION__ . " Cleaning old install sources packages");
    $size = str_replace("&nbsp;", " ", FormatBytes($GLOBALS["DELETED_SIZE"]));
    echo "{$size} cleaned :  {$GLOBALS["DELETED_FILES"]} files\n";
    if ($GLOBALS["DELETED_SIZE"] > 500) {
        send_email_events("{$size} logs files cleaned", "{$GLOBALS["DELETED_FILES"]} files cleaned for {$size} free disk space:\n\n\t\t" . @implode("\n", $GLOBALS["UNLINKED"]), "logs_cleaning");
    }
}
示例#25
0
function scanarp()
{
    $GLOBALS["CLASS_USERS"] = new usersMenus();
    $GLOBALS["CLASS_SOCKETS"] = new sockets();
    if (!$GLOBALS["CLASS_USERS"]->ARPD_INSTALLED) {
        if ($GLOBALS["VERBOSE"]) {
            echo __FUNCTION__ . " ARPD_INSTALLED = FALSE\n";
        }
        return;
    }
    $EnableArpDaemon = $GLOBALS["CLASS_SOCKETS"]->GET_INFO("EnableArpDaemon");
    if (!is_numeric($EnableArpDaemon)) {
        $EnableArpDaemon = 1;
    }
    if ($EnableArpDaemon == 0) {
        if ($GLOBALS["VERBOSE"]) {
            echo __FUNCTION__ . " EnableArpDaemon = {$EnableArpDaemon}\n";
        }
        return;
    }
    $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . ".pid";
    $unix = new unix();
    $me = basename(__FILE__);
    $pid = $unix->get_pid_from_file($pidfile);
    if ($unix->process_exists($pid, $me)) {
        if ($GLOBALS["VERBOSE"]) {
            echo " {$pid} --> Already executed.. aborting the process\n";
        }
        $time = $unix->PROCCESS_TIME_MIN($pid);
        system_admin_events("Already executed pid {$pid} since {$time}Mn.. aborting the process", __FUNCTION__, __FILE__, __LINE__, "system");
        die;
    }
    @file_put_contents($pidfile, getmypid());
    if (!is_file("/var/lib/arpd/arpd.db")) {
        die;
    }
    $GLOBALS["CLASS_UNIX"] = $unix;
    $GLOBALS["nmblookup"] = $unix->find_program("nmblookup");
    $GLOBALS["arpd"] = $unix->find_program("arpd");
    $GLOBALS["arp"] = $unix->find_program("arp");
    $GLOBALS["ARP_DB"] = "/var/lib/arpd/arpd.db";
    $GLOBALS["CACHE_DB"] = "/etc/artica-postfix/arpd.cache";
    $GLOBALS["EnableMacAddressFilter"] = trim(@file_get_contents("/etc/artica-postfix/settings/Daemons/EnableMacAddressFilter"));
    if (!is_numeric($GLOBALS["EnableMacAddressFilter"])) {
        $GLOBALS["EnableMacAddressFilter"] = 1;
    }
    $squidbin = $unix->LOCATE_SQUID_BIN();
    if (is_file($squidbin)) {
        if ($GLOBALS["EnableMacAddressFilter"] == 0) {
            return;
        }
    }
    $ArpdArray = unserialize(base64_decode(@file_get_contents($GLOBALS["CACHE_DB"])));
    if ($GLOBALS["FLUSH"]) {
        $ArpdArray = array();
    }
    if (!is_array($ArpdArray)) {
        $ArpdArray = array();
    }
    if (!isset($ArpdArray["LAST"])) {
        $ArpdArray["LAST"] = 0;
    }
    $last_modified = filemtime($GLOBALS["ARP_DB"]);
    $TimeArpd = $ArpdArray["LAST"];
    if ($TimeArpd == $last_modified) {
        events("{$TimeArpd} -> {$last_modified} No modification time", __FUNCTION__, __LINE__);
        return;
    }
    events("Scanning ARP table....", __FUNCTION__, __LINE__);
    $ArpdArray["LAST"] = $last_modified;
    exec("{$GLOBALS["arpd"]} -l 2>&1", $results);
    events("{$GLOBALS["arpd"]} -l return " . count($results) . " element(s)", __FUNCTION__, __LINE__);
    while (list($num, $ligne) = each($results)) {
        if (preg_match("#unexpected file type or format#", $ligne)) {
            @unlink($GLOBALS["ARP_DB"]);
            @unlink($GLOBALS["CACHE_DB"]);
            shell_exec("/etc/init.d/arpd restart");
            die;
        }
        if (!preg_match("#^[0-9]+\\s+\\s+(.+?)\\s+(.+)#", $ligne, $re)) {
            if ($GLOBALS["VERBOSE"]) {
                echo "line: {$num}, unexpected line..\n";
            }
            continue;
        }
        if (preg_match("#FAILED:#", $re[2])) {
            continue;
        }
        $mac = $re[2];
        $ipaddr = $re[1];
        if ($GLOBALS["VERBOSE"]) {
            echo "line: {$num}, MAC:{$mac} -> {$ipaddr}\n";
        }
        if (isset($ArpdArray["MACS"][$mac])) {
            if ($GLOBALS["VERBOSE"]) {
                echo "MAC:{$mac} Already cached, aborting....\n";
            }
            continue;
        }
        $ArpdArray["MACS"][$mac] = true;
        $cmp = new computers();
        $uid = $cmp->ComputerIDFromMAC($mac);
        if ($GLOBALS["VERBOSE"]) {
            echo "line: {$num}, MAC:{$mac} -> {$uid}\n";
        }
        if ($uid == null) {
            $res2 = array();
            $computer_name = null;
            events("It is time to add {$mac}/{$ipaddr} in database", __FUNCTION__, __LINE__);
            exec("{$GLOBALS["arp"]} -a {$ipaddr} 2>&1", $res2);
            if (preg_match("#^(.+?)\\s+\\(#", trim(@implode("", $res2)), $rz)) {
                $computer_name = $rz[1];
            }
            if (strlen($computer_name) < 3) {
                $computer_name = $ipaddr;
            }
            $cmp->uid = "{$computer_name}\$";
            $cmp->ComputerIP = $ipaddr;
            $cmp->ComputerMacAddress = $mac;
            system_admin_events("adding/editing {$computer_name} with MAC:{$mac}", __FUNCTION__, __FILE__, __LINE__, "network");
            $cmp->Add();
        } else {
            if ($GLOBALS["FLUSH"]) {
                $res2 = array();
                $cmp = new computers($uid);
                $computer_name = null;
                events("It is time to edit {$uid}/{$mac}/{$ipaddr} in database", __FUNCTION__, __LINE__);
                exec("{$GLOBALS["arp"]} -a {$ipaddr} 2>&1", $res2);
                if ($GLOBALS["VERBOSE"]) {
                    echo "{$GLOBALS["arp"]} -a {$ipaddr} 2>&1 = >" . trim(@implode("", $res2));
                }
                if (preg_match("#^(.+?)\\s+\\(#", trim(@implode("", $res2)), $rz)) {
                    $computer_name = $rz[1];
                } else {
                    if ($GLOBALS["VERBOSE"]) {
                        echo "Unable to find computer name\n";
                    }
                }
                if (strlen($computer_name) < 3) {
                    $computer_name = $ipaddr;
                }
                if ($GLOBALS["VERBOSE"]) {
                    echo "line: {$num}, UID:{$mac} -> {$uid}\n";
                }
                if ($GLOBALS["VERBOSE"]) {
                    echo "line: {$num}, NAME:{$computer_name} -> {$uid}\n";
                }
                system_admin_events("adding/editing {$computer_name} with MAC:{$mac}", __FUNCTION__, __FILE__, __LINE__, "network");
                $cmp->ComputerIP = $ipaddr;
                $cmp->ComputerMacAddress = $mac;
                $cmp->Add();
            }
        }
        if (system_is_overloaded(basename(__FILE__))) {
            @file_put_contents($GLOBALS["CACHE_DB"], base64_encode(serialize($ArpdArray)));
            system_admin_events("Overloaded system, aborting the task...", __FUNCTION__, __FILE__, __LINE__, "network");
            return;
        }
        @file_put_contents($GLOBALS["CACHE_DB"], base64_encode(serialize($ArpdArray)));
        $nice = EXEC_NICE();
        $unix = new unix();
        $nohup = $unix->find_program("nohup");
        $php5 = $unix->LOCATE_PHP5_BIN();
        shell_exec("{$nohup} {$nice} {$php5} " . __FILE__ . " --tomysql schedule-id={$GLOBALS["SCHEDULE_ID"]} >/dev/null 2>&1 &");
    }
}
function ParseKav4UriLogs()
{
    $users = new usersMenus();
    if (!$users->KAV4PROXY_INSTALLED) {
        die;
    }
    $unix = new unix();
    if (system_is_overloaded(basename(__FILE__))) {
        if ($GLOBALS["VERBOSE"]) {
            "System overloaded\n";
        }
        return;
    }
    if (!$GLOBALS["NO_PID_CHECKS"]) {
        if (stats_pid()) {
            return;
        }
    }
    $tablename = "Kav4Proxy_" . date('Y') . date('m');
    if ($GLOBALS["VERBOSE"]) {
        echo "Table {$tablename}/artica_events...\n";
    }
    $q = new mysql();
    if (!$q->TABLE_EXISTS($tablename, "artica_events")) {
        $sql = "CREATE TABLE `artica_events`.`{$tablename}` (\n\t\t`zmd5` VARCHAR( 90 ) NOT NULL ,\n\t\t`zDate` DATETIME NOT NULL ,\n\t\t`size` INT UNSIGNED NOT NULL,\n\t\t`status` VARCHAR( 40 ) NOT NULL ,\n\t\t`ICAP_SERVER` VARCHAR( 40 ) NOT NULL ,\n\t\t`uid` VARCHAR( 128 ) NOT NULL ,\n\t\t`client` VARCHAR( 40 ) NOT NULL ,\n\t\t`uri` VARCHAR( 255 ) NOT NULL ,\n\t\t`country` VARCHAR( 90 ) NOT NULL ,\n\t\t`sitename` VARCHAR( 128 ) NOT NULL ,\n\t\t`category` VARCHAR( 90 ) NOT NULL ,\n\t\tPRIMARY KEY ( `zmd5` ) ,\n\t\tKEY `zDate` (`zDate`),\n\t\tKEY `size` (`size`),\n\t\tKEY `status` (`status`),\n\t\tKEY `ICAP_SERVER` (`ICAP_SERVER`),\n\t\tKEY `uid` (`uid`),\n\t\tKEY `client` (`client`),\n\t\tKEY `country` (`country`),\n\t\tKEY `sitename` (`sitename`),\n\t\tINDEX ( `category` )\n\t\t)";
        $q->QUERY_SQL($sql, "artica_events");
        if ($GLOBALS["VERBOSE"]) {
            echo "Table {$tablename}/artica_events failed...\n";
        }
        if (!$q->ok) {
            $unix->send_email_events("Unable to create {$tablename}/artica_events", "Kaspersky statistics has been aborted\n{$q->mysql_error}", "proxy");
            return;
        }
    }
    $WorkingDirectory = "/var/log/artica-postfix/kav4Server-queue";
    $WorkingDirectoryError = "/var/log/artica-postfix/kav4Server-errors";
    if (!is_dir($WorkingDirectoryError)) {
        @mkdir($WorkingDirectoryError, 0600, true);
    }
    if (!($handle = @opendir($WorkingDirectory))) {
        if ($GLOBALS["VERBOSE"]) {
            echo "{$WorkingDirectory} no such directory\n";
        }
        return;
    }
    //$newArray=array("DATE" =>$date,"SIZE"=>$size,"STATUS"=>$status,"ICAP_SERVER"=>$icap_server,"UID"=>$uid,
    //"CLIENT"=>$clientip,"URI"=>$uri,"COUNTRY"=>$Country,"SITENAME"=>$sitename);
    if ($GLOBALS["VERBOSE"]) {
        echo "Processing {$WorkingDirectory}\n";
    }
    $prefixsql = "INSERT IGNORE INTO {$tablename} (`zmd5`,`zDate`,`size`,`status`,`ICAP_SERVER`,`uid`,`client`,`uri`,`country`,`sitename`) VALUES ";
    while (false !== ($filename = readdir($handle))) {
        $targetFile = "{$WorkingDirectory}/{$filename}";
        if ($GLOBALS["VERBOSE"]) {
            echo "Processing {$targetFile}\n";
        }
        if (!is_file($targetFile)) {
            if ($GLOBALS["VERBOSE"]) {
                echo "Processing {$targetFile} no such file\n";
            }
            continue;
        }
        $array = unserialize(@file_get_contents($targetFile));
        if (!is_array($array)) {
            @unlink($targetFile);
            if ($GLOBALS["VERBOSE"]) {
                echo "Processing {$targetFile} not an array\n";
            }
            continue;
        }
        $md5 = md5(serialize($array));
        $suffix[] = "('{$md5}','{$array["DATE"]}','{$array["SIZE"]}','{$array["STATUS"]}','{$array["ICAP_SERVER"]}',\n\t\t'{$array["UID"]}','{$array["CLIENT"]}','{$array["URI"]}','{$array["COUNTRY"]}',\n\t\t'{$array["SITENAME"]}')";
        @unlink($targetFile);
        if (count($suffix) > 500) {
            $d = $d + count($suffix);
            $sql = "{$prefixsql} " . @implode(",", $suffix);
            $q->QUERY_SQL($sql, "artica_events");
            if (!$q->ok) {
                @file_put_contents($sql, "{$WorkingDirectoryError}/" . md5($sql) . ".err");
                $unix->send_email_events("kav4proxy statistics Mysql error", "{$q->mysql_error}\nProcess has been aborted and saved in {$WorkingDirectoryError} directory", "proxy");
            }
            if (system_is_overloaded(basename(__FILE__))) {
                $unix->send_email_events("kav4proxy statistics aborted du to overload computer", "Will retry in next cycle", "proxy");
                return;
            }
        }
    }
    if (count($suffix) > 1) {
        $d = $d + count($suffix);
        $sql = "{$prefixsql} " . @implode(",", $suffix);
        $q->QUERY_SQL($sql, "artica_events");
        if (!$q->ok) {
            @file_put_contents($sql, "{$WorkingDirectoryError}/" . md5($sql) . "err");
            $unix->send_email_events("kav4proxy statistics Mysql error", "{$q->mysql_error}\nProcess has been aborted and saved in {$WorkingDirectoryError} directory", "proxy");
        }
    }
    if ($GLOBALS["VERBOSE"]) {
        echo "processed {$d} files\n";
    }
}
示例#27
0
function ipblocks(){
	if(system_is_overloaded()){return;}
	include_once(dirname(__FILE__) . '/ressources/class.mysql.inc');
	$unix=new unix();
	$php=$unix->LOCATE_PHP5_BIN();
	$nogup=$unix->find_program("nohup");
	$pidfile="/etc/artica-postfix/pids/".basename(__FILE__).".".__FUNCTION__.".pid";
	$pidtime="/etc/artica-postfix/pids/".basename(__FILE__).".".__FUNCTION__.".time";
	$pid=@file_get_contents($pidfile);
	if($unix->process_exists($pid)){echo "Already running pid $pid\n";return;}	
	$q=new mysql();
	if(!$q->TABLE_EXISTS('ipblocks_db','artica_backup')){$q->BuildTables();}
	if(!is_file($pidtime)){
		$count=$q->COUNT_ROWS("ipblocks_db", "artica_backup");
		if($count==0){shell_exec(trim("$nogup /usr/share/artica-postfix/bin/artica-update --ipblocks >/dev/null 2>&1 &"));}
		sleep(5);
		@file_put_contents($pidtime, time());
	}
	
	if($unix->file_time_min($pidtime)>480){
		shell_exec(trim("$nogup /usr/share/artica-postfix/bin/artica-update --ipblocks >/dev/null 2>&1 &"));
		sleep(5);
		@unlink($pidtime);
		@file_put_contents($pidtime, time());
		$unix->THREAD_COMMAND_SET("$php /usr/share/artica-postfix/exec.postfix.iptables.php --ipdeny");
	}
	
	@file_put_contents($pidfile, getmypid());
	
	foreach (glob("/var/log/artica-postfix/ipblocks/*.zone") as $filename) {
		$basename=basename($filename);
		if(!preg_match("#(.+?)\.zone#", $basename,$re)){continue;}
		$country=$re[1];
		$datas=explode("\n", @file_get_contents($filename));
		$f=true;
		
		while (list ($index, $line) = each ($datas) ){
			$line=trim($line);if($line==null){continue;}if($country==null){continue;}
			$sql="INSERT IGNORE INTO ipblocks_db (cdir,country) VALUES('$line','$country')";
			$q->QUERY_SQL($sql,"artica_backup");
			if(!$q->ok){events("ipblocks:: $q->mysql_error line:".__LINE__);$f=false;break;}
		}
		if(!$f){continue;}
		@unlink($filename);
	}
	
	$file_time="/etc/artica-postfix/pids/". basename(__FILE__).".".__FUNCTION__.".time";
	if($unix->file_time_min($file_time)>300){
		$sql="DELETE FROM loadavg WHERE stime < DATE_SUB( NOW( ) , INTERVAL 7 DAY )";
		$q->QUERY_SQL($sql,"artica_events");
		@unlink($file_time);
		@file_put_contents($file_time, time());
	}
	
	
}
示例#28
0
function xupdate($aspid = false)
{
    $unix = new unix();
    $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid";
    $pidtime = "/etc/artica-postfix/pids/exec.suricata.updates.php.update.time";
    if (!$GLOBALS["FORCE"]) {
        if (system_is_overloaded()) {
            die;
        }
        if (!$aspid) {
            $pid = @file_get_contents($pidfile);
            if ($pid < 100) {
                $pid = null;
            }
            if ($unix->process_exists($pid, basename(__FILE__))) {
                echo "PID: {$pid} Already exists....\n";
                die;
            }
            @file_put_contents($pidfile, getmypid());
            $pidExec = $unix->file_time_min($pidtime);
            if ($pidExec < 1439) {
                return;
            }
            @unlink($pidtime);
            @file_put_contents($pidtime, time());
        }
    }
    echo "Starting....\n";
    $sock = new sockets();
    $CurrentEmergingRulesMD5 = $sock->GET_INFO("CurrentEmergingRulesMD5");
    $tmpdir = $unix->TEMP_DIR();
    echo "CurrentEmergingRulesMD5={$CurrentEmergingRulesMD5} TMPDIR:{$tmpdir}\n";
    $curl = new ccurl("https://rules.emergingthreatspro.com/open/suricata/emerging.rules.tar.gz.md5");
    $targetpath = "{$tmpdir}/emerging.rules.tar.gz.md5";
    if (!$curl->GetFile($targetpath)) {
        echo "{$targetpath} failed\n";
        artica_update_event(0, "Unable to download emerging.rules.tar.gz.md5", $curl->errors, __FILE__, __LINE__);
        return;
    }
    echo "Open {$targetpath}\n";
    $f = explode("\n", @file_get_contents($targetpath));
    echo "{$targetpath} " . count($f) . " lines\n";
    if (count($f) > 2) {
        artica_update_event(0, "Truncated emerging.rules.tar.gz.md5", $curl->errors, __FILE__, __LINE__);
        return;
    }
    @unlink($targetpath);
    $NewEmergingRulesMD5 = trim($f[0]);
    if ($NewEmergingRulesMD5 == $CurrentEmergingRulesMD5) {
        echo "No new updates...\n";
        die;
    }
    $curl = new ccurl("https://rules.emergingthreatspro.com/open/suricata/version.txt");
    $targetpath = "{$tmpdir}/version.txt";
    if (!$curl->GetFile($targetpath)) {
        echo "{$targetpath} failed\n";
        artica_update_event(0, "Unable to version.txt", $curl->errors, __FILE__, __LINE__);
        return;
    }
    $NextVersion = @file_get_contents($targetpath);
    @unlink($targetpath);
    $curl = new ccurl("https://rules.emergingthreatspro.com/open/suricata/emerging.rules.tar.gz");
    $targetpath = "{$tmpdir}/emerging.rules.tar.gz";
    if (!$curl->GetFile($targetpath)) {
        echo "{$targetpath} failed\n";
        artica_update_event(0, "Unable to download emerging.rules.tar.gz", $curl->errors, __FILE__, __LINE__);
        return;
    }
    $FileMD5 = md5_file($targetpath);
    if ($FileMD5 != $NewEmergingRulesMD5) {
        artica_update_event(0, "Corrupted emerging.rules.tar.gz file", "{$FileMD5}<>{$NewEmergingRulesMD5}", __FILE__, __LINE__);
        return;
    }
    echo "Extracting rules\n";
    $tar = $unix->find_program("tar");
    shell_exec("{$tar} xf {$targetpath} -C /etc/suricata/");
    @unlink($targetpath);
    $sock->SET_INFO("CurrentEmergingRulesMD5", $NewEmergingRulesMD5);
    $sock->SET_INFO("CurrentEmergingRulesVersion", $NextVersion);
    $curl = new ccurl("https://rules.emergingthreatspro.com/open/suricata/classification.config");
    $targetpath = "{$tmpdir}/classification.config";
    if (!$curl->GetFile($targetpath)) {
        echo "{$targetpath} failed\n";
        artica_update_event(0, "Unable to download classification.config", $curl->errors, __FILE__, __LINE__);
        return;
    }
    @unlink("/etc/suricata/classification.config");
    @copy($targetpath, "/etc/suricata/classification.config");
    @unlink($targetpath);
    $php = $unix->LOCATE_PHP5_BIN();
    $nohup = $unix->find_program("nohup");
    shell_exec("{$php} /usr/share/artica-postfix/exec.suricata.php --classifications");
    $q = new postgres_sql();
    $results = $q->QUERY_SQL("select signature FROM suricata_sig where enabled=0");
    $nice = $unix->EXEC_NICE();
    $SH[] = "#!/bin/sh";
    while ($ligne = @pg_fetch_assoc($results)) {
        $sig = $ligne["signature"];
        echo "Disable signature {$sig}\n";
        $SH[] = "{$nice} /usr/share/artica-postfix/bin/sidrule -d {$sig} || true";
    }
    $targetpath = "{$tmpdir}/sidrule-remove.sh";
    $SH[] = "rm -f {$tmpdir}/sidrule-remove.sh";
    $SH[] = "/etc/init.d/suricata restart\n\n";
    @file_put_contents("{$tmpdir}/sidrule-remove.sh", @implode("\n", $SH));
    @chmod("{$tmpdir}/sidrule-remove.sh", 0755);
    shell_exec("{$nohup} {$tmpdir}/sidrule-remove.sh >/dev/null 2>&1 &");
    artica_update_event(2, "Success updating emergingthreatspro IDS patterns v{$NextVersion}", null, __FILE__, __LINE__);
    BlockIPs();
}
示例#29
0
function sa_update()
{
    if (system_is_overloaded(basename(__FILE__))) {
        writelogs("Overloaded system, aborting task", __FUNCTION__, __FILE__, __LINE__);
        return;
    }
    $unix = new unix();
    $saupdate = $unix->find_program("sa-update");
    $sacompile = $unix->find_program("sa-compile");
    if (!is_file($saupdate)) {
        return null;
    }
    $statusFileContent = "/usr/share/artica-postfix/ressources/logs/sa-update-status.txt";
    $statusFile = "/usr/share/artica-postfix/ressources/logs/sa-update-status.html";
    if ($sacompile != null) {
        $sacompile = " && {$sacompile} >>{$statusFileContent}";
    }
    $wget = $unix->find_program("wget");
    shell_exec("{$wget} http://yerp.org/rules/GPG.KEY -O /root/GPG.KEY");
    shell_exec("{$saupdate} sa-update --import /root/GPG.KEY");
    $cmd = "{$saupdate} --nogpg -D --gpgkey 6C6191E3 --channel sought.rules.yerp.org --channel updates.spamassassin.org >{$statusFileContent}{$sacompile} 2>&1";
    if ($GLOBALS["VERBOSE"]) {
        echo "sa-update:: {$cmd}\n";
    }
    shell_exec($cmd);
    shell_exec("/bin/chmod 777 {$statusFileContent}");
    $f = explode("\n", $statusFileContent);
    while (list($index, $line) = each($f)) {
        if (preg_match("updates complete, exiting with code [0-9]+", $line)) {
            if ($GLOBALS["VERBOSE"]) {
                echo "sa-update:: {$line}\n";
            }
            $unix->send_email_events("Spamassassin success update databases", @implode("\n", $f), "postfix");
            shell_exec("{$sacompile}");
            @unlink($statusFile);
            shell_exec("/etc/init.d/spamassassin reload");
            return;
        }
    }
    if ($GLOBALS["VERBOSE"]) {
        echo "sa-update:: FAILED\n";
    }
}
示例#30
0
function build()
{
    $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid";
    $pid = @file_get_contents($pidfile);
    $unix = new unix();
    if ($unix->process_exists($pid)) {
        echo "Starting......: " . date("H:i:s") . " Already process exists pid {$pid}\n";
        return;
    }
    @file_put_contents($pidfile, getmypid());
    $php = $unix->LOCATE_PHP5_BIN();
    if (system_is_overloaded()) {
        $unix->THREAD_COMMAND_SET("{$php} " . __FILE__ . " --build");
        return;
    }
    patch_grub_default();
    $sock = new sockets();
    $q = new mysql();
    $sql = "SELECT * FROM users_containers WHERE created=0 AND onerror=0";
    $results = $q->QUERY_SQL($sql, "artica_backup");
    $count = mysql_num_rows($results);
    if (!$q->ok) {
        echo "Starting......: " . date("H:i:s") . " users_containers {$q->mysql_error}\n";
        return;
    }
    echo "Starting......: " . date("H:i:s") . " {$count} containers to build\n";
    if ($count > 0) {
        while ($ligne = @mysql_fetch_array($results, MYSQL_ASSOC)) {
            $directory = trim($ligne["directory"]);
            $ID = $ligne["container_id"];
            if ($directory == null) {
                users_containers_error($ID, "No specified main directory...");
                continue;
            }
            $directory_size_avai = $unix->DIRECTORY_FREEM($directory);
            if ($directory_size_avai == 0) {
                users_containers_error($ID, "no space left on specified directory");
                continue;
            }
            @mkdir($directory, 0755, true);
            if (!is_dir($directory)) {
                users_containers_error($ID, "Permission denied on specified directory");
                continue;
            }
            $ContainerFullPath = $directory . "/{$ID}.disk";
            $size = $ligne["container_size"];
            if ($size > $directory_size_avai) {
                users_containers_error($ID, "{$size}MB will exceed space on main storage");
                continue;
            }
            $label = "{$ID}_disk";
            echo "Starting......: " . date("H:i:s") . " Verify {$ContainerFullPath} with a size of {$size}MB\n";
            if (!stat_system($ContainerFullPath)) {
                echo "Starting......: " . date("H:i:s") . " buil_dd {$ContainerFullPath} {$size}MB\n";
                if (!build_dd($ContainerFullPath, $size)) {
                    users_containers_error($ID, "Unable to build the virtual disk (ERR." . __LINE__ . ")");
                    continue;
                }
            }
            $GetLoops = GetLoops();
            if (!stat_system($ContainerFullPath)) {
                users_containers_error($ID, "Unable to build the virtual disk (ERR." . __LINE__ . ")");
                continue;
            }
            if ($GetLoops[$ContainerFullPath] == null) {
                echo "Starting......: " . date("H:i:s") . " {$ContainerFullPath} no such loop\n";
                if (!build_loop($ContainerFullPath)) {
                    echo "`{$ContainerFullPath}` unable to create loop\n";
                    echo "Starting......: " . date("H:i:s") . " Re-check the loop list...\n";
                    $GetLoops = GetLoops();
                    if ($GetLoops[$ContainerFullPath] == null) {
                        users_containers_error($ID, "Loop error (ERR." . __LINE__ . ")");
                        continue;
                    }
                }
            }
            echo "Starting......: " . date("H:i:s") . " {$ContainerFullPath} loop={$GetLoops[$ContainerFullPath]}\n";
            $sql = "UPDATE users_containers SET loop_dev='{$GetLoops[$ContainerFullPath]}' WHERE `container_id`='{$ID}'";
            $q->QUERY_SQL($sql, 'artica_backup');
            if (!$q->ok) {
                echo "{$q->mysql_error}\n";
                continue;
            }
            $dev = $GetLoops[$ContainerFullPath];
            echo "Starting......: " . date("H:i:s") . " {$ContainerFullPath} is {$dev}\n";
            if (!ifFileSystem($dev)) {
                if (!mke2fs($dev, $label)) {
                    users_containers_error($ID, "mke2fs error (ERR." . __LINE__ . ")");
                    continue;
                }
            }
            $uuid = Getuuid($dev);
            echo "Starting......: " . date("H:i:s") . " {$dev} uuid={$uuid}\n";
            $q->QUERY_SQL("UPDATE users_containers SET uuid='{$uuid}' WHERE `container_id`='{$ID}'", 'artica_backup');
            if ($uuid == null) {
                continue;
            }
            $q->QUERY_SQL("UPDATE users_containers SET created='1' WHERE `container_id`='{$ID}'", 'artica_backup');
        }
    }
    @mkdir("/media/artica_containers/membersdisks", 0755, true);
    $q = new mysql();
    $sql = "SELECT * FROM users_containers WHERE created=1 AND onerror=0";
    $results = $q->QUERY_SQL($sql, "artica_backup");
    $count = mysql_num_rows($results);
    $mount = $unix->find_program("mount");
    $umount = $unix->find_program("umount");
    while ($ligne = @mysql_fetch_array($results, MYSQL_ASSOC)) {
        $directory = trim($ligne["directory"]);
        $mkfs_ext4 = $unix->find_program("mkfs.ext4");
        $typ = "ext4";
        if (!is_file($mkfs_ext4)) {
            $typ = "ext3";
        }
        $ID = $ligne["container_id"];
        $ContainerFullPath = $directory . "/{$ID}.disk";
        if (!is_file($ContainerFullPath)) {
            echo "Starting......: " . date("H:i:s") . " {$ContainerFullPath} no such file\n";
        }
        $autofs[] = "disk{$ID}\t-fstype={$typ},loop\t:{$ContainerFullPath}";
    }
    echo "Starting......: " . date("H:i:s") . " Saving /etc/auto.members\n";
    @file_put_contents("/etc/auto.members", implode("\n", $autofs) . "\n");
    @unlink("/etc/init.d/artica-containers");
    patch_auto_master();
    shell_exec("/etc/init.d/autofs reload");
    $unix = new unix();
    $php5 = $unix->LOCATE_PHP5_BIN();
    $SquidPerformance = intval($sock->GET_INFO("SquidPerformance"));
    shell_exec("{$php5} /usr/share/artica-postfix/exec.initslapd.php --iscsi");
    if (is_file("/etc/init.d/iscsitarget")) {
        $unix->THREAD_COMMAND_SET("/etc/init.d/iscsitarget restart");
    }
    Checks(true);
}