function user_status_table()
{
    if (isset($GLOBALS["user_status_table_executed"])) {
        if ($GLOBALS["VERBOSE"]) {
            $trace = debug_backtrace();
            if (isset($trace[1])) {
                $called = " called by " . basename($trace[1]["file"]) . " {$trace[1]["function"]}() line {$trace[1]["line"]}";
                echo "user_status_table Already executed {$called}\n";
            }
        }
        return;
    }
    $GLOBALS["user_status_table_executed"] = true;
    $unix = new unix();
    $sock = new sockets();
    $timefile = "/usr/share/artica-postfix/ressources/databases/ZARAFA_DB_STATUS.db";
    $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid";
    $mns = $unix->file_time_min($timefile);
    if ($GLOBALS["VERBOSE"]) {
        echo "{$timefile} = {$mns}Mn\n";
    }
    if (!$GLOBALS["FORCE"]) {
        if (system_is_overloaded(basename(__FILE__))) {
            system_admin_events("Overload system, aborting", __FUNCTION__, __FILE__, __LINE__, "zarafa");
            return;
        }
        if ($mns < 180) {
            return;
        }
        $pid = $unix->get_pid_from_file($pidfile);
        if ($unix->process_exists($pid, basename(__FILE__))) {
            $timeProcess = $unix->PROCCESS_TIME_MIN($pid);
            system_admin_events("{$pid}, task is already executed (since {$timeProcess}Mn}), aborting", __FUNCTION__, __FILE__, __LINE__, "zarafa");
            if ($timeProcess < 15) {
                return;
            }
            $kill = $unix->find_program("kill");
            unix_system_kill_force($pid);
            system_admin_events("{$pid}, killed (since {$timeProcess}Mn}), aborting", __FUNCTION__, __FILE__, __LINE__, "zarafa");
        }
    }
    @file_put_contents($pidfile, getmypid());
    @unlink($timefile);
    @file_put_contents($timefile, time());
    $ZarafaIndexPath = $sock->GET_INFO("ZarafaIndexPath");
    $ZarafaStoreOutsidePath = $sock->GET_INFO("ZarafaStoreOutsidePath");
    $ZarafaMySQLServiceType = $sock->GET_INFO("ZarafaMySQLServiceType");
    if (!is_numeric($ZarafaMySQLServiceType)) {
        $ZarafaMySQLServiceType = 1;
    }
    // $ZarafaMySQLServiceType =1 ou 2 /var/lib/mysql
    // $ZarafaMySQLServiceType =3 --> dedicated instance
    if ($ZarafaIndexPath == null) {
        $ZarafaIndexPath = "/var/lib/zarafa/index";
    }
    if ($ZarafaStoreOutsidePath == null) {
        $ZarafaStoreOutsidePath = "/var/lib/zarafa";
    }
    $ARRAY["ZARAFA_INDEX"] = $unix->DIRSIZE_BYTES($ZarafaIndexPath);
    if ($ZarafaMySQLServiceType == 1 or $ZarafaMySQLServiceType == 2) {
        $ARRAY["ZARAFA_DB"] = $unix->DIRSIZE_BYTES("/var/lib/mysql");
    }
    if ($ZarafaMySQLServiceType == 3) {
        $WORKDIR = $sock->GET_INFO("ZarafaDedicateMySQLWorkDir");
        if ($WORKDIR == null) {
            $WORKDIR = "/home/zarafa-db";
        }
        $ARRAY["ZARAFA_DB"] = $unix->DIRSIZE_BYTES($WORKDIR);
    }
    $ARRAY["ATTACHS"] = $unix->DIRSIZE_BYTES($ZarafaStoreOutsidePath);
    @file_put_contents($timefile, serialize($ARRAY));
    @chmod($timefile, 0750);
    unset($ARRAY);
    $zarafaadmin = $unix->find_program("zarafa-admin");
    $kill = $unix->find_program("kill");
    $pids = $unix->PIDOF_PATTERN_ALL("zarafa-admin -l");
    if (count($pids) > 0) {
        while (list($pid, $line) = each($pids)) {
            $time = $unix->PROCESS_TTL($pid);
            if ($time > 15) {
                $unix->_syslog("killing zarafa-admin -l pid {$pid} ({$time}mn)", basename(__FILE__));
                unix_system_kill_force($pid);
            }
        }
    }
    $pid = $unix->PIDOF_PATTERN("zarafa-admin -l");
    if ($unix->process_exists($pid)) {
        $unix->_syslog("zarafa-admin -l pid {$pid} still running", basename(__FILE__));
    }
    if ($GLOBALS["VERBOSE"]) {
        echo "{$zarafaadmin} -l 2>&1\n--------------------------------------------------------------------\n";
    }
    exec("{$zarafaadmin} -l 2>&1", $results);
    while (list($num, $line) = each($results)) {
        $line = trim($line);
        if ($GLOBALS["VERBOSE"]) {
            echo "\"{$line}\"\n";
        }
        if (preg_match("#User list for\\s+(.+?)\\(#i", $line, $re)) {
            $ou = $re[1];
            continue;
        }
        if (preg_match("#Username#", $line)) {
            continue;
        }
        if (preg_match("#SYSTEM#", $line)) {
            continue;
        }
        if (preg_match("#^(.+?)\\s+.+?#", $line, $re)) {
            if ($GLOBALS["VERBOSE"]) {
                echo "\"{$ou}\" -> \"{$re[1]}\" -> \"_user_status_table_info({$re[1]},{$zarafaadmin})\"\n";
            }
            $array[$ou][$re[1]] = _user_status_table_info($re[1], $zarafaadmin);
        }
    }
    $q = new mysql();
    if (!$q->TABLE_EXISTS('zarafauserss', 'artica_events')) {
        $sql = "CREATE TABLE IF NOT EXISTS `zarafauserss` (\n\t\t\t  `zmd5` varchar(90) NOT NULL PRIMARY KEY,\n\t\t\t  `uid` varchar(128) NOT NULL,\n\t\t\t  `ou` varchar(128) NOT NULL,\n\t\t\t  `mail` varchar(255) NOT NULL,\n\t\t\t  `license` smallint(1) NOT NULL,\n\t\t\t  `NONACTIVETYPE` varchar(60) NOT NULL,\n\t\t\t  `storesize` BINT(100) UNSIGNED NOT NULL,\n\t\t\t  KEY `uid` (`uid`),\n\t\t\t  KEY `ou` (`ou`),\n\t\t\t  KEY `mail` (`mail`),\n\t\t\t  KEY `license` (`license`),\n\t\t\t  KEY `NONACTIVETYPE` (`NONACTIVETYPE`),\n\t\t\t  KEY `storesize` (`storesize`)\n\t\t\t) ";
        $q->QUERY_SQL($sql, 'artica_events');
        if (!$q->ok) {
            echo $q->mysql_error . "\n";
            return;
        }
    }
    $prefix = "INSERT IGNORE INTO zarafauserss (zmd5,uid,ou,mail,license,NONACTIVETYPE,storesize) VALUES ";
    while (list($ou, $members) = each($array)) {
        while (list($uid, $main) = each($members)) {
            $md5 = md5("{$uid}{$ou}");
            if (!isset($main["NONACTIVETYPE"])) {
                $main["NONACTIVETYPE"] = '';
            }
            if ($GLOBALS["VERBOSE"]) {
                echo "\"('{$md5}','{$uid}','{$ou}','{$main["MAIL"]}','{$main["ACTIVE"]}','{$main["NONACTIVETYPE"]}','{$main["STORE_SIZE"]}')\n";
            }
            $f[] = "('{$md5}','{$uid}','{$ou}','{$main["MAIL"]}','{$main["ACTIVE"]}','{$main["NONACTIVETYPE"]}','{$main["STORE_SIZE"]}')";
        }
    }
    if (count($f) == 0) {
        return;
    }
    $q->QUERY_SQL("TRUNCATE TABLE zarafauserss", "artica_events");
    $q->QUERY_SQL($prefix . @implode(",", $f), "artica_events");
    if (!$q->ok) {
        echo $q->mysql_error . "\n";
    }
    if ($GLOBALS["VERBOSE"]) {
        echo "FINISH\n--------------------------------------------------------------------\n";
    }
}
Beispiel #2
0
function phpcgi()
{
    $unix = new unix();
    $phpcgi = $unix->LIGHTTPD_PHP5_CGI_BIN_PATH();
    $pids = $unix->PIDOF_PATTERN_ALL($phpcgi);
    if (count($pids) == 0) {
        return;
    }
    $c = 0;
    while (list($pid, $ligne) = each($pids)) {
        $time = $unix->PROCESS_TTL($pid);
        if ($time > 1640) {
            $c++;
            $unix->KILL_PROCESS($pid, 9);
        }
    }
}
function start($xtime = 0)
{
    if ($GLOBALS["VERBOSE"]) {
        "echo Loading...\n";
    }
    $unix = new unix();
    $pids = $unix->PIDOF_PATTERN_ALL(basename(__FILE__));
    if (count($pids) > 5) {
        die;
    }
    if ($xtime == 0) {
        if ($GLOBALS["VERBOSE"]) {
            "echo Loading done...\n";
        }
        $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["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 < 720) {
                return;
            }
            $mypid = getmypid();
            @file_put_contents($pidfile, $mypid);
        }
    }
    @unlink($timefile);
    @file_put_contents($timefile, time());
    $nohup = $unix->find_program("nohup");
    $php = $unix->LOCATE_PHP5_BIN();
    if ($xtime > 0) {
        $dateRequested = date("Y-m-d", $xtime);
        $dateRequested_sql = " WHERE zDate='{$dateRequested}'";
        if (SquidStatisticsTasksOverTime()) {
            stats_admin_events(1, "Statistics overtime... Aborting ( requested for {$dateRequested} ) ", null, __FILE__, __LINE__);
            return;
        }
    }
    $sql = "SELECT\n\tDATE_FORMAT(zDate,'%Y%m%d') as tprefix,DATE_FORMAT(zDate,'%Y-%m-%d') as CurDay,tablename FROM tables_day{$dateRequested_sql}  \n\tORDER BY zDate DESC";
    $q = new mysql_squid_builder();
    $results = $q->QUERY_SQL($sql);
    //bigint(100)
    if ($q->FIELD_TYPE("tables_day", "totalBlocked", "syslogs") == "bigint(100)") {
        $q->QUERY_SQL('ALTER TABLE `tables_day` CHANGE `size` `size` BIGINT( 255 ) NOT NULL');
        $q->QUERY_SQL('ALTER TABLE `tables_day` CHANGE `totalBlocked` `totalBlocked` BIGINT( 255 ) NOT NULL');
        $q->QUERY_SQL('ALTER TABLE `tables_day` CHANGE `requests` `requests` BIGINT( 255 ) NOT NULL');
        $q->QUERY_SQL('ALTER TABLE `tables_day` CHANGE `totalsize` `totalsize` BIGINT( 255 ) NOT NULL');
        $q->QUERY_SQL('ALTER TABLE `tables_day` CHANGE `size_cached` `size_cached` BIGINT( 255 ) NOT NULL');
    }
    if (!$q->FIELD_EXISTS("tables_day", "totalKeyWords")) {
        $q->QUERY_SQL("ALTER TABLE `tables_day` ADD `totalKeyWords` BIGINT( 255 ) NOT NULL NOT NULL,ADD INDEX ( `totalKeyWords`)");
        if (!$q->ok) {
            squid_admin_mysql(0, $q->mysql_error, null, __FILE__, __LINE__);
            echo $q->mysql_error;
            return;
        }
    }
    if (!$q->FIELD_EXISTS("tables_day", "DangerousCatz")) {
        $q->QUERY_SQL("ALTER TABLE `tables_day` ADD `DangerousCatz` smallint( 1 ) NOT NULL NOT NULL,ADD INDEX ( `DangerousCatz`)");
    }
    if (!$q->ok) {
        echo "{$q->mysql_error}.<hr>{$sql}</hr>";
    }
    while ($ligne = @mysql_fetch_array($results, MYSQL_ASSOC)) {
        $tablename = $ligne["tablename"];
        $hourtable = $ligne["tprefix"] . "_hour";
        if ($ligne["tprefix"] == date("Ymd")) {
            continue;
        }
        $KeyWordsTable = "searchwordsD_" . $ligne["tprefix"];
        $members_table = "{$ligne["tprefix"]}_members";
        $youtube_table = "youtubeday_{$ligne["tprefix"]}";
        $myXtime = strtotime($ligne["CurDay"] . "00:00:00");
        if ($q->TABLE_EXISTS($hourtable)) {
            $sql = "SELECT SUM(size) as tsize, SUM(hits) as thits FROM {$hourtable}";
            $ligne2 = mysql_fetch_array($q->QUERY_SQL($sql));
            $size = $ligne2["tsize"];
            $hits = $ligne2["thits"];
            $sizeL = FormatBytes($size / 1024);
            if ($GLOBALS["VERBOSE"]) {
                echo "{$tablename} - {$sizeL} / {$hits} {$hourtable} [ {$sql} ]\n";
            }
            $sql = "UPDATE tables_day SET totalsize='{$size}',requests='{$hits}' WHERE tablename='{$tablename}'";
            $q->QUERY_SQL($sql);
            if (!$q->ok) {
                if ($GLOBALS["VERBOSE"]) {
                    echo $q->mysql_error . "\n";
                }
            }
            $sql = "SELECT COUNT(`sitename`) as tcount FROM {$hourtable} WHERE LENGTH(`category`)=0";
            if ($GLOBALS["VERBOSE"]) {
                echo $sql . "\n";
            }
            $ligne2 = mysql_fetch_array($q->QUERY_SQL($sql));
            $max = $ligne2["tcount"];
            $sql = "UPDATE tables_day SET `not_categorized`={$max} WHERE tablename='{$tablename}'";
            $q->QUERY_SQL($sql);
        }
        if ($q->TABLE_EXISTS($members_table)) {
            $MembersField = which_filter($members_table, true);
            if ($GLOBALS["VERBOSE"]) {
                echo "Table members Calculate Members by {$MembersField}\n";
            }
            if ($MembersField != null) {
                $MembersCount = CalculateElements($members_table, $MembersField);
                $sql = "UPDATE tables_day SET `MembersCount`={$MembersCount} WHERE tablename='{$tablename}'";
                if ($GLOBALS["VERBOSE"]) {
                    echo $sql . "\n";
                }
                $q->QUERY_SQL($sql);
            }
        }
        if ($q->TABLE_EXISTS($youtube_table)) {
            $sql = "SELECT youtubeid FROM {$youtube_table} GROUP BY youtubeid";
            $results2 = $q->QUERY_SQL($sql);
            if (!$q->ok) {
                echo $q->mysql_error . "\n";
                return;
            }
            $YouTubeHits = mysql_num_rows($results2);
            $sql = "UPDATE tables_day SET `YouTubeHits`={$YouTubeHits} WHERE tablename='{$tablename}'";
            $q->QUERY_SQL($sql);
        }
        if ($q->TABLE_EXISTS($KeyWordsTable)) {
            $sql = "SELECT `words` FROM {$KeyWordsTable} GROUP BY `words`";
            $results2 = $q->QUERY_SQL($sql);
            if (!$q->ok) {
                echo $q->mysql_error . "\n";
                return;
            }
            $CountOfWords = mysql_num_rows($results2);
            $sql = "UPDATE tables_day SET totalKeyWords='{$CountOfWords}' WHERE tablename='{$tablename}'";
            $q->QUERY_SQL($sql);
        }
    }
}
function xstart()
{
    $T1 = time();
    $curl = new ccurl();
    $unix = new unix();
    $GLOBALS["MYPID"] = getmypid();
    $pidfile = "/etc/artica-postfix/pids/windowupdate.partial.processor.pid";
    $pid = $unix->get_pid_from_file($pidfile);
    if ($unix->process_exists($pid, basename(__FILE__))) {
        die;
    }
    $pids = $unix->PIDOF_PATTERN_ALL(basename(__FILE__), true);
    if (count($pids) > 0) {
        while (list($i, $line) = each($pids)) {
            events("Already executed PID:{$i}... aborting ", __LINE__);
        }
        die;
    }
    $TEMPDIR = $unix->TEMP_DIR() . "/WindowsUpdates";
    $rm = $unix->find_program("rm");
    @file_put_contents($pidfile, $GLOBALS["MYPID"]);
    if (is_dir($TEMPDIR)) {
        shell_exec("{$rm} -rf {$TEMPDIR}");
        @mkdir($TEMPDIR);
    }
    $GLOBALS["WindowsUpdateMaxToPartialQueue"] = intval(@file_get_contents("/etc/artica-postfix/settings/Daemons/WindowsUpdateMaxToPartialQueue"));
    $GLOBALS["WindowsUpdateCachingDir"] = @file_get_contents("/etc/artica-postfix/settings/Daemons/WindowsUpdateCachingDir");
    if ($GLOBALS["WindowsUpdateCachingDir"] == null) {
        $GLOBALS["WindowsUpdateCachingDir"] = "/home/squid/WindowsUpdate";
    }
    $WindowsUpdateDownTimeout = intval(@file_get_contents("/etc/artica-postfix/settings/Daemons/WindowsUpdateDownTimeout"));
    if ($WindowsUpdateDownTimeout == 0) {
        $WindowsUpdateDownTimeout = 600;
    }
    $WindowsUpdateBandwidthMaxFailed = intval(@file_get_contents("/etc/artica-postfix/settings/Daemons/WindowsUpdateBandwidthMaxFailed"));
    if ($WindowsUpdateBandwidthMaxFailed == 0) {
        $WindowsUpdateBandwidthMaxFailed = 50;
    }
    $WindowsUpdateMaxPartition = intval(@file_get_contents("/etc/artica-postfix/settings/Daemons/WindowsUpdateMaxPartition"));
    if ($WindowsUpdateMaxPartition == 0) {
        $WindowsUpdateMaxPartition = 80;
    }
    $fileSource = "{$GLOBALS["WindowsUpdateCachingDir"]}/Partials/Queue.log";
    $LinesCount = $unix->COUNT_LINES_OF_FILE($fileSource);
    if (!is_file($fileSource)) {
        return;
    }
    $md5start = md5_file($fileSource);
    $CheckPartitionPercentage = CheckPartitionPercentage();
    if ($CheckPartitionPercentage > $WindowsUpdateMaxPartition) {
        events("Failed: Storage Partition exceed {$WindowsUpdateMaxPartition}% Stopping retreivals", __LINE__);
        @touch("/etc/squid3/WindowsUpdatePartitionExceed");
        DirectorySize();
        return;
    }
    $WindowsUpdateInProduction = intval(@file_get_contents("/etc/artica-postfix/settings/Daemons/WindowsUpdateInProduction"));
    if ($WindowsUpdateInProduction == 0) {
        if ($unix->IsProductionTime()) {
            $time = $unix->file_time_min("/etc/artica-postfix/pids/WindowsUpdateInProduction");
            if ($time > 15) {
                @unlink("/etc/artica-postfix/pids/WindowsUpdateInProduction");
                @touch("/etc/artica-postfix/pids/WindowsUpdateInProduction");
                events("INFO: Aborting, No download during production time", __LINE__);
                DirectorySize();
            }
            return;
        }
    }
    if (is_file("/etc/squid3/WindowsUpdatePartitionExceed")) {
        @unlink("/etc/squid3/WindowsUpdatePartitionExceed");
    }
    $handle = @fopen($fileSource, "r");
    if (!$handle) {
        events("Fopen failed on {$fileSource}", __LINE__);
        return false;
    }
    $NEWBUFFER = array();
    $URLALREADY = array();
    $NewBuffer = array();
    $FinalSize = 0;
    $FF = 0;
    $c = 0;
    while (!feof($handle)) {
        $buffer = trim(fgets($handle));
        $c++;
        if ($buffer == null) {
            continue;
        }
        $TR = explode("|||", $buffer);
        $LocalFile = $TR[0];
        $URI = $TR[1];
        $ExpectedSize = $TR[2];
        if (!isset($TR[3])) {
            $TR[3] = 1;
        }
        if (isset($URLALREADY[$URI])) {
            continue;
        }
        $URLALREADY[$URI] = true;
        $BaseNameOfFile = basename($URI);
        events("INFO: {$BaseNameOfFile} " . xFormatBytes($ExpectedSize / 1024) . " Retry:{$TR[3]} [{$c}/{$LinesCount}]", __LINE__);
        if (DownloadByRange($URI, $ExpectedSize, $LocalFile)) {
            update_mysql($LocalFile, $URI);
            continue;
        }
        $TR[3] = $TR[3] + 1;
        if ($TR[3] > $WindowsUpdateBandwidthMaxFailed) {
            events("Error: Max retry ({$WindowsUpdateBandwidthMaxFailed}) for filename: {$BaseNameOfFile}", __LINE__);
            SaveToBlacklists($BaseNameOfFile);
            RemoveTempOf($URI, $LocalFile);
            continue;
        }
        $NewBuffer[] = @implode("|||", $TR);
    }
    if (count($NewBuffer) == 0) {
        @unlink($fileSource);
        return;
    }
    events("INFO: add " . count($NewBuffer) . " orders to queue", __LINE__);
    @file_put_contents($fileSource, @implode("\n", $NewBuffer));
    DirectorySize();
}
Beispiel #5
0
function xstart()
{
    $unix = new unix();
    $TimeFile = "/etc/artica-postfix/pids/exec.squidcache.php.time";
    $PidFile = "/etc/artica-postfix/pids/exec.squidcache.php.pid";
    $Pid = $unix->get_pid_from_file($PidFile);
    if ($unix->process_exists($Pid)) {
        $pidtime = $unix->PROCCESS_TIME_MIN($Pid);
        if ($pidtime > 29) {
            events("Max execution time reached 30Mn for PID {$Pid} Kill it...", 0, 2, __LINE__);
            unix_system_kill_force($Pid);
            die;
        }
        events("Already running PID {$Pid} since {$pidtime}Mn", 0, 2, __LINE__);
        return;
    }
    @file_put_contents($PidFile, getmypid());
    $pids = $unix->PIDOF_PATTERN_ALL(basename(__FILE__));
    if (count($pids) > 3) {
        events("Too many instances " . count($pids) . " dying", 0, 1, __LINE__);
        $mypid = getmypid();
        while (list($pid, $ligne) = each($pids)) {
            if ($pid == $mypid) {
                continue;
            }
            events("Killing {$pid}");
            unix_system_kill_force($pid);
        }
    }
    $pids = $unix->PIDOF_PATTERN_ALL(basename(__FILE__));
    if (count($pids) > 3) {
        events("Too many instances " . count($pids) . " dying", 0, 2, __LINE__);
        die;
    }
    @unlink($TimeFile);
    @file_put_contents($TimeFile, time());
    $sock = new sockets();
    $GLOBALS["HyperCacheStoragePath"] = $sock->GET_INFO("HyperCacheStoragePath");
    if ($GLOBALS["HyperCacheStoragePath"] == null) {
        $GLOBALS["HyperCacheStoragePath"] = "/home/artica/proxy-cache";
    }
    @chown("/usr/share/squid3", "squid");
    @chgrp("/usr/share/squid3", "squid");
    HyperCacheMirror();
    if ($GLOBALS["HYPER_CACHE_VERBOSE"]) {
        events("Storage path: {$GLOBALS["HyperCacheStoragePath"]}", 0, 2, __LINE__);
        events("Scanning /usr/share/squid3", 0, 2, __LINE__);
    }
    $f = $unix->DirFiles("/usr/share/squid3", "HyperCacheQueue-.+?-([0-9]+)\\.db\$");
    $GLOBALS["SIZE_DOWNLOADED"] = 0;
    $GLOBALS["HITS"] = 0;
    while (list($num, $file) = each($f)) {
        if ($GLOBALS["HYPER_CACHE_VERBOSE"]) {
            events("Found database: {$file}", 0, 2, __LINE__);
        }
        if (!preg_match("#^HyperCacheQueue-.+?-([0-9]+)\\.db\$#", $file, $re)) {
            continue;
        }
        if (preg_match("#HyperCacheQueue-dropbox\\.com#", $file)) {
            continue;
        }
        $ID = $re[1];
        HyperCacheScanDBFile("/usr/share/squid3/{$file}", $ID);
    }
    if ($GLOBALS["SIZE_DOWNLOADED"] > 0) {
        $size = FormatBytes($GLOBALS["SIZE_DOWNLOADED"] / 1024);
        $hits = $GLOBALS["HITS"];
        events("{$size} downloaded -  {$hits} requests", $ID, 2, __LINE__);
        squid_admin_enforce(2, "{$size} downloaded and store {$hits} requests", null, __FILE__, __LINE__);
    }
    if ($GLOBALS["VERBOSE"]) {
        echo "xstart ---> DeleteRules\n";
    }
    DeleteRules();
    if ($GLOBALS["VERBOSE"]) {
        echo "xstart ---> GetRulesSizes\n";
    }
    GetRulesSizes();
}
Beispiel #6
0
function clean_nmap_processes()
{
    $unix = new unix();
    $nmap = $unix->find_program("nmap");
    if (!is_file($nmap)) {
        return;
    }
    $pids = $unix->PIDOF_PATTERN_ALL($nmap);
    while (list($pid, $ar) = each($pids)) {
        $Time = $unix->PROCCESS_TIME_MIN($pid, 60);
    }
}
function start_squid($aspid = false)
{
    $GLOBALS["LOGS"] = array();
    $suffix = null;
    if ($GLOBALS["MONIT"]) {
        $suffix = " (by system monitor)";
    }
    if ($GLOBALS["BY_CACHE_LOGS"]) {
        $suffix = " (by cache.log monitor)";
    }
    if ($GLOBALS["BY_STATUS"]) {
        $suffix = " (by Artica monitor)";
    }
    if ($GLOBALS["BY_CLASS_UNIX"]) {
        $suffix = " (by Artica class.unix.inc)";
    }
    if ($GLOBALS["BY_FRAMEWORK"]) {
        $suffix = " (by Artica framework)";
    }
    if ($GLOBALS["BY_OTHER_SCRIPT"]) {
        $suffix = " (by other script)";
    }
    if ($GLOBALS["BY_ARTICA_INSTALL"]) {
        $suffix = " (by artica-install)";
    }
    if ($GLOBALS["BY_FORCE_RECONFIGURE"]) {
        $suffix = " (after building settings)";
    }
    $unix = new unix();
    $php = $unix->LOCATE_PHP5_BIN();
    $nohup = $unix->find_program("nohup");
    $sock = new sockets();
    $reconfigure = false;
    $SQUIDEnable = $sock->GET_INFO("SQUIDEnable");
    $NtpdateAD = $sock->GET_INFO("NtpdateAD");
    if (!is_numeric($SQUIDEnable)) {
        $SQUIDEnable = 1;
    }
    $kill = $unix->find_program("kill");
    if (!is_numeric($NtpdateAD)) {
        $NtpdateAD = 0;
    }
    $su_bin = $unix->find_program("su");
    $sysctl = $unix->find_program("sysctl");
    $squidbin = $unix->LOCATE_SQUID_BIN();
    if (!is_file($squidbin)) {
        build_progress_start("Not installed", 110);
        if ($GLOBALS["OUTPUT"]) {
            echo "Restart......: Squid-cache, not installed\n";
        }
        return;
    }
    if ($GLOBALS["MONIT"]) {
        if (function_exists("debug_backtrace")) {
            $trace = debug_backtrace();
            if (isset($trace[1])) {
                $file = basename($trace[1]["file"]);
                $function = $trace[1]["function"];
                $line = $trace[1]["line"];
                $called = "Called by {$function}() from line {$line}";
            }
        }
        $pid = SQUID_PID();
        if ($unix->process_exists($pid)) {
            $ps = $unix->find_program("ps");
            $grep = $unix->find_program("grep");
            exec("{$ps} aux|{$grep} squid 2>&1", $results);
            squid_admin_mysql(2, "Monit ordered to start squid but squid is still in memory PID {$pid} ??", "I cannot accept this order, see details\n" . @implode("\n", $results), __FILE__, __LINE__);
            $squidpidfile = $unix->LOCATE_SQUID_PID();
            @file_put_contents($squidpidfile, $pid);
            return;
        }
        squid_admin_mysql(1, "Monit ordered to start squid", $called, __FILE__, __LINE__);
    }
    if ($SQUIDEnable == 0) {
        if ($GLOBALS["OUTPUT"]) {
            echo "Starting......: " . date("H:i:s") . " Squid is disabled...\n";
        }
        build_progress_start("Proxy service is disabled", 110);
        return;
    }
    if (is_file("/etc/init.d/iptables-transparent")) {
        shell_exec("/etc/init.d/iptables-transparent start");
    }
    if (is_file("/etc/artica-postfix/squid.lock")) {
        $time = $unix->file_time_min("/etc/artica-postfix/squid.lock");
        if ($time < 60) {
            if ($GLOBALS["OUTPUT"]) {
                echo "Starting......: " . date("H:i:s") . " Proxy is locked (since {$time}Mn...\n";
            }
            build_progress_start(" Proxy is locked (since {$time}Mn", 110);
            return;
        }
        @unlink("/etc/artica-postfix/squid.lock");
    }
    $pids = $unix->PIDOF_PATTERN_ALL("exec.squid.watchdog.php --start");
    if (count($pids) > 2) {
        if ($GLOBALS["OUTPUT"]) {
            echo "Starting......: " . date("H:i:s") . " Too many instances " . count($pids) . " starting squid, kill them!\n";
        }
        $mypid = getmypid();
        while (list($pid, $ligne) = each($pids)) {
            if ($pid == $mypid) {
                continue;
            }
            if ($GLOBALS["OUTPUT"]) {
                echo "Starting......: " . date("H:i:s") . " killing {$pid}\n";
            }
            unix_system_kill_force($pid);
        }
    }
    if (!$aspid) {
        $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid";
        $pid = $unix->get_pid_from_file($pidfile);
        if ($unix->process_exists($pid, basename(__FILE__))) {
            $time = $unix->PROCCESS_TIME_MIN($pid);
            if ($time < 5) {
                build_progress_start("Task Already running PID {$pid} since {$time}mn", 110);
                Events("Task Already running PID {$pid} since {$time}mn");
                if ($GLOBALS["OUTPUT"]) {
                    echo "Starting......: " . date("H:i:s") . " Already task running PID {$pid} since {$time}mn, Aborting operation (" . __LINE__ . ")\n";
                }
                return;
            }
            squid_admin_mysql(0, "Too long time for artica task PID {$pid} running since {$time}mn", "Process will be killed");
            Tosyslog("Too long time for artica task PID {$pid} running since {$time}mn -> kill");
            unix_system_kill_force($pid);
        }
        @file_put_contents($pidfile, getmypid());
    }
    $squidbin = $unix->find_program("squid");
    if (!is_file($squidbin)) {
        $squidbin = $unix->find_program("squid3");
    }
    if (!is_file($squidbin)) {
        build_progress_start("Not installed", 110);
        system_admin_events("Squid not seems to be installed", __FUNCTION__, __FILE__, __LINE__, "proxy");
        return;
    }
    @chmod($squidbin, 0755);
    $sock = new sockets();
    $DisableForceFCK = intval($sock->GET_INFO("DisableForceFCK"));
    if ($DisableForceFCK == 0) {
        if ($GLOBALS["OUTPUT"]) {
            echo "Starting......: " . date("H:i:s") . " Will force a checkdisk At next reboot\n";
        }
        @touch("/forcefsck");
    }
    $pid = SQUID_PID();
    if ($unix->process_exists($pid)) {
        $time = $unix->PROCCESS_TIME_MIN($pid);
        build_progress_start("Proxy service already running since {$time}Mn", 50);
        if ($GLOBALS["START_PROGRESS"]) {
            $php = $unix->LOCATE_PHP5_BIN();
            build_progress_start("Removing caches...", 55);
            @unlink("/usr/share/artica-postfix/ressources/databases/ALL_SQUID_STATUS");
            build_progress_start("Building caches...", 70);
            system("{$php} /usr/share/artica-postfix/exec.status.php --all-squid");
            if (!is_file("/usr/share/artica-postfix/ressources/databases/ALL_SQUID_STATUS")) {
                build_progress_start("Fatal!! Watchdog issue!!", 110);
                return;
            }
            build_progress_start("{done}", 100);
        }
        return;
    }
    build_progress_start("Preparing proxy service", 50);
    start_prepare();
    $squid_checks = new squid_checks();
    $squid_checks->squid_parse();
    build_progress_start("{starting_proxy_service}", 60);
    $pid = SQUID_PID();
    if ($GLOBALS["CRASHED"]) {
        for ($i = 0; $i < 10; $i++) {
            sleep(1);
            $pid = SQUID_PID();
            if ($unix->process_exists($pid)) {
                continue;
            }
            break;
        }
        squid_admin_mysql(2, "No need to start Proxy service after a crash", "It seems the watchdog detect a crash but after 10s the proxy still running\nOperation is aborted", __FILE__, __LINE__);
        return;
    }
    build_progress_start("Tuning network", 70);
    $unix->TCP_TUNE_SQUID_DEFAULT();
    $t1 = time();
    build_progress_start("Checking caches", 71);
    SendLogs("Checking caches...");
    $cacheBooster = new squidbooster();
    $cacheBooster->cache_booster();
    build_progress_start("Checking caches", 73);
    CheckStoreDirs(true);
    SendLogs("Checking caches done...");
    build_progress_start("Checking Ports", 75);
    SendLogs("Checking Ports...");
    $array = CheckAllports();
    SendLogs("Checking " . count($array) . " ports");
    while (list($port, $ligne) = each($array)) {
        $portZ = $unix->PIDOF_BY_PORT($port);
        SendLogs("Checking port {$port} - " . count($portZ) . " process(es)");
        if (count($portZ) > 0) {
            while (list($pid, $ligne) = each($portZ)) {
                SendLogs("Checking port {$port} - killing pid {$pid}");
                shell_exec("kill -9 {$pid} >/dev/null 2>&1");
            }
        }
    }
    build_progress_start("Checking SHM", 75);
    system("{$php} /usr/share/artica-postfix/exec.squid.smp.php");
    SendLogs("Starting squid {$squidbin}....");
    $echo = $unix->find_program("echo");
    $size = round(@filesize("/var/log/squid/cache.log") / 1024, 2) / 1024;
    if ($size > 50) {
        squid_admin_mysql(2, "Cleaning cache.log {$size}MB", null, __FILE__, __LINE__);
        @copy("/var/log/squid/cache.log", "/var/log/squid/cache.log." . time());
        shell_exec("{$echo} \" \"> /var/log/squid/cache.log 2>&1");
    }
    @chmod($squidbin, 0755);
    @chmod("/var/log/squid", 0755);
    if (is_link("/var/log/squid")) {
        @chmod(readlink("/var/log/squid"), 0755);
    }
    squid_admin_mysql(1, "Starting Squid-cache service {$suffix}", @implode("\n", $GLOBALS["LOGS"]), __FILE__, __LINE__);
    build_progress_start("Remove SystemV5 Memory", 80);
    kill_shm();
    CHECK_WIFIDOG_IPTABLES_RULES();
    $PIDFILE = $unix->LOCATE_SQUID_PID();
    $f = array();
    $f[] = "#! /bin/sh";
    $f[] = ". /lib/lsb/init-functions";
    $f[] = "PATH=/bin:/usr/bin:/sbin:/usr/sbin";
    $f[] = "DAEMON=\"{$squidbin}\"";
    $f[] = "CONFIG=\"/etc/squid3/squid.conf\"";
    $f[] = "SQUID_ARGS=\"-YC -f \$CONFIG\"";
    $f[] = "PIDFILE=\"{$PIDFILE}\"";
    $f[] = "";
    $f[] = "KRB5RCACHETYPE=none";
    $f[] = "KRB5_KTNAME=/etc/squid3/PROXY.keytab";
    $f[] = "export KRB5RCACHETYPE";
    $f[] = "export KRB5_KTNAME";
    $f[] = "";
    $f[] = "";
    $f[] = "umask 027";
    $f[] = "ulimit -n 65535";
    $f[] = "start-stop-daemon --start --pidfile \$PIDFILE --exec \$DAEMON -- \$SQUID_ARGS";
    $f[] = "status=\$?";
    $f[] = "if [ \$status -eq 0 ]";
    $f[] = "\tthen";
    $f[] = "\t        echo \"Success starting Proxy service\"";
    $f[] = "\tfi ";
    $f[] = "exit 0\n";
    @file_put_contents("/usr/sbin/squid-start", @implode("\n", $f));
    $f = array();
    @chmod("/usr/sbin/squid-start", 0755);
    exec("/usr/sbin/squid-start 2>&1", $GLOBALS["LOGS"]);
    $PRC = 40;
    $MAXPRC = 60;
    $AB = 0;
    $TESTFAILED = false;
    while (list($index, $line) = each($GLOBALS["LOGS"])) {
        if (preg_match("#FATAL: Bungled#", $line)) {
            squid_admin_mysql(1, "Alert: Bungled configuration when starting Proxy", $line, __FILE__, __LINE__);
            $TESTFAILED = true;
            break;
        }
    }
    if ($TESTFAILED) {
        $TESTFAILED = false;
        if (!is_file("/etc/artica-postfix/SQUID_TEST_FAILED")) {
            build_progress_start("Reconfigure Proxy service", 80);
            system("{$php} /usr/share/artica-postfix/exec.squid.php --build --force");
        }
        $GLOBALS["LOGS"] = array();
        exec("{$squidbin} -f /etc/squid3/squid.conf 2>&1", $GLOBALS["LOGS"]);
        while (list($index, $line) = each($GLOBALS["LOGS"])) {
            if (preg_match("#FATAL: Bungled#", $line)) {
                squid_admin_mysql(1, "Alert: Bungled configuration after reconfiguring Proxy", $line, __FILE__, __LINE__);
                $TESTFAILED = true;
                break;
            }
        }
    }
    if ($TESTFAILED) {
        @touch("/etc/artica-postfix/SQUID_TEST_FAILED");
        build_progress_start("Start Proxy service {failed}", 110);
        die;
    }
    @unlink("/etc/artica-postfix/SQUID_TEST_FAILED");
    for ($i = 0; $i < 10; $i++) {
        $PRC++;
        if ($PRC > $MAXPRC - 1) {
            $PRC = $MAXPRC - 1;
        }
        build_progress_start("{starting_service} {$i}/10", 85);
        build_progress_restart("{starting_service}", $PRC);
        $pid = SQUID_PID();
        if ($unix->process_exists($pid)) {
            SendLogs("Starting squid started pid {$pid}...");
            break;
        }
        ToSyslog("Starting squid waiting {$i}/10s");
        SendLogs("Starting squid waiting {$i}/10s");
        sleep(1);
    }
    if (!$unix->process_exists($pid)) {
        build_progress_start("{failed}", 110);
        SendLogs("Starting Squid failed to start...");
        ToSyslog("Starting Squid failed to start...");
        if (function_exists("debug_backtrace")) {
            $trace = debug_backtrace();
            if (isset($trace[1])) {
                $sourcefunction = $trace[1]["function"];
                $sourceline = $trace[1]["line"];
                $executed = "Executed by {$sourcefunction}() line {$sourceline}\nusing argv:{$GLOBALS["ARGVS"]}\n";
            }
        }
        squid_admin_mysql(0, "Squid failed to start {$suffix}", @implode("\n", $GLOBALS["LOGS"]) . "\n{$executed}");
        system_admin_events("Starting Squid failed to start\n" . @implode("\n", $GLOBALS["LOGS"]), __FUNCTION__, __FILE__, __LINE__, "proxy");
        return;
    }
    SendLogs("Starting Squid Tests if it listen all connections....");
    for ($i = 0; $i < 10; $i++) {
        build_progress_start("{checking} {$i}/10", 90);
        if (is_started()) {
            SendLogs("Starting squid listen All connections OK");
            break;
        }
        SendLogs("Starting squid listen All connections... waiting {$i}/10");
        sleep(1);
    }
    $took = $unix->distanceOfTimeInWords($t1, time());
    $nohup = $unix->find_program("nohup");
    SendLogs("Starting Squid success to start PID {$pid}...");
    if (function_exists("debug_backtrace")) {
        $trace = debug_backtrace();
        if (isset($trace[1])) {
            $sourcefunction = $trace[1]["function"];
            $sourceline = $trace[1]["line"];
            $executed = "Executed by {$sourcefunction}() line {$sourceline}\nusing argv:{$GLOBALS["ARGVS"]}\n";
        }
    }
    $php5 = $unix->LOCATE_PHP5_BIN();
    taskset();
    build_progress_start("Restarting cache-tail", 91);
    shell_exec("{$nohup} /etc/init.d/cache-tail restart >/dev/null 2>&1 &");
    build_progress_start("Restarting access-tail", 92);
    shell_exec("{$nohup} /etc/init.d/squid-tail restart >/dev/null 2>&1 &");
    build_progress_start("Restarting auth-tail", 93);
    shell_exec("{$nohup} /etc/init.d/auth-tail restart >/dev/null 2>&1 &");
    build_progress_start("{done}", 100);
    system_admin_events("Starting Squid success to start PID {$pid} took {$took}\n" . @implode("\n", $GLOBALS["LOGS"]), __FUNCTION__, __FILE__, __LINE__, "proxy");
    SendLogs("Starting Squid done...");
    if (is_file("/usr/share/artica-postfix/ressources/databases/ALL_SQUID_STATUS")) {
        @unlink("/usr/share/artica-postfix/ressources/databases/ALL_SQUID_STATUS");
    }
}
}
if ($argv[1] == "--progress") {
    restart_progress();
    exit;
}
$users = new usersMenus();
if ($users->WEBSTATS_APPLIANCE) {
    iptables_delete_all();
    die;
}
if (!$users->SQUID_INSTALLED) {
    iptables_delete_all();
    die;
}
$sysctl = $unix->find_program("sysctl");
$pids = $unix->PIDOF_PATTERN_ALL("exec.squid.transparent.php");
if ($GLOBALS["OUTPUT"]) {
    echo "Starting......: " . date("H:i:s") . " instances:" . count($pids) . "\n";
}
if (count($pids) > 2) {
    if ($GLOBALS["OUTPUT"]) {
        echo "Starting......: " . date("H:i:s") . " Too many instances " . count($pids) . " starting squid, kill them!\n";
    }
    $mypid = getmypid();
    while (list($pid, $ligne) = each($pids)) {
        if ($pid == $mypid) {
            continue;
        }
        if ($GLOBALS["OUTPUT"]) {
            echo "Starting......: " . date("H:i:s") . " killing {$pid}\n";
        }
Beispiel #9
0
 }
 if ($argv[1] == "--videocache") {
     $conf[] = videocache();
     $conf[] = videocache_scheduler();
     $conf[] = videocache_clients();
     echo @implode("\n", $conf);
     die;
 }
 if ($argv[1] == "--functions") {
     $arr = get_defined_functions();
     print_r($arr);
     die;
 }
 if ($argv[1] == "--all-squid") {
     $unix = new unix();
     $processes = $unix->PIDOF_PATTERN_ALL(basename(__FILE__) . ".*?{$argv[1]}", true);
     events(count($processes) . " Running  " . @implode(";", $processes), "{$argv[1]}", __LINE__);
     if (count($processes) > 2) {
         while (list($num, $pid) = each($processes)) {
             events("Killing pid {$pid}  ", "MAIN", __LINE__);
             $unix->KILL_PROCESS($pid, 9);
         }
         $processes = $unix->PIDOF_PATTERN_ALL(basename(__FILE__) . ".*?{$argv[1]}", true);
         events(count($processes) . " Running  " . @implode(";", $processes), "{$argv[1]}", __LINE__);
     }
     if (count($processes) > 0) {
         events("ALL_SQUID: Processes already exists, aborting", "{$argv[1]}", __LINE__);
         die;
     }
     $cachefile = "/usr/share/artica-postfix/ressources/databases/ALL_SQUID_STATUS";
     $GLOBALS["DISABLE_WATCHDOG"] = true;
Beispiel #10
0
function status()
{
    $unix = new unix();
    $phpcgi = $unix->LIGHTTPD_PHP5_CGI_BIN_PATH();
    $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid";
    $pidtime = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".time";
    $pid = $unix->get_pid_from_file($pidfile);
    if ($unix->process_exists($pid, basename(__FILE__))) {
        $time = $unix->PROCCESS_TIME_MIN($pid);
        if ($GLOBALS["OUTPUT"]) {
            echo "Starting......: " . date("H:i:s") . " [INIT]: Already Artica task running PID {$pid} since {$time}mn\n";
        }
        return;
    }
    if (!$GLOBALS["VERBOSE"]) {
        $timeExec = $unix->file_time_min($pidtime);
        if ($timeExec < 240) {
            return;
        }
    }
    @unlink($pidtime);
    @file_put_contents($pidtime, time());
    @file_put_contents($pidfile, getmypid());
    $pid = LIGHTTPD_PID();
    $unix = new unix();
    if ($unix->process_exists($pid)) {
        $timepid = $unix->PROCCESS_TIME_MIN($pid);
        if ($GLOBALS["OUTPUT"]) {
            echo "Starting......: " . date("H:i:s") . " [INIT]: Framework service running {$pid} since {$timepid}Mn...\n";
        }
    } else {
        FrmToSyslog("Framework service stopped");
        if ($GLOBALS["OUTPUT"]) {
            echo "Starting......: " . date("H:i:s") . " [INIT]: Framework service stopped...\n";
        }
        start(true);
        return;
    }
    $MAIN_PID = $pid;
    $phpcgi = $unix->LIGHTTPD_PHP5_CGI_BIN_PATH();
    $kill = $unix->find_program("kill");
    $array = $unix->PIDOF_PATTERN_ALL($phpcgi);
    if (count($array) == 0) {
        if ($GLOBALS["OUTPUT"]) {
            echo "Starting......: " . date("H:i:s") . " [INIT]: no php-cgi processes...\n";
        }
        return;
    }
    while (list($pid, $line) = each($array)) {
        $username = $unix->PROCESS_GET_USER($pid);
        if ($username == null) {
            continue;
        }
        if ($username != "root") {
            continue;
        }
        $time = $unix->PROCCESS_TIME_MIN($pid);
        $arrayPIDS[$pid] = $time;
        $ppid = $unix->PPID_OF($pid);
        if ($time > 20) {
            if ($ppid != $MAIN_PID) {
                if ($GLOBALS["VERBOSE"]) {
                    echo "killing {$pid} {$time}mn ppid:{$ppid}/{$MAIN_PID}\n";
                }
                unix_system_kill_force($pid);
            }
        }
    }
    if ($GLOBALS["OUTPUT"]) {
        echo "Starting......: " . date("H:i:s") . " [INIT]: " . count($arrayPIDS) . " php-cgi processes...\n";
    }
}
Beispiel #11
0
function restart_ldap()
{
    $unix = new unix();
    $MYPID_FILE = "/etc/artica-postfix/pids/restart_ldap.pid";
    $pid = $unix->get_pid_from_file($MYPID_FILE);
    if (!is_file("/etc/artica-postfix/settings/Daemons/EnableOpenLDAP")) {
        @file_put_contents("/etc/artica-postfix/settings/Daemons/EnableOpenLDAP", 1);
        @chmod("/etc/artica-postfix/settings/Daemons/EnableOpenLDAP", 0755);
    }
    $EnableOpenLDAP = intval(@file_get_contents("/etc/artica-postfix/settings/Daemons/EnableOpenLDAP"));
    if ($unix->process_exists($pid, basename(__FILE__))) {
        echo "slapd: [INFO] Artica task already running pid {$pid}\n";
        restart_ldap_progress("{failed}  [" . __LINE__ . "]", 110);
        die;
    }
    $pids = $unix->PIDOF_PATTERN_ALL(basename(__FILE__) . ".*?--restart", true);
    if (count($pids) > 0) {
        while (list($i, $line) = each($pids)) {
            echo "slapd: [INFO] Artica task already executed PID:{$i}... aborting\n";
        }
        restart_ldap_progress("{failed}", 110);
        die;
    }
    if ($GLOBALS["MONIT"]) {
        squid_admin_mysql(0, "Monit (Watchdog) Ask to restart OpenLDAP service...", null, __FILE__, __LINE__);
        system_admin_mysql(0, "Monit (Watchdog) Ask to restart OpenLDAP service...", null, __FILE__, __LINE__);
    }
    if (!$GLOBALS["FORCE"]) {
        $lastexecution = $unix->file_time_min($MYPID_FILE);
        if ($lastexecution == 0) {
            $unix->ToSyslog("Restarting the OpenLDAP by `{$GLOBALS["BY_FRAMEWORK"]}` aborted this command must be executed minimal each 1mn", false, basename(__FILE__));
            echo "slapd: [INFO] this command must be executed minimal each 1mn\n";
            die;
        }
    }
    @unlink($MYPID_FILE);
    restart_ldap_progress("{build_init_script}", 5);
    $INITD_PATH = $unix->SLAPD_INITD_PATH();
    echo "Script: {$INITD_PATH}\n";
    buildscript();
    if (!is_file($INITD_PATH)) {
        restart_ldap_progress("{build_init_script} {failed}", 110);
        return;
    }
    @file_put_contents($MYPID_FILE, getmypid());
    $unix->ToSyslog("Restarting the OpenLDAP daemon by `{$GLOBALS["BY_FRAMEWORK"]}`", false, basename(__FILE__));
    restart_ldap_progress("{stopping_service}", 10);
    stop_ldap(true);
    if ($EnableOpenLDAP == 1) {
        $php = $unix->LOCATE_PHP5_BIN();
        shell_exec("/etc/init.d/monit restart");
        restart_ldap_progress("{starting_service}", 40);
        start_ldap(true);
    }
}
function Paranoid($nopid = false)
{
    $unix = new unix();
    if (!$nopid) {
        $mypid = getmypid();
        if (isset($argv[1])) {
            $argv = $argv[1];
        }
        $pids = $unix->PIDOF_PATTERN_ALL(basename(__FILE__) . ".*?{$argv}");
        if (count($pids) > 1) {
            while (list($num, $ligne) = each($pids)) {
                $cmdline = @file_get_contents("/proc/{$num}/cmdline");
                echo "Starting......: " . date("H:i:s") . " [SERV]: [{$mypid}] Already process PID {$num} {$cmdline} exists..\n";
                echo "Starting......: " . date("H:i:s") . " [SERV]: [{$mypid}] Running " . @file_get_contents("/proc/{$num}/cmdline") . "\n";
            }
            build_progress_paranoid("{already_process_exists_try_later}", 110);
            die;
        }
    }
    $ParanoidBlockerEmergency = intval(@file_get_contents("/etc/artica-postfix/settings/Daemons/ParanoidBlockerEmergency"));
    $UfdbEnableParanoidMode = intval(@file_get_contents("/etc/artica-postfix/settings/Daemons/UfdbEnableParanoidMode"));
    if ($ParanoidBlockerEmergency == 1) {
        if (isInSquid()) {
            build_progress_paranoid("{reconfigure}", 70);
            $php = $unix->LOCATE_PHP5_BIN();
            system("{$php} /usr/share/artica-postfix/exec.squid.php --build --force");
        }
        build_progress_paranoid("{emergency}!!!", 110);
        @unlink("/etc/squid3/paranoid.db");
        return;
    }
    if ($UfdbEnableParanoidMode == 0) {
        @unlink("/etc/squid3/paranoid.db");
        if (isInSquid()) {
            build_progress_paranoid("{reconfigure}", 70);
            $php = $unix->LOCATE_PHP5_BIN();
            system("{$php} /usr/share/artica-postfix/exec.squid.php --build --force");
        }
        build_progress_paranoid("{disabled}!!!", 110);
        return;
    }
    $sock = new sockets();
    if ($sock->EnableUfdbGuard() == 0) {
        build_progress_paranoid("{webfiltering} {disabled}!!!", 110);
        @unlink("/etc/squid3/paranoid.db");
        return;
    }
    build_progress_paranoid("{webfiltering} {enabled} OK", 25);
    $ipClass = new IP();
    $SquidFam = new squid_familysite();
    $q = new mysql_squid_builder();
    $ARRAY = array();
    $results = $q->QUERY_SQL("SELECT pattern, object FROM webfilters_paranoid");
    while ($ligne = mysql_fetch_assoc($results)) {
        $ligne["pattern"] = trim(strtolower($ligne["pattern"]));
        if ($ligne["pattern"] == null) {
            continue;
        }
        build_progress_paranoid("{$ligne["pattern"]}", 50);
        $ARRAY[$ligne["object"]][$ligne["pattern"]] = true;
    }
    $src = array();
    $dstdomain = array();
    if (isset($ARRAY["src"])) {
        while (list($pattern, $xtrace) = each($ARRAY["src"])) {
            if (!$ipClass->isValid($pattern)) {
                continue;
            }
            $MAIN["IPSRC"][$pattern] = true;
        }
    }
    if (isset($ARRAY["dstdomain"])) {
        while (list($pattern, $xtrace) = each($ARRAY["dstdomain"])) {
            $MAIN["DOMS"][$pattern] = true;
        }
    }
    if (isset($ARRAY["dstdomainsrc"])) {
        while (list($pattern, $xtrace) = each($ARRAY["dstdomainsrc"])) {
            $fr = explode("/", $pattern);
            if (!$ipClass->isValid($fr[0])) {
                continue;
            }
            if ($fr[1] == null) {
                continue;
            }
            $fr[1] = $SquidFam->GetFamilySites($fr[1]);
            $MAIN["IPDOM"][trim($fr[0])][trim(strtolower($fr[1]))] = true;
        }
    }
    if (!isInSquid()) {
        build_progress_paranoid("{reconfigure}", 70);
        $php = $unix->LOCATE_PHP5_BIN();
        system("{$php} /usr/share/artica-postfix/exec.squid.php --build --force");
    }
    if (!isInSquid()) {
        build_progress_paranoid("{failed}", 110);
        return;
    }
    build_progress_paranoid("{enabled} OK", 80);
    if ($GLOBALS["RSQUID"]) {
        $squidbin = $unix->LOCATE_SQUID_BIN();
        shell_exec("{$squidbin} -k reconfigure");
    }
    @file_put_contents("/etc/squid3/paranoid.db", serialize($MAIN));
    build_progress_paranoid("{done}", 100);
}
function xstart()
{
    $T1 = time();
    $curl = new ccurl();
    $unix = new unix();
    $GLOBALS["MYPID"] = getmypid();
    $pidfile = "/etc/artica-postfix/pids/windowupdate.processor.pid";
    $pid = $unix->get_pid_from_file($pidfile);
    if ($unix->process_exists($pid, basename(__FILE__))) {
        die;
    }
    $pids = $unix->PIDOF_PATTERN_ALL(basename(__FILE__), true);
    if (count($pids) > 0) {
        while (list($i, $line) = each($pids)) {
            events("Already executed PID:{$i}... aborting ", __LINE__);
        }
        die;
    }
    $TEMPDIR = $unix->TEMP_DIR() . "/WindowsUpdates";
    $rm = $unix->find_program("rm");
    @file_put_contents($pidfile, $GLOBALS["MYPID"]);
    if (is_dir($TEMPDIR)) {
        shell_exec("{$rm} -rf {$TEMPDIR}");
    }
    @mkdir($TEMPDIR, 0755, true);
    $WindowsUpdateMaxPartition = intval(@file_get_contents("/etc/artica-postfix/settings/Daemons/WindowsUpdateMaxPartition"));
    if ($WindowsUpdateMaxPartition == 0) {
        $WindowsUpdateMaxPartition = 80;
    }
    $CheckPartitionPercentage = CheckPartitionPercentage();
    if ($CheckPartitionPercentage > $WindowsUpdateMaxPartition) {
        $time = $unix->file_time_min("/etc/squid3/WindowsUpdatePartitionExceed");
        if ($time > 10) {
            @unlink("/etc/squid3/WindowsUpdatePartitionExceed");
            events("Failed: Storage Partition exceed {$WindowsUpdateMaxPartition}%, Stopping retreivals", __LINE__);
            @touch("/etc/squid3/WindowsUpdatePartitionExceed");
            DirectorySize();
        }
        return;
    }
    $WindowsUpdateInProduction = intval(@file_get_contents("/etc/artica-postfix/settings/Daemons/WindowsUpdateInProduction"));
    if ($WindowsUpdateInProduction == 0) {
        if ($unix->IsProductionTime()) {
            $time = $unix->file_time_min("/etc/artica-postfix/pids/WindowsUpdateInProduction");
            if ($time > 15) {
                @unlink("/etc/artica-postfix/pids/WindowsUpdateInProduction");
                @touch("/etc/artica-postfix/pids/WindowsUpdateInProduction");
                events("INFO: Aborting, No download during production time", __LINE__);
                DirectorySize();
            }
            return;
        }
    }
    if (is_file("/etc/squid3/WindowsUpdatePartitionExceed")) {
        @unlink("/etc/squid3/WindowsUpdatePartitionExceed");
    }
    $q = new mysql_squid_builder();
    $sql = "CREATE TABLE IF NOT EXISTS `windowsupdate` (\n\t\t\t`filemd5` VARCHAR( 90 ) NOT NULL ,\n\t\t\t`zDate` DATETIME NOT NULL ,\n\t\t\t`zUri` VARCHAR( 255 ) NOT NULL ,\n\t\t\t`localpath` VARCHAR( 255 ) NOT NULL ,\n\t\t\t`filesize` BIGINT UNSIGNED DEFAULT '0',\n\t\t\t INDEX ( `filesize` ,`zDate`) ,\n\t\t\t KEY `localpath`(`localpath`),\n\t\t\t KEY `zUri`(`zUri`),\n\t\t\t PRIMARY KEY (`filemd5`)) ENGINE=MYISAM;";
    $q->QUERY_SQL($sql);
    if (!$q->ok) {
        events("MySQL Failed {$q->mysql_error}", __LINE__);
        die;
    }
    $GLOBALS["WindowsUpdateMaxToPartialQueue"] = intval(@file_get_contents("/etc/artica-postfix/settings/Daemons/WindowsUpdateMaxToPartialQueue"));
    if ($GLOBALS["WindowsUpdateMaxToPartialQueue"] == 0) {
        $GLOBALS["WindowsUpdateMaxToPartialQueue"] = 350;
    }
    $GLOBALS["WindowsUpdateCachingDir"] = @file_get_contents("/etc/artica-postfix/settings/Daemons/WindowsUpdateCachingDir");
    if ($GLOBALS["WindowsUpdateCachingDir"] == null) {
        $GLOBALS["WindowsUpdateCachingDir"] = "/home/squid/WindowsUpdate";
    }
    $filepath = "{$GLOBALS["WindowsUpdateCachingDir"]}/Queue.log";
    $WindowsUpdateDownTimeout = intval(@file_get_contents("/etc/artica-postfix/settings/Daemons/WindowsUpdateDownTimeout"));
    if ($WindowsUpdateDownTimeout == 0) {
        $WindowsUpdateDownTimeout = 600;
    }
    $WindowsUpdateMaxToPartialQueue = $GLOBALS["WindowsUpdateMaxToPartialQueue"] * 1000;
    $WindowsUpdateMaxToPartialQueue = $WindowsUpdateMaxToPartialQueue * 1000;
    $LinesCount = $unix->COUNT_LINES_OF_FILE($filepath);
    if (!is_file($filepath)) {
        return;
    }
    $md5start = md5_file($filepath);
    $handle = @fopen($filepath, "r");
    if (!$handle) {
        events("Fopen failed on {$filepath}", __LINE__);
        return false;
    }
    $NEWBUFFER = array();
    $URLALREADY = array();
    $FinalSize = 0;
    $FF = 0;
    $c = 0;
    while (!feof($handle)) {
        $buffer = trim(fgets($handle));
        $c++;
        if ($buffer == null) {
            continue;
        }
        $TR = explode("|||", $buffer);
        $prc = $c / $LinesCount;
        $prc = round($prc * 100);
        $LocalFile = $TR[0];
        $URI = $TR[1];
        $ExpectedSize = 0;
        if (strpos($URI, $GLOBALS["WindowsUpdateCachingDir"]) > 0) {
            events("FOUND! directory in  URI", __LINE__);
            $TTR = explode($GLOBALS["WindowsUpdateCachingDir"], $URI);
            $URI = $TTR[0];
            $LocalFile = "{$GLOBALS["WindowsUpdateCachingDir"]}{$TTR[1]}";
            events("FOUND! URI:{$URI}", __LINE__);
            events("FOUND! NEXT:{$LocalFile}", __LINE__);
        }
        $BASENAMELL = basename($LocalFile);
        if (strlen($BASENAMELL) > 20) {
            $BASENAMELL = substr($BASENAMELL, 0, 17) . "...";
        }
        build_progressG("{$BASENAMELL} {$c}/{$LinesCount} {files}", $prc);
        if (isset($URLALREADY[$URI])) {
            continue;
        }
        $URLALREADY[$URI] = true;
        if (isBlacklisted($URI)) {
            events(basename($URI) . " blacklisted...");
            continue;
        }
        if (is_file($LocalFile)) {
            $size = @filesize($LocalFile);
            if ($size > 5) {
                events("SKIP " . basename($LocalFile) . " " . xFormatBytes($size / 1024), __LINE__);
                update_mysql($LocalFile, $URI);
                continue;
            } else {
                @unlink($LocalFile);
            }
        }
        $dirname = dirname($LocalFile);
        if (!is_dir($dirname)) {
            @mkdir($dirname, true, 0755);
        }
        $curl = new ccurl($URI);
        $Headers = $curl->getHeaders();
        $TIMEDOWN = time();
        $TMPFILE = "{$TEMPDIR}/" . basename($LocalFile);
        $GLOBALS["previousProgress"] = 0;
        $GLOBALS["DOWNLOADED_FILE"] = basename($LocalFile);
        $GLOBALS["TMPFILE"] = $TMPFILE;
        $ExpectedSize = GetTargetedSize($URI);
        if ($ExpectedSize == 0) {
            events("Failed to download {$URI} ( unable to get expected size)", __LINE__);
            continue;
        }
        if ($ExpectedSize > $WindowsUpdateMaxToPartialQueue) {
            $ExpectedSizeText = xFormatBytes($ExpectedSize / 1024, true);
            events(basename($URI) . " ({$ExpectedSizeText} {$ExpectedSize}/{$WindowsUpdateMaxToPartialQueue}) Limit {$WindowsUpdateMaxToPartialQueue} to BigFiles queue", __LINE__);
            AddToPartialQueue($URI, $ExpectedSize, $LocalFile);
            continue;
        }
        $curl = new ccurl($URI);
        $curl->WriteProgress = true;
        $curl->Timeout = $WindowsUpdateDownTimeout * 60;
        $curl->ProgressFunction = "xdownload_progress";
        events("Downloading " . basename($URI) . " to {$TMPFILE} (" . xFormatBytes($ExpectedSize / 1024, true) . " max:{$WindowsUpdateDownTimeout} Minutes)", __LINE__);
        if (!$curl->GetFile($TMPFILE)) {
            events("Failed: TMP: &laquo;{$TMPFILE}&raquo;", __LINE__);
            events("Failed: URL: &laquo;{$URI}&raquo;", __LINE__);
            events("Failed: After: " . $unix->distanceOfTimeInWords($TIMEDOWN, time(), true), __LINE__);
            events("Failed: With error: {$curl->error} http code: {$curl->CURLINFO_HTTP_CODE} (" . count($curl->CURL_ALL_INFOS) . ") infos", __LINE__);
            reset($curl->CURL_ALL_INFOS);
            while (list($index, $value) = each($curl->CURL_ALL_INFOS)) {
                events("Failed: &laquo;{$index}&raquo; [{$value}]", __LINE__);
            }
            if ($curl->CURLINFO_HTTP_CODE == 404) {
                continue;
            }
            @unlink($TMPFILE);
            $NEWBUFFER[] = "{$buffer}";
            continue;
        }
        if (!is_file($TMPFILE)) {
            events("Fatal {$TMPFILE}: no such file", __LINE__);
            continue;
        }
        $size = filesize($TMPFILE);
        $sizeT = xFormatBytes($size / 1024);
        if ($size < 5) {
            @unlink($TMPFILE);
            events("Failed: File less than 5 Bytes ({$size}), aborting", __LINE__);
            continue;
        }
        if ($ExpectedSize > 0) {
            if ($size != $ExpectedSize) {
                $ExpectedSizeT = xFormatBytes($ExpectedSize / 1024);
                events("Failed: corrupted download " . basename($URI) . " expected size {$ExpectedSizeT}/{$ExpectedSize} current:({$sizeT}/{$size})", __LINE__);
                @unlink($TMPFILE);
                continue;
            }
        }
        if (!@copy($TMPFILE, $LocalFile)) {
            @unlink($TMPFILE);
            events("Failed: Translating to {$LocalFile}", __LINE__);
            $NEWBUFFER[] = "{$buffer}";
            continue;
        }
        events("Success: " . basename($TMPFILE) . " ({$sizeT})", __LINE__);
        @unlink($TMPFILE);
        $FF++;
        $size = @filesize($LocalFile);
        $FinalSize = $FinalSize + $size;
        update_mysql($LocalFile, $URI);
    }
    $took = $unix->distanceOfTimeInWords($T1, time(), true);
    if ($FinalSize > 0) {
        $CURLINFO_SPEED_DOWNLOAD = $curl->CURL_ALL_INFOS["CURLINFO_SPEED_DOWNLOAD"];
        events("Downloaded {$FF} files for " . xFormatBytes($FinalSize / 1024, true) . " ({$CURLINFO_SPEED_DOWNLOAD}) took: {$took}", __LINE__);
    }
    $md5finish = md5_file($filepath);
    if (count($NEWBUFFER) > 0) {
        events("Retry " . count($NEWBUFFER) . " requests next time...", __LINE__);
        @file_put_contents($filepath, @implode("\n", $NEWBUFFER));
    } else {
        events("No new file downloaded....", __LINE__);
        events("Removing queue {$filepath}", __LINE__);
        @unlink($filepath);
    }
    DirectorySize();
    events("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; * * * END TOOK: {$took} * * *", __LINE__);
}
Beispiel #14
0
function ucarp_all_pid($eth = null)
{
    $unix = new unix();
    $ucarp_bin = $unix->find_program("ucarp");
    if ($eth != null) {
        $eth = ".*?--interface={$eth}";
    }
    return $unix->PIDOF_PATTERN_ALL("{$ucarp_bin}{$eth}");
}
Beispiel #15
0
function build()
{
    build_progress("{reconfigure} (1)", 2);
    if ($GLOBALS["VERBOSE"]) {
        echo "Running build...\n";
    }
    $unix = new unix();
    $sock = new sockets();
    $users = new usersMenus();
    $forceCMD = null;
    $argv = null;
    $PHP = $unix->LOCATE_PHP5_BIN();
    $mypid = getmypid();
    if (isset($argv[1])) {
        $argv = $argv[1];
    }
    $pids = $unix->PIDOF_PATTERN_ALL(basename(__FILE__) . ".*?{$argv}");
    if (count($pids) > 1) {
        build_progress("{already_process_exists_try_later}", 110);
        while (list($num, $ligne) = each($pids)) {
            $cmdline = @file_get_contents("/proc/{$num}/cmdline");
            echo "Starting......: " . date("H:i:s") . " [SERV]: [{$mypid}] Already process PID {$num} {$cmdline} exists..\n";
            echo "Starting......: " . date("H:i:s") . " [SERV]: [{$mypid}] Running " . @file_get_contents("/proc/{$num}/cmdline") . "\n";
        }
        die;
    }
    $EnableKerbAuth = $sock->GET_INFO("EnableKerbAuth");
    if (!is_numeric($EnableKerbAuth)) {
        $EnableKerbAuth = 0;
    }
    $EnableWebProxyStatsAppliance = $sock->GET_INFO("EnableWebProxyStatsAppliance");
    $EnableRemoteStatisticsAppliance = $sock->GET_INFO("EnableRemoteStatisticsAppliance");
    if (!is_numeric($EnableRemoteStatisticsAppliance)) {
        $EnableRemoteStatisticsAppliance = 0;
    }
    if (!is_numeric($EnableWebProxyStatsAppliance)) {
        $EnableWebProxyStatsAppliance = 0;
    }
    $UnlockWebStats = $sock->GET_INFO("UnlockWebStats");
    if (!is_numeric($UnlockWebStats)) {
        $UnlockWebStats = 0;
    }
    $ServiceFTPEnabled = intval($sock->GET_INFO("ServiceFTPEnabled"));
    if ($users->WEBSTATS_APPLIANCE) {
        $EnableWebProxyStatsAppliance = 1;
        $sock->SET_INFO("{$EnableWebProxyStatsAppliance}", 1);
    }
    if ($EnableWebProxyStatsAppliance == 1) {
        notify_remote_proxys();
    }
    if ($UnlockWebStats == 1) {
        $EnableRemoteStatisticsAppliance = 0;
    }
    //Vérifie le compte utilisateur.
    //------------------------------------------------------------------------------------------------------------------------------------------------------------
    $unix->CreateUnixUser("squid", "squid", "Squid Cache Service");
    $MustHave[] = "/etc/squid3/artica-meta/whitelist-nets.db";
    $MustHave[] = "/var/logs/cache.log";
    $MustHave[] = "/etc/squid3/squid-block.acl";
    $MustHave[] = "/etc/squid3/allowed-user-agents.acl";
    $MustHave[] = "/etc/squid3/GlobalAccessManager_auth.conf";
    $MustHave[] = "/etc/squid3/icap.conf";
    $MustHave[] = "/etc/squid3/GlobalAccessManager_url_rewrite.conf";
    $MustHave[] = "/etc/squid3/GlobalAccessManager_deny_cache.conf";
    $MustHave[] = "/etc/squid3/GlobalAccessManager_deny.conf";
    $MustHave[] = "/etc/squid3/squid-block.acl";
    $MustHave[] = "/etc/squid3/clients_ftp.acl";
    $MustHave[] = "/etc/squid3/allowed-user-agents.acl";
    $MustHave[] = "/etc/squid3/whitelisted-computers-by-mac.acl";
    while (list($none, $path) = each($MustHave)) {
        echo "Starting......: " . date("H:i:s") . " [SYS]: checking {$path}\n";
        if (!is_file($path)) {
            @touch($path);
        }
        @chown($path, "squid");
        @chgrp($path, "squid");
    }
    if ($GLOBALS["FORCE"]) {
        $forceCMD = " --force";
    }
    $squidbin = $unix->LOCATE_SQUID_BIN();
    if (!is_file($squidbin)) {
        build_progress("{squid_binary_not_found}", 110);
        echo "Starting......: " . date("H:i:s") . " [SERV]: Unable to stat squid binary, aborting..\n";
        die;
    }
    $EXEC_TIME_FILE = "/etc/artica-postfix/" . basename(__FILE__) . ".build.time";
    if (!$GLOBALS["FORCE"]) {
        $time = $unix->file_time_min($EXEC_TIME_FILE);
        if ($time == 0) {
            build_progress("Failed! Only one config per minute !!!", 110);
            echo "Starting......: " . date("H:i:s") . " [SERV]: Only one config per minute...\n";
            die;
        }
    }
    @unlink($EXEC_TIME_FILE);
    @file_put_contents($EXEC_TIME_FILE, time());
    if ($GLOBALS["EMERGENCY"]) {
        squid_admin_mysql(0, "Reconfiguring Proxy service after Emergency enabled", null, __FILE__, __LINE__);
    }
    $TimeStart = time();
    $EXEC_PID_FILE = "/etc/artica-postfix/" . basename(__FILE__) . ".build.pid";
    $kill = $unix->find_program("kill");
    $pid = @file_get_contents($EXEC_PID_FILE);
    if ($unix->process_exists($pid, basename(__FILE__))) {
        $TimePid = $unix->PROCCESS_TIME_MIN($pid);
        if ($TimePid > 30) {
            posix_kill(intval($pid), 9);
        } else {
            if (!$GLOBALS["FORCE"]) {
                print "Starting......: " . date("H:i:s") . " Checking (L." . __LINE__ . ") Squid Already executed pid {$pid} since {$TimePid}mn ...\n";
                die;
            }
        }
    }
    echo "Starting......: " . date("H:i:s") . " [SERV]: is connected to remote appliance ? `{$EnableRemoteStatisticsAppliance}`\n";
    if ($EnableRemoteStatisticsAppliance == 1) {
        $r = new squid_stats_appliance();
        echo "Starting......: " . date("H:i:s") . " [SERV]: ################################\n";
        echo "Starting......: " . date("H:i:s") . " [SERV]: # This server is connected to: #\n";
        echo "Starting......: " . date("H:i:s") . " [SERV]: # {$r->URI} #\n";
        echo "Starting......: " . date("H:i:s") . " [SERV]: ################################\n";
        remote_appliance_restore_tables();
    }
    build_progress("{reconfigure} (1)", 5);
    if (!PortsConversion()) {
        build_progress("{reconfigure} {failed} !PortsConversion", 110);
        return;
    }
    squid_reconfigure_build_tool();
    build_progress("{reconfigure}", 10);
    squid_pactester();
    build_progress("{reconfigure}", 15);
    $childpid = posix_getpid();
    $sock = new sockets();
    $squid_user = SquidUser();
    $SQUID_CONFIG_PATH = $unix->SQUID_CONFIG_PATH();
    $PHP = LOCATE_PHP5_BIN2();
    $NOHUP = $unix->find_program("nohup");
    build_progress("{reconfigure}", 20);
    @file_put_contents($EXEC_PID_FILE, $childpid);
    if (is_file("/etc/squid3/mime.conf")) {
        shell_exec("/bin/chown squid:squid /etc/squid3/mime.conf");
    }
    $EnableKerbAuth = $sock->GET_INFO("EnableKerbAuth");
    if (!is_numeric("{$EnableKerbAuth}")) {
        $EnableKerbAuth = 0;
    }
    if (!is_dir("/usr/share/squid-langpack")) {
        TemplatesInMysql(true);
        exit;
    }
    echo "Starting......: " . date("H:i:s") . " Checking squid kerberos authentification is set to {$EnableKerbAuth}\n";
    echo "Starting......: " . date("H:i:s") . " Checking squid certificate\n";
    build_progress("{reconfigure} Check database", 25);
    checkdatabase();
    build_progress("{reconfigure} certificates", 30);
    certificate_generate();
    build_progress("{reconfigure}", 35);
    remote_appliance_restore_tables();
    build_progress("{reconfigure}", 40);
    echo "Starting......: " . date("H:i:s") . " Instanciate squid library..\n";
    $squid = new squidbee();
    $squidbin = $unix->find_program("squid3");
    echo "Starting......: " . date("H:i:s") . " checking squid binaries..\n";
    if (!is_file($squidbin)) {
        $squidbin = $unix->find_program("squid");
    }
    echo "Starting......: " . date("H:i:s") . " Binary: {$squidbin}\n";
    echo "Starting......: " . date("H:i:s") . " Config: {$SQUID_CONFIG_PATH}\n";
    echo "Starting......: " . date("H:i:s") . " User..: {$squid_user}\n";
    echo "Starting......: " . date("H:i:s") . " Checking blocked sites\n";
    build_progress("{reconfigure} {building} NET ADS", 45);
    shell_exec("{$NOHUP} {$PHP} " . basename(__FILE__) . "/exec.squid.netads.php >/dev/null 2>&1 &");
    echo "Starting......: " . date("H:i:s") . " Building master configuration\n";
    $squid->ASROOT = true;
    echo "Starting......: " . date("H:i:s") . " Checking Watchdog\n";
    build_progress("{reconfigure} checking Watchdog settings", 46);
    watchdog_config();
    build_progress("{reconfigure} build errors", 47);
    errors_details_txt();
    build_progress("{reconfigure} Checking caches", 48);
    BuildCaches(true);
    build_progress("{reconfigure} Check files and security", 49);
    CheckFilesAndSecurity();
    build_progress("{reconfigure} Building schedules", 50);
    build_schedules(true);
    build_progress("{reconfigure} Building SSL passwords", 89);
    build_sslpasswords();
    build_progress("{reconfigure} Building blacklists", 90);
    build_blacklists();
    build_progress("{reconfigure} Building No caches list", 91);
    build_denycaches();
    build_progress("{reconfigure} Building {GLOBAL_ACCESS_CENTER}", 93);
    system("{$PHP} /usr/share/artica-postfix/exec.squid.global.access.php --nochek");
    build_progress("{reconfigure} Building main configuration", 94);
    if (!ApplyConfig()) {
        build_progress("Apply configuration failed", 110);
        echo "Starting......: " . date("H:i:s") . " Apply configuration failed....\n";
        return;
    }
    build_progress("{reconfigure} FTP Proxy service", 95);
    system("{$NOHUP} {$PHP} /usr/share/artica-postfix/exec.ftpproxy-multi.php --build >/dev/null 2>&1 &");
    build_progress("{reconfigure} Wan Compressor Proxy service", 95);
    system("{$NOHUP} {$PHP} /usr/share/artica-postfix/exec.wanproxy.php --build-squid >/dev/null 2>&1 &");
    build_progress("{checking_transparent_mode}", 95);
    if ($unix->IS_FIREHOLE_ACTIVE()) {
        build_progress("{restarting_firewall}", 95);
        system("{$PHP} /usr/share/artica-postfix/exec.firehol.php");
        system("/etc/init.d/firehol restart");
    } else {
        system("{$PHP} /usr/share/artica-postfix/exec.squid.transparent.php");
        system("{$PHP} /usr/share/artica-postfix/exec.secure.gateway.php");
        if (is_file("/etc/init.d/iptables-transparent")) {
            build_progress("{restarting_firewall}", 95);
            system("/etc/init.d/iptables-transparent restart");
        }
        if (is_file("/bin/iptables-parents.sh")) {
            build_progress("{restarting_firewall} (parent)", 95);
            system("/bin/iptables-parents.sh");
        }
        if (is_file("/bin/artica-secure-gateway.sh")) {
            build_progress("{restarting_firewall} (Secure gateway)", 95);
            shell_exec("/bin/artica-secure-gateway.sh");
        }
    }
    build_progress("{checking_wccp_mode}", 95);
    system("{$PHP} /usr/share/artica-postfix/exec.squid.wccp.php --reconfigure");
    build_progress("{checking_mikrotik_mode}", 95);
    system("{$PHP} /usr/share/artica-postfix/exec.mikrotik.php");
    build_progress("{reconfigure}", 96);
    $GLOBALS["OUTPUT"] = true;
    if ($GLOBALS["NOAPPLY"]) {
        build_progress("{reconfiguring_proxy_service} {success}", 100);
        return;
    }
    if (!$GLOBALS["RESTART"]) {
        build_progress("{reloading_service}", 91);
        if (!$GLOBALS["NORELOAD"]) {
            Reload_Squid();
        }
    }
    if ($GLOBALS["RESTART"]) {
        if (!$GLOBALS["NORELOAD"]) {
            build_progress("{stopping_service}", 91);
            system("{$PHP} /usr/share/artica-postfix/exec.squid.watchdog.php --stop {$forceCMD} --byForceReconfigure");
            build_progress("{starting_service}", 93);
            system("{$PHP} /usr/share/artica-postfix/exec.squid.watchdog.php --start {$forceCMD} --byForceReconfigure");
            build_progress("{starting_service}", 95);
        }
    }
    build_progress("{building} Cached Web frontend pages", 97);
    shell_exec("{$NOHUP} {$PHP} " . basename(__FILE__) . "/exec.cache.pages.php --force >/dev/null 2>&1 &");
    $BuildAllTemplatesDone = $sock->GET_INFO("BuildAllTemplatesDone");
    if (!is_numeric($BuildAllTemplatesDone)) {
        $BuildAllTemplatesDone = 0;
    }
    if ($BuildAllTemplatesDone == 0) {
        build_progress("{building} Templates schedules", 97);
        echo "Starting......: " . date("H:i:s") . " scheduling Building templates\n";
        sys_THREAD_COMMAND_SET("{$PHP} " . __FILE__ . " --tpl-save");
        $sock->SET_INFO("BuildAllTemplatesDone", 1);
    }
    build_progress("{building} Templates", 98);
    sys_THREAD_COMMAND_SET("{$PHP} " . __FILE__ . " --mysql-tpl");
    build_progress("{reconfiguring_proxy_service} {success}", 100);
    echo "Starting......: " . date("H:i:s") . " Done (Took: " . $unix->distanceOfTimeInWords($TimeStart, time()) . ")\n";
    die;
}
function start_squid($aspid = false)
{
    $GLOBALS["LOGS"] = array();
    $suffix = null;
    if ($GLOBALS["MONIT"]) {
        $suffix = " (by system monitor)";
    }
    if ($GLOBALS["BY_CACHE_LOGS"]) {
        $suffix = " (by cache.log monitor)";
    }
    if ($GLOBALS["BY_STATUS"]) {
        $suffix = " (by Artica monitor)";
    }
    if ($GLOBALS["BY_CLASS_UNIX"]) {
        $suffix = " (by Artica class.unix.inc)";
    }
    if ($GLOBALS["BY_FRAMEWORK"]) {
        $suffix = " (by Artica framework)";
    }
    if ($GLOBALS["BY_OTHER_SCRIPT"]) {
        $suffix = " (by other script)";
    }
    if ($GLOBALS["BY_ARTICA_INSTALL"]) {
        $suffix = " (by artica-install)";
    }
    if ($GLOBALS["BY_FORCE_RECONFIGURE"]) {
        $suffix = " (after building settings)";
    }
    $unix = new unix();
    $php = $unix->LOCATE_PHP5_BIN();
    $nohup = $unix->find_program("nohup");
    $sock = new sockets();
    $reconfigure = false;
    $SQUIDEnable = $sock->GET_INFO("SQUIDEnable");
    $NtpdateAD = $sock->GET_INFO("NtpdateAD");
    if (!is_numeric($SQUIDEnable)) {
        $SQUIDEnable = 1;
    }
    $kill = $unix->find_program("kill");
    if (!is_numeric($NtpdateAD)) {
        $NtpdateAD = 0;
    }
    $su_bin = $unix->find_program("su");
    $sysctl = $unix->find_program("sysctl");
    $squidbin = $unix->LOCATE_SQUID_BIN();
    if (!is_file($squidbin)) {
        if ($GLOBALS["OUTPUT"]) {
            echo "Restart......: Squid-cache, not installed\n";
        }
        return;
    }
    if ($GLOBALS["MONIT"]) {
        if (function_exists("debug_backtrace")) {
            $trace = debug_backtrace();
            if (isset($trace[1])) {
                $file = basename($trace[1]["file"]);
                $function = $trace[1]["function"];
                $line = $trace[1]["line"];
                $called = "Called by {$function}() from line {$line}";
            }
        }
        $pid = SQUID_PID();
        if ($unix->process_exists($pid)) {
            $ps = $unix->find_program("ps");
            $grep = $unix->find_program("grep");
            exec("{$ps} aux|{$grep} squid 2>&1", $results);
            squid_admin_mysql(2, "Monit ordered to start squid but squid is still in memory PID {$pid} ??", "I cannot accept this order, see details\n" . @implode("\n", $results), __FILE__, __LINE__);
            $squidpidfile = $unix->LOCATE_SQUID_PID();
            @file_put_contents($squidpidfile, $pid);
            return;
        }
        squid_admin_mysql(1, "Monit ordered to start squid", $called, __FILE__, __LINE__);
    }
    if ($SQUIDEnable == 0) {
        if ($GLOBALS["OUTPUT"]) {
            echo "Starting......: " . date("H:i:s") . " Squid is disabled...\n";
        }
        return;
    }
    if (is_file("/etc/artica-postfix/squid.lock")) {
        $time = $unix->file_time_min("/etc/artica-postfix/squid.lock");
        if ($time < 60) {
            if ($GLOBALS["OUTPUT"]) {
                echo "Starting......: " . date("H:i:s") . " Squid is locked (since {$time}Mn...\n";
            }
            return;
        }
        @unlink("/etc/artica-postfix/squid.lock");
    }
    $pids = $unix->PIDOF_PATTERN_ALL("exec.squid.watchdog.php --start");
    if (count($pids) > 2) {
        if ($GLOBALS["OUTPUT"]) {
            echo "Starting......: " . date("H:i:s") . " Too many instances " . count($pids) . " starting squid, kill them!\n";
        }
        $mypid = getmypid();
        while (list($pid, $ligne) = each($pids)) {
            if ($pid == $mypid) {
                continue;
            }
            if ($GLOBALS["OUTPUT"]) {
                echo "Starting......: " . date("H:i:s") . " killing {$pid}\n";
            }
            unix_system_kill_force($pid);
        }
    }
    if (!$aspid) {
        $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid";
        $pid = $unix->get_pid_from_file($pidfile);
        if ($unix->process_exists($pid, basename(__FILE__))) {
            $time = $unix->PROCCESS_TIME_MIN($pid);
            if ($time < 5) {
                Events("Task Already running PID {$pid} since {$time}mn");
                if ($GLOBALS["OUTPUT"]) {
                    echo "Starting......: " . date("H:i:s") . " Already task running PID {$pid} since {$time}mn, Aborting operation (" . __LINE__ . ")\n";
                }
                return;
            }
            squid_admin_mysql(0, "Too long time for artica task PID {$pid} running since {$time}mn", "Process will be killed");
            Tosyslog("Too long time for artica task PID {$pid} running since {$time}mn -> kill");
            unix_system_kill_force($pid);
        }
        @file_put_contents($pidfile, getmypid());
    }
    $squidbin = $unix->find_program("squid");
    if (!is_file($squidbin)) {
        $squidbin = $unix->find_program("squid3");
    }
    if (!is_file($squidbin)) {
        system_admin_events("Squid not seems to be installed", __FUNCTION__, __FILE__, __LINE__, "proxy");
        return;
    }
    @chmod($squidbin, 0755);
    $sock = new sockets();
    $DisableForceFCK = intval($sock->GET_INFO("DisableForceFCK"));
    if ($DisableForceFCK == 0) {
        if ($GLOBALS["OUTPUT"]) {
            echo "Starting......: " . date("H:i:s") . " Will force a checkdisk At next reboot\n";
        }
        @touch("/forcefsck");
    }
    start_prepare();
    $pid = SQUID_PID();
    if ($GLOBALS["CRASHED"]) {
        for ($i = 0; $i < 10; $i++) {
            sleep(1);
            $pid = SQUID_PID();
            if ($unix->process_exists($pid)) {
                continue;
            }
            break;
        }
        squid_admin_mysql(2, "No need to start Proxy service after a crash", "It seems the watchdog detect a crash but after 10s the proxy still running\nOperation is aborted", __FILE__, __LINE__);
        return;
    }
    if ($unix->process_exists($pid)) {
        $time = $unix->PROCCESS_TIME_MIN($pid);
        if ($GLOBALS["OUTPUT"]) {
            echo "Starting......: " . date("H:i:s") . " Proxy service already running pid {$pid} since {$time}mn\n";
        }
        system_admin_events("Squid seems to already running pid {$pid} since {$time}mn", __FUNCTION__, __FILE__, __LINE__, "proxy");
        return;
    }
    $unix->TCP_TUNE_SQUID_DEFAULT();
    $t1 = time();
    SendLogs("Checking caches...");
    $cacheBooster = new squidbooster();
    $cacheBooster->cache_booster();
    CheckStoreDirs(true);
    SendLogs("Checking caches done...");
    SendLogs("Checking Ports...");
    $array = CheckAllports();
    SendLogs("Checking " . count($array) . " ports");
    while (list($port, $ligne) = each($array)) {
        $portZ = $unix->PIDOF_BY_PORT($port);
        SendLogs("Checking port {$port} - " . count($portZ) . " process(es)");
        if (count($portZ) > 0) {
            while (list($pid, $ligne) = each($portZ)) {
                SendLogs("Checking port {$port} - killing pid {$pid}");
                shell_exec("kill -9 {$pid} >/dev/null 2>&1");
            }
        }
    }
    SendLogs("Starting squid {$squidbin}....");
    $echo = $unix->find_program("echo");
    $size = round(@filesize("/var/log/squid/cache.log") / 1024, 2) / 1024;
    if ($size > 10) {
        @copy("/var/log/squid/cache.log", "/var/log/squid/cache.log." . time());
        shell_exec("{$echo} \" \"> /var/log/squid/cache.log 2>&1");
    }
    @chmod($squidbin, 0755);
    @chmod("/var/log/squid", 0755);
    if (is_link("/var/log/squid")) {
        @chmod(readlink("/var/log/squid"), 0755);
    }
    squid_admin_mysql(1, "Starting Squid-cache service {$suffix}", @implode("\n", $GLOBALS["LOGS"]), __FILE__, __LINE__);
    exec("{$squidbin} -f /etc/squid3/squid.conf 2>&1", $GLOBALS["LOGS"]);
    $PRC = 40;
    $MAXPRC = 60;
    $AB = 0;
    for ($i = 0; $i < 10; $i++) {
        $PRC++;
        if ($PRC > $MAXPRC - 1) {
            $PRC = $MAXPRC - 1;
        }
        build_progress_restart("{starting_service}", $PRC);
        $pid = SQUID_PID();
        if ($unix->process_exists($pid)) {
            SendLogs("Starting squid started pid {$pid}...");
            break;
        }
        ToSyslog("Starting squid waiting {$i}/10s");
        SendLogs("Starting squid waiting {$i}/10s");
        sleep(1);
    }
    if (!$unix->process_exists($pid)) {
        SendLogs("Starting Squid failed to start...");
        ToSyslog("Starting Squid failed to start...");
        if (function_exists("debug_backtrace")) {
            $trace = debug_backtrace();
            if (isset($trace[1])) {
                $sourcefunction = $trace[1]["function"];
                $sourceline = $trace[1]["line"];
                $executed = "Executed by {$sourcefunction}() line {$sourceline}\nusing argv:{$GLOBALS["ARGVS"]}\n";
            }
        }
        squid_admin_mysql(0, "Squid failed to start {$suffix}", @implode("\n", $GLOBALS["LOGS"]) . "\n{$executed}");
        squid_admin_notifs("Starting Squid failed to start\n" . @implode("\n", $GLOBALS["LOGS"]) . "\n{$executed}", __FUNCTION__, __FILE__, __LINE__, "proxy");
        system_admin_events("Starting Squid failed to start\n" . @implode("\n", $GLOBALS["LOGS"]), __FUNCTION__, __FILE__, __LINE__, "proxy");
        return;
    }
    SendLogs("Starting Squid Tests if it listen all connections....");
    for ($i = 0; $i < 10; $i++) {
        if (is_started()) {
            SendLogs("Starting squid listen All connections OK");
            break;
        }
        SendLogs("Starting squid listen All connections... waiting {$i}/10");
        sleep(1);
    }
    $took = $unix->distanceOfTimeInWords($t1, time());
    $nohup = $unix->find_program("nohup");
    SendLogs("Starting Squid success to start PID {$pid}...");
    if (function_exists("debug_backtrace")) {
        $trace = debug_backtrace();
        if (isset($trace[1])) {
            $sourcefunction = $trace[1]["function"];
            $sourceline = $trace[1]["line"];
            $executed = "Executed by {$sourcefunction}() line {$sourceline}\nusing argv:{$GLOBALS["ARGVS"]}\n";
        }
    }
    $php5 = $unix->LOCATE_PHP5_BIN();
    system_admin_events("Starting Squid success to start PID {$pid} took {$took}\n" . @implode("\n", $GLOBALS["LOGS"]), __FUNCTION__, __FILE__, __LINE__, "proxy");
    SendLogs("Starting Squid finishing Reloading DNSMasq");
    shell_exec("{$nohup} /etc/init.d/dnsmasq reload >/dev/null 2>&1 &");
    SendLogs("Starting Squid finishing Starting Squid-cache tail");
    shell_exec("{$nohup} /etc/init.d/artica-postfix start squidcache-tail >/dev/null 2>&1 &");
    SendLogs("Starting Squid finishing Starting auth-cache tail");
    shell_exec("{$nohup} /etc/init.d/auth-tail restart >/dev/null 2>&1 &");
    SendLogs("Starting Squid finishing Reconfiguring proxy.pac scripts");
    shell_exec("{$nohup} {$php5} " . basename(__FILE__) . "/exec.proxy.pac.php --write 2>&1 &");
    SendLogs("Starting Squid done...");
    shell_exec("{$nohup} {$php5} " . basename(__FILE__) . "/exec.cache.pages.php --force >/dev/null 2>&1 &");
}
function STATS_BuildCurrentTable()
{
    $unix = new unix();
    $maxInstances = 3;
    $pids = $unix->PIDOF_PATTERN_ALL(basename(__FILE__));
    if (count($pids) > $maxInstances) {
        if ($GLOBALS["VERBOSE"]) {
            echo count($pids) . " > {$maxInstances}\n";
        }
        events(count($pids) . " > {$maxInstances}, aborting");
        die;
    }
    $pidefile = "/etc/artica-postfix/pids/exec.postfix-stats.php.STATS_BuildCurrentTable.pid";
    $pid = $unix->get_pid_from_file($pidefile);
    if ($unix->process_exists($pid)) {
        die;
    }
    file_put_contents($pidefile, $pid);
    $unix = new unix();
    $timefile = "/etc/artica-postfix/pids/exec.postfix-stats.php.STATS_BuildCurrentTable.time";
    $timesched = $unix->file_time_min($timefile);
    if ($timesched < 1) {
        events("{$timesched}Mn need at least 1mn");
        return;
    }
    @unlink($timefile);
    @file_put_contents($timefile, time());
    $Files = $unix->DirFiles("/home/artica/postfix/postfix/logger", "^realtime\\.[0-9]+\\.db");
    events(count($Files) . " realtime files to parse...");
    $current = "realtime." . date("YmdHi") . ".db";
    $c = 0;
    while (list($filename, $none) = each($Files)) {
        $c++;
        if ($filename == $current) {
            continue;
        }
        if (!preg_match("#^realtime\\.[0-9]+\\.db\$#", $filename, $re)) {
            continue;
        }
        $path = "/home/artica/postfix/postfix/logger/{$filename}";
        $LOCKFILE = "{$path}.LCK";
        if (isLocked($path)) {
            continue;
        }
        @unlink($LOCKFILE);
        @file_put_contents($LOCKFILE, getmypid());
        if (!STATS_BuildCurrentTable_parse($path)) {
            @unlink($LOCKFILE);
            continue;
        }
        echo "Remove {$path}\n";
        @unlink($path);
        @unlink($LOCKFILE);
    }
    events("STATS_CNX_ACCEPT()");
    STATS_CNX_ACCEPT();
    events("STATS_BuildCurrentWeek()");
    STATS_BuildCurrentWeek();
    events("STATS_hourly_cnx_to_daily_cnx()");
    STATS_hourly_cnx_to_daily_cnx();
}
    ini_set('display_errors', 1);
    ini_set('error_reporting', E_ALL);
}
$_GET["LOGFILE"] = "/var/log/artica-postfix/dansguardian-logger.debug";
if (preg_match("#--verbose#", implode(" ", $argv))) {
    $GLOBALS["debug"] = true;
    $GLOBALS["VERBOSE"] = true;
}
if (preg_match("#--simulate#", implode(" ", $argv))) {
    $GLOBALS["SIMULATE"] = true;
}
if (posix_getuid() != 0) {
    die("Cannot be used in web server mode\n\n");
}
$unix = new unix();
$pids = $unix->PIDOF_PATTERN_ALL(basename(__FILE__));
if ($GLOBALS["OUTPUT"]) {
    echo "Starting......: " . date("H:i:s") . " instances:" . count($pids) . "\n";
}
if (count($pids) > 3) {
    echo "Starting......: " . date("H:i:s") . " Too many instances " . count($pids) . " starting squid, kill them!\n";
    $mypid = getmypid();
    while (list($pid, $ligne) = each($pids)) {
        if ($pid == $mypid) {
            continue;
        }
        echo "Starting......: " . date("H:i:s") . " killing {$pid}\n";
        unix_system_kill_force($pid);
    }
}
$pids = $unix->PIDOF_PATTERN_ALL(basename(__FILE__));
function scan_queue($nopid = false)
{
    $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid";
    $pidTime = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".time";
    $unix = new unix();
    if (!$GLOBALS["VERBOSE"]) {
        if ($nopid) {
            $pid = @file_get_contents($pidfile);
            if ($unix->process_exists($pid)) {
                writelogs("Already running pid {$pid}", __FUNCTION__, __FILE__, __LINE__);
                return;
            }
            $t = 0;
        }
        $pids = $unix->PIDOF_PATTERN_ALL("exec.syslog-engine.php --admin-evs");
        if (count($pids) > 1) {
            writelogs("2 instances already runnin.. aborting", __FUNCTION__, __FILE__, __LINE__);
            return;
        }
        $TimeExec = $unix->file_time_min($pidTime);
        if ($TimeExec < 5) {
            writelogs("Only each 5 mn", __FUNCTION__, __FILE__, __LINE__);
            return;
        }
    }
    @unlink($pidTime);
    @file_put_contents($pidTime, time());
    @file_put_contents($pidfile, getmypid());
    blackwhite_admin_mysql_check(true);
    squid_admin_notifs_check(true);
    system_rotate_events_checks(true);
    haproxy_events();
    sys_load();
    cyrus_admin_mysql_check(true);
    apache_admin_mysql_check(true);
    vsftpd_admin_mysql_check(true);
    squid_admin_mysql_check(true);
    squid_admin_enforce_check(true);
    webupdate_admin_mysql_check(true);
    nginx_admin_mysql_check(true);
    system_admin_events_checks(true);
    artica_update_task(true);
    checks_hotspot_admin_mysql(true);
    checks_stats_admin_events(true);
    squid_admin_purge_check(true);
    rotate_admin_events_checks(true);
    udfbguard_admin_events(true);
    sys_alerts(true);
    clean_mysql_events(true);
    seeker();
}
Beispiel #20
0
function scanarp_mysql()
{
    $unix = new unix();
    $t = time();
    if (systemMaxOverloaded()) {
        return;
    }
    $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid";
    $unix = new unix();
    $me = basename(__FILE__);
    $pid = @file_get_contents($pidfile);
    if ($unix->process_exists($pid, $me)) {
        if ($GLOBALS["VERBOSE"]) {
            echo " --> Already executed.. {$pid} aborting the process\n";
        }
        system_admin_events("--> Already executed.. {$pid} aborting the process", __FUNCTION__, __FILE__, __LINE__, "network");
        die;
    }
    $sock = new sockets();
    $EnableArpDaemon = $sock->GET_INFO("EnableArpDaemon");
    $ArpdKernelLevel = $sock->GET_INFO("ArpdKernelLevel");
    if (!is_numeric($EnableArpDaemon)) {
        $EnableArpDaemon = 1;
    }
    $articastatus_pidfile = "/etc/artica-postfix/exec.status.php.pid";
    $pid = $unix->get_pid_from_file($articastatus_pidfile);
    if (!$unix->process_exists($pid)) {
        syslog_status("artica status doesn't run, start it, old pid was: {$pid}");
        shell_exec("/etc/init.d/artica-status start");
    }
    $list = $unix->PIDOF_PATTERN_ALL($me);
    if (count($list) > 2) {
        system_admin_events("--> Already executed.." . count($list) . " Processes executed");
        die;
    }
    @file_put_contents($pidfile, getmypid());
    $arpbin = $unix->find_program("arp");
    $arpdbin = $unix->find_program("arpd");
    if (!is_file($arpbin)) {
        echo "arp, no such binary...\n";
        return;
    }
    exec("{$arpbin} -a 2>&1", $results);
    if ($GLOBALS["VERBOSE"]) {
        echo "{$arpbin} -a 2>&1\n";
    }
    $prefix = "INSERT INTO arpcache (`mac`,`ipaddr`,`hostname`,`HWtype`,`iface`) VALUES ";
    while (list($num, $ligne) = each($results)) {
        if (preg_match("#^(.+?)\\s+\\((.+?)\\)\\s+.+?\\s+(.+?)\\s+\\[(.+?)\\]\\s+.+?\\s+(.+)#", $ligne, $re)) {
            $mac = trim($re[3]);
            $hostname = trim($re[1]);
            $ipaddr = trim($re[2]);
            $HWtype = trim($re[4]);
            $iface = trim($re[5]);
            if ($GLOBALS["VERBOSE"]) {
                echo "MATCH `{$ligne}` '{$mac}','{$ipaddr}','{$hostname}','{$HWtype}','{$iface}'\n";
            }
            $f[] = "('{$mac}','{$ipaddr}','{$hostname}','{$HWtype}','{$iface}')";
            continue;
        }
        if (preg_match("#^([a-z0-9\\.\\-\\_\\?]+)\\s+\\((.+?)\\).+?incomplete.+?[a-z]+\\s+(.+)\$#", $ligne, $re)) {
            $mac = null;
            $hostname = trim($re[1]);
            $ipaddr = trim($re[2]);
            $HWtype = null;
            $iface = trim($re[3]);
            if ($GLOBALS["VERBOSE"]) {
                echo "MATCH `{$ligne}` '{$mac}','{$ipaddr}','{$hostname}','{$HWtype}','{$iface}'\n";
            }
            $f[] = "('{$mac}','{$ipaddr}','{$hostname}','{$HWtype}','{$iface}')";
            continue;
        }
        if ($GLOBALS["VERBOSE"]) {
            echo "No match `{$ligne}`\n";
        }
    }
    if (is_file($arpdbin)) {
        $results = array();
        exec("{$arpdbin} -l 2>&1", $results);
        while (list($num, $ligne) = each($results)) {
            if (preg_match("#^[0-9]+\\s+([0-9\\.]+)\\s+(.+)#", $ligne, $re)) {
                $mac = trim($re[2]);
                if (preg_match("#FAILED:#", $mac)) {
                    $mac = null;
                }
                $hostname = null;
                $ipaddr = trim($re[1]);
                $HWtype = null;
                $iface = "arpd";
                $f[] = "('{$mac}','{$ipaddr}','{$hostname}','{$HWtype}','{$iface}')";
                continue;
            }
        }
    }
    if (count($f) > 0) {
        $q = new mysql();
        $q->QUERY_SQL("TRUNCATE TABLE `arpcache`", "artica_backup");
        if ($GLOBALS["VERBOSE"]) {
            echo count($f) . " entries\n";
        }
        $sql = $prefix . @implode(",", $f);
        $q->QUERY_SQL($sql, "artica_backup");
        if (!$q->ok) {
            system_admin_events("Fatal, {$q->mysql_error}", __FUNCTION__, __FILE__, __LINE__, "network");
            return;
        }
        $took = $unix->distanceOfTimeInWords($t, time(), true);
        system_admin_events(count($f) . " ARP entries added into MySQL server", __FUNCTION__, __FILE__, __LINE__, "network");
    }
}
function sexec()
{
    $EXEC_PID_FILE = "/etc/artica-postfix/" . basename(__FILE__) . ".sexec.pid";
    $TILE_PID_FILE = "/etc/artica-postfix/" . basename(__FILE__) . ".sexec.pid";
    $unix = new unix();
    $sock = new sockets();
    $SQUIDEnable = $sock->GET_INFO("SQUIDEnable");
    if (!is_numeric($SQUIDEnable)) {
        $SQUIDEnable = 1;
    }
    if ($SQUIDEnable == 0) {
        die;
    }
    $pid = @file_get_contents($EXEC_PID_FILE);
    if ($unix->process_exists($pid, basename(__FILE__))) {
        build_progress("Already running", 110);
        return false;
    }
    $pids = $unix->PIDOF_PATTERN_ALL(__FILE__);
    if (count($pids) > 0) {
        return;
    }
    $TILE_PID_TIME = $unix->file_time_min($TILE_PID_FILE);
    $SquidHTTPTemplateLanguage = $sock->GET_INFO("SquidHTTPTemplateLanguage");
    if ($SquidHTTPTemplateLanguage == null) {
        $SquidHTTPTemplateLanguage = "en-us";
    }
    $GLOBALS["XTPL_SQUID_DEFAULT"] = unserialize(@file_get_contents("/usr/share/artica-postfix/ressources/databases/squid.default.templates.db"));
    $xtpl = new template_simple();
    $MAIN = $GLOBALS["XTPL_SQUID_DEFAULT"][$SquidHTTPTemplateLanguage];
    @mkdir("/usr/share/squid-langpack/{$SquidHTTPTemplateLanguage}", 0755, true);
    @chown("/usr/share/squid-langpack/{$SquidHTTPTemplateLanguage}", "squid");
    @chgrp("/usr/share/squid-langpack/{$SquidHTTPTemplateLanguage}", "squid");
    $arrayxLangs = $xtpl->arrayxLangs;
    while (list($TEMPLATE_TITLE, $subarray) = each($MAIN)) {
        build_progress("{building} {$TEMPLATE_TITLE}", 50);
        $xtpl = new template_simple($TEMPLATE_TITLE, $SquidHTTPTemplateLanguage);
        $templateDestination = "/usr/share/squid-langpack/templates/{$TEMPLATE_TITLE}";
        $templateLangDestination = "/usr/share/squid-langpack/templates/{$SquidHTTPTemplateLanguage}/{$TEMPLATE_TITLE}";
        $design = $xtpl->TemplatesDesign();
        @file_put_contents($templateDestination, $design);
        @file_put_contents($templateLangDestination, $design);
        if ($GLOBALS["VERBOSE"]) {
            echo "{$TEMPLATE_TITLE}: {$SquidHTTPTemplateLanguage} {$templateDestination} done\n";
        }
        if ($GLOBALS["VERBOSE"]) {
            echo "{$TEMPLATE_TITLE}: {$SquidHTTPTemplateLanguage} {$templateLangDestination} done\n";
        }
        @chown($templateLangDestination, "squid");
        @chgrp($templateLangDestination, "squid");
        @chown($templateDestination, "squid");
        @chgrp($templateDestination, "squid");
    }
    $ln = $unix->find_program("ln");
    while (list($Mainlang, $xarr) = each($xtpl->arrayxLangs)) {
        while (list($index, $z) = each($xarr)) {
            build_progress("Saving {$z}", 60);
            $destination_path = "/usr/share/squid-langpack/templates/{$z}";
            if (!is_link($destination_path)) {
                shell_exec("/bin/rm -rf {$destination_path}");
            }
            @unlink("{$destination_path}");
            shell_exec("{$ln} -sf \"/usr/share/squid-langpack/templates/{$Mainlang}\" \"{$destination_path}\"");
        }
    }
    $php = $unix->LOCATE_PHP5_BIN();
    if ($GLOBALS["BYINITD"]) {
        $addon = "By init.d";
    }
    if ($GLOBALS["BY"] != null) {
        $addon = $GLOBALS["BY"];
    }
    shell_exec("{$php} /usr/share/artica-postfix/exec.squid.php --mime");
    @file_put_contents("/etc/artica-postfix/SQUID_TEMPLATE_DONEv3", time());
    if ($GLOBALS["PROGRESS"]) {
        build_progress("{reloading} Proxy service", 70);
        squid_admin_mysql(2, "Reloading proxy service in order to refresh templates ({$addon})", null, __FILE__, __LINE__);
        $SQUID_BIN = $unix->LOCATE_SQUID_BIN();
        system("{$SQUID_BIN} -f /etc/squid3/squid.conf -k reconfigure");
        build_progress("{done}", 100);
        $TILE_PID_TIME = 0;
        return;
    }
    build_progress("{done}", 100);
}