function compile_rule($ID) { $unix = new unix(); $php5 = $unix->LOCATE_PHP5_BIN(); $nice = $unix->EXEC_NICE(); $f[] = "MAILTO=\"\""; $f[] = "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/X11R6/bin:/usr/share/artica-postfix/bin"; $f[] = "0,15,30,45 * * * * root {$nice}{$php5} " . __FILE__ . " --export >/dev/null 2>&1"; $f[] = ""; @file_put_contents("/etc/cron.d/iptaccount", @implode("\n", $f)); shell_exec("/bin/chmod 640 /etc/cron.d/iptaccount >/dev/null 2>&1"); iptables_delete_rule($ID); $q = new mysql(); $sql = "SELECT * FROM tcp_account_rules WHERE ID='{$ID}'"; $ligne = @mysql_fetch_array($q->QUERY_SQL($sql, 'artica_backup')); if ($ligne["ipaddr"] == null) { return; } if ($ligne["mode"] == null) { return; } $unix = new unix(); $iptables = $unix->find_program("iptables"); $cmd = "{$iptables} -A {$ligne["mode"]} -j ACCOUNT --addr {$ligne["ipaddr"]} --tname rule_{$ID} -m comment --comment \"ArticaIptAccountRule_{$ID}\""; if ($GLOBALS["VERBOSE"]) { echo $cmd . "\n"; } shell_exec($cmd); }
function restore($filename) { $unix = new unix(); $sock = new sockets(); $TMP = $unix->FILE_TEMP(); $filenameBase = basename($filename); if (!is_file($filename)) { echo "{$filename} no such file\n"; build_progress("{failed}", 110); } $tmpf = $unix->FILE_TEMP(); build_progress("{uncompress} {$filenameBase}", 10); if (!$unix->uncompress($filename, $tmpf)) { @unlink($filename); build_progress("{uncompress} {$filenameBase} {failed}", 110); return; } @unlink($filename); build_progress("{importing} {$tmpf}", 50); $q = new mysql_squid_builder(); $nice = $unix->EXEC_NICE(); $mysql = $unix->find_program("mysql"); $gzip = $unix->find_program("gzip"); $nohup = $unix->find_program("nohup"); $echo = $unix->find_program("echo"); $rm = $unix->find_program("rm"); $php = $unix->LOCATE_PHP5_BIN(); $sh[] = "#!/bin/sh"; $sh[] = "{$echo} \"{$mysql} -> {$filenameBase}\""; $sh[] = "{$nice} {$mysql} {$q->MYSQL_CMDLINES} -f squidlogs < {$tmpf}"; $sh[] = "{$rm} {$TMP}.sh"; $sh[] = "\n"; @file_put_contents("{$TMP}.sh", @implode("\n", $sh)); @chmod("{$TMP}.sh", 0755); build_progress(10, "Starting restore {$filenameBase} - " . basename("{$TMP}.sh") . " "); system("{$nohup} {$TMP}.sh >{$TMP}.txt 2>&1 &"); sleep(1); $PID = $unix->PIDOF_PATTERN("{$TMP}.sh"); echo "Running PID {$PID}\n"; while ($unix->process_exists($PID)) { build_progress(50, "Starting restoring {$filenameBase}"); sleep(3); $PID = $unix->PIDOF_PATTERN("{$TMP}.sh"); echo "Running PID {$PID}\n"; } echo @file_get_contents("{$TMP}.txt") . "\n"; @unlink("{$TMP}.sh"); @unlink("{$TMP}.txt"); build_progress(50, "{restore} {done} {$filenameBase}"); build_progress(50, "{restore} Analyze Hourly tables"); system("{$php} /usr/share/artica-postfix/exec.squid.stats.hours.php --force --verbose"); build_progress(60, "{restore} Repair Hourly tables"); system("{$php} /usr/share/artica-postfix/exec.squid.stats.hours.php --repair --force --verbose"); build_progress(70, "{restore} Repair Table days"); system("{$php} /usr/share/artica-postfix/exec.squid.stats.repair.php --tables-day --repair --force --verbose"); build_progress(80, "{restore} Repair sums"); system("{$php} /usr/share/artica-postfix/exec.squid.stats.totals.php --repair --force --verbose"); build_progress(100, "{restore} Done"); }
function create_cron_task(){ $unix=new unix(); $php5=$unix->LOCATE_PHP5_BIN(); $nice=$unix->EXEC_NICE(); $f[]="MAILTO=\"\""; $f[]="PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/X11R6/bin:/usr/share/artica-postfix/bin"; $f[]="0,10,20,30,40,50 * * * * root $nice$php5 ".__FILE__." --resolv >/dev/null 2>&1"; $f[]=""; @file_put_contents("/etc/cron.d/iptaccount", @implode("\n", $f)); shell_exec("/bin/chmod 640 /etc/cron.d/freeweb_resolv >/dev/null 2>&1"); }
function chock_status() { $unix = new unix(); $nohup = $unix->find_program("nohup"); writelogs_framework("nohup = {$nohup}", __FUNCTION__, __FILE__, __LINE__); $nice = $unix->EXEC_NICE(); writelogs_framework("nice = {$nice}", __FUNCTION__, __FILE__, __LINE__); $php5 = $unix->LOCATE_PHP5_BIN(); $cache_file = "/usr/share/artica-postfix/ressources/logs/web/monit.status.all"; if (is_file($cache_file)) { writelogs_framework("{$cache_file} exists", __FUNCTION__, __FILE__, __LINE__); @chmod($cache_file, 0755); } else { writelogs_framework("{$cache_file} does not exists", __FUNCTION__, __FILE__, __LINE__); } $cmd = "{$nohup} {$nice} {$php5} /usr/share/artica-postfix/exec.monit.php --status >/dev/null 2>&1 &"; writelogs_framework($cmd, __FUNCTION__, __FILE__, __LINE__); shell_exec($cmd); }
function directory_backup($WordpressBackupParams, $servername) { $unix = new unix(); $tar = $unix->find_program("tar"); $q = new mysql(); $free = new freeweb($servername); $gzip = $unix->find_program("gzip"); $WORKDIR = $free->www_dir; echo "Backup directory {$WORKDIR}"; if (!is_dir($WORKDIR)) { apache_admin_mysql(0, "{$servername} cannot backup a non-existent directory {$WORKDIR}", null, __FILE__, __LINE__); return false; } $BaseWorkDir = $WordpressBackupParams["DEST"] . "/{$servername}/" . date("Y-m-d-H") . "h"; @mkdir("{$BaseWorkDir}", 0755, true); $nice = $unix->EXEC_NICE(); $t = time(); chdir($WORKDIR); if ($GLOBALS["OUTPUT"]) { echo "Compressing {$BaseWorkDir}/wordpress.tar.gz\n"; } shell_exec("{$nice} {$tar} cfz {$BaseWorkDir}/wordpress.tar.gz *"); $took = $unix->distanceOfTimeInWords($t, time()); $size = FormatBytes(@filesize("{$BaseWorkDir}/wordpress.tar.gz") / 1024); if ($GLOBALS["OUTPUT"]) { echo "Compressing wordpress.tar.gz took {$took} size= {$size}"; } apache_admin_mysql(2, "{$servername} directory backuped {$size} (took {$took})", null, __FILE__, __LINE__); }
function parse_memory() { $unix = new unix(); $nginx = $unix->find_program("nginx"); $sock = new sockets(); $nginx = $unix->find_program("nginx"); if (!is_file($nginx)) { if ($GLOBALS["OUTPUT"]) { echo "Starting......: " . date("H:i:s") . " [INIT]: Nginx, not installed\n"; } return; } $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid"; $pidtime = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".time"; $pidStampReload = $GLOBALS["pidStampReload"]; if (!$GLOBALS["VERBOSE"]) { echo "{$pidtime}\n"; $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]: Nginx Already Artica task running PID {$pid} since {$time}mn\n"; } return; } $TimExec = $unix->file_time_min($pidtime); if ($TimExec < 5) { return; } } @file_put_contents($pidfile, getmypid()); @unlink($pidtime); @file_put_contents($pidtime, time()); $python = $unix->find_program("python"); $nice = $unix->EXEC_NICE(); exec("{$nice}{$python} /usr/share/artica-postfix/bin/ps_mem.py 2>&1", $results); $FOUND = false; while (list($index, $line) = each($results)) { $line = trim($line); if ($line == null) { continue; } if (!preg_match("#^[0-9\\.]+.*?=\\s+([0-9\\.]+)\\s+(.+?)\\s+nginx#", $line, $re)) { if ($GLOBALS["VERBOSE"]) { echo "Not found \"{$line}\"\n"; } continue; } $memoryValue = $re[1]; $unit = trim(strtolower($re[2])); echo "Found {$memoryValue} {$unit}\n"; if ($unit == "kib") { $memoryValue = $memoryValue / 1048.576; } if ($unit == "mib") { $memoryValue = $memoryValue * 1.048576; } if ($unit == "gib") { $memoryValue = $memoryValue * 1048.576; } $FOUND = true; break; } if (!$FOUND) { if ($GLOBALS["VERBOSE"]) { echo "Not found...\n"; } return; } $memoryValue = round($memoryValue, 2); $MaxMemory = max_memory(); $MaxMemoryReload = $MaxMemory / 2; $memoryValueInt = intval($memoryValue); echo "Nginx = {$memoryValue} MB INT({$memoryValueInt}) Reload on:{$MaxMemoryReload}MB; Restart on:{$MaxMemory}MB\n"; $ACTION_DONE = false; if ($MaxMemory > 0) { if ($memoryValueInt > 0) { if ($memoryValueInt > $MaxMemoryReload) { $StampTime = $unix->file_time_min($pidStampReload); if ($StampTime > 20) { squid_admin_mysql(1, "Reverse proxy reach medium memory {$memoryValueInt}MB Reload:{$MaxMemoryReload}MB [action=reload]", "The service will be restarted"); reload(true); @unlink($pidStampReload); @file_put_contents($pidStampReload, time()); $ACTION_DONE = true; } } if (!$ACTION_DONE) { if ($memoryValueInt > $MaxMemory) { squid_admin_mysql(0, "Reverse proxy reach max memory allowed {$memoryValueInt}MB MAX:{$MaxMemory}MB [action=restart]", "The service will be restarted"); stop(true); start(true); @unlink($pidStampReload); } } } } add_memory_value($memoryValue); }
if ($GLOBALS["DEBUG_INCLUDES"]) { echo basename(__FILE__) . "::class.squid.inc\n"; } include_once dirname(__FILE__) . '/ressources/class.squid.inc'; if ($GLOBALS["DEBUG_INCLUDES"]) { echo basename(__FILE__) . "::framework/class.unix.inc\n"; } include_once dirname(__FILE__) . '/framework/class.unix.inc'; if ($GLOBALS["DEBUG_INCLUDES"]) { echo basename(__FILE__) . "::frame.class.inc\n"; } include_once dirname(__FILE__) . '/framework/frame.class.inc'; include_once dirname(__FILE__) . '/ressources/class.mysql.inc'; include_once dirname(__FILE__) . '/ressources/class.squid.acls.inc'; $unix = new unix(); $NICE = $unix->EXEC_NICE(); $GetCachesInsquidConf = $unix->SQUID_CACHE_FROM_SQUIDCONF(); $chown = $unix->find_program("chown"); $chmod = $unix->find_program("chmod"); $t = time(); $c = 0; while (list($CacheDirectory, $type) = each($GetCachesInsquidConf)) { if (trim($CacheDirectory) == null) { continue; } if (!is_dir($CacheDirectory)) { continue; } $c++; $F[] = $CacheDirectory; shell_exec("{$NICE} {$chown} -R squid:squid {$CacheDirectory}");
function backup($ID) { $date_start = time(); $sock = new sockets(); $q = new mysql(); $unix = new unix(); $users = new usersMenus(); $GLOBALS["RESOURCE_MOUNTED"] = true; $sql = "SELECT * FROM backup_schedules WHERE ID='{$ID}'"; if ($GLOBALS["VERBOSE"]) { backup_events($ID, "initialization", "{$sql}", __LINE__); } $mount_path = "/opt/artica/mounts/backup/{$ID}"; if (!$q->TABLE_EXISTS("backup_storages", "artica_backup", true)) { $q->BuildTables(); if (!$q->TABLE_EXISTS("backup_storages", "artica_backup", true)) { backup_events($ID, "initialization", "ERROR, backup_storages, no such table", __LINE__); return; } } $servername = $users->fqdn; $servername = str_replace('.(none)', "", $servername); $servername = str_replace(')', "", $servername); $servername = str_replace('(', "", $servername); $GLOBALS["MYSERVERNAME"] = $servername; $ExecBackupDeadAfterH = $sock->GET_INFO("ExecBackupDeadAfterH"); if (!is_numeric($ExecBackupDeadAfterH)) { $ExecBackupDeadAfterH = 2; } if ($ExecBackupDeadAfterH < 2) { $ExecBackupDeadAfterH = 2; } $ExecBackupDeadAfterH = $ExecBackupDeadAfterH * 60; $ligne = @mysql_fetch_array($q->QUERY_SQL($sql, "artica_backup")); if (!$q->ok) { send_email_events("Backup Task {$ID}:: Mysql database error !", "Aborting backup\n{$q->mysql_error}", "backup"); backup_events($ID, "initialization", "ERROR, Mysql database error\n{$q->mysql_error}", __LINE__); return false; } if (!$GLOBALS["ONNLY_MOUNT"]) { $pid = $ligne["pid"]; if ($unix->process_exists($pid)) { $time = $unix->PROCCESS_TIME_MIN($pid); if ($time > $ExecBackupDeadAfterH) { send_email_events("Backup Task {$ID}:: Already instance {$pid} running since {$time}Mn", "The old process was killed and a new backup task will be performed\nstatus:\n\n{$unix->proc_status}", "backup"); } else { send_email_events("Backup Task {$ID}:: Already instance {$pid} running since {$time}Mn", "Aborting backup\n{$unix->proc_status}", "backup"); backup_events($ID, "initialization", "ERROR, Already instance {$pid} running since {$time}Mn", $unix->proc_status); return false; } } } $sql = "UPDATE backup_schedules set pid='" . getmypid() . "' WHERE ID='{$ID}'"; $q->QUERY_SQL($sql, "artica_backup"); $ressources = unserialize(base64_decode($ligne["datasbackup"])); if (count($ressources) == 0) { backup_events($ID, "initialization", "ERROR,No source specified"); send_email_events("Backup Task {$ID}:: No source specified", "Aborting backup", "backup"); return false; } if ($ressources["OPTIONS"]["STOP_IMAP"] == 1) { $GLOBALS["NO_STOP_CYRUS"] = " --no-cyrus-stop"; } $backup = new backup_protocols(); $resource_type = $ligne["resource_type"]; $pattern = $ligne["pattern"]; $first_ressource = $backup->extractFirsRessource($ligne["pattern"]); $container = $ligne["container"]; backup_events($ID, "initialization", "resource: {$resource_type} -> {$first_ressource}", __LINE__); if ($resource_type == null) { backup_events($ID, "initialization", "ERROR,No resource specified"); send_email_events("Backup Task {$ID}:: No resource specified !", "Aborting backup", "backup"); return false; } if ($resource_type == "smb") { $GLOBALS["CAN_CLEAN_CONTAINERS"] = true; $mounted_path_sep = "/"; if (!mount_smb($pattern, $ID, true)) { backup_events($ID, "initialization", "ERROR,{$first_ressource} unable to mount mount_smb()", __LINE__); send_email_events("Backup Task {$ID}:: resource: {$first_ressource} unable to mount", "Aborting backup", "backup"); return false; } $GLOBALS["PCOPY"] = true; } if ($resource_type == "ssh") { $GLOBALS["CAN_CLEAN_CONTAINERS"] = true; $mounted_path_sep = "/"; if (!mount_ssh($pattern, $ID, true)) { backup_events($ID, "initialization", "ERROR,{$first_ressource} unable to mount mount_ssh()", __LINE__); send_email_events("Backup Task {$ID}:: resource: {$first_ressource} unable to mount to remote ssh service", "Aborting backup", "backup"); return false; } $GLOBALS["PCOPY"] = true; } if ($resource_type == "usb") { $GLOBALS["CAN_CLEAN_CONTAINERS"] = true; $mounted_path_sep = "/"; if (!mount_usb($pattern, $ID, true)) { backup_events($ID, "initialization", "ERROR,{$first_ressource} unable to mount mount_usb()", __LINE__); send_email_events("Backup Task {$ID}:: resource: {$first_ressource} unable to mount", "Aborting backup", "backup"); return false; } backup_events($ID, "initialization", "INFO, using external device trough USB", __LINE__); $GLOBALS["PCOPY"] = true; } if ($resource_type == "rsync") { $mounted_path_sep = null; $mount_path = null; $GLOBALS["RESOURCE_MOUNTED"] = false; $GLOBALS["USE_RSYNC"] = true; $GLOBALS["NO_UMOUNT"] = true; $GLOBALS["CAN_CLEAN_CONTAINERS"] = false; if (!mount_rsync($pattern, $ID, true)) { backup_events($ID, "initialization", "ERROR,{$first_ressource} unable to connect"); send_email_events("Backup Task {$ID}:: resource: {$first_ressource} unable to connect", "Aborting backup", "backup"); return false; } else { backup_events($ID, "initialization", "INFO,{$first_ressource} connect success"); } } if ($resource_type == "automount") { $mounted_path_sep = "/"; $mount_path = $first_ressource; $GLOBALS["RESOURCE_MOUNTED"] = false; $GLOBALS["USE_RSYNC"] = true; $GLOBALS["NO_UMOUNT"] = true; $GLOBALS["CAN_CLEAN_CONTAINERS"] = true; $GLOBALS["MOUNTED_PATH_FINAL"] = $first_ressource; CheckCommandLineCopy(); if (!mount_automount($pattern, $ID, true)) { backup_events($ID, "initialization", "ERROR,{$first_ressource} unable to connect"); send_email_events("Backup Task {$ID}:: resource: {$first_ressource} unable to connect", "Aborting backup", "backup"); return false; } backup_events($ID, "initialization", "INFO,{$first_ressource} connect success"); $GLOBALS["PCOPY"] = true; } if ($resource_type == "local") { $mounted_path_sep = "/"; $mount_path = $first_ressource; $GLOBALS["RESOURCE_MOUNTED"] = false; $GLOBALS["CAN_CLEAN_CONTAINERS"] = true; $GLOBALS["USE_RSYNC"] = true; $GLOBALS["NO_UMOUNT"] = true; $GLOBALS["MOUNTED_PATH_FINAL"] = $first_ressource; CheckCommandLineCopy(); if (!is_dir($first_ressource)) { backup_events($ID, "initialization", "{$first_ressource} directory doesn't exsits, create it..", __LINE__); @mkdir($first_ressource, 0755, true); } if (!is_dir($first_ressource)) { backup_events($ID, "initialization", "{$first_ressource} no such directory permission denied", __LINE__); send_email_events("Backup Task {$ID}:: resource: {$first_ressource} no such directory", "Aborting backup", "backup"); return false; } backup_events($ID, "initialization", "INFO,{$first_ressource} success"); $GLOBALS["PCOPY"] = true; } if ($GLOBALS["ONLY_TESTS"]) { if ($GLOBALS["RESOURCE_MOUNTED"]) { writelogs(date('m-d H:i:s') . " " . "[TASK {$ID}]:umount {$mount_path}", __FUNCTION__, __FILE__, __LINE__); exec("umount -l {$mount_path}"); } writelogs(date('m-d H:i:s') . " " . "[TASK {$ID}]: terminated...", __FUNCTION__, __FILE__, __LINE__); return; } if ($GLOBALS["ONNLY_MOUNT"]) { return $mount_path; } if ($container == "daily") { backup_events($ID, "initialization", "INFO, Daily container", __LINE__); $DirectoryContainer = "backup." . date('Y-m-d') . "/{$servername}"; $GLOBAL["BACKUP_MEMORY_SQL"]["CONTAINER"] = $DirectoryContainer; $mount_path_final = $mount_path . $mounted_path_sep . $DirectoryContainer; } else { backup_events($ID, "initialization", "INFO, Weekly container", __LINE__); $DirectoryContainer = "backup." . date('Y-W') . "/{$servername}"; $GLOBAL["BACKUP_MEMORY_SQL"]["CONTAINER"] = $DirectoryContainer; $mount_path_final = $mount_path . $mounted_path_sep . $DirectoryContainer; } if ($GLOBALS["DEBUG"]) { $cmd_verb = " --verbose"; writelogs(date('m-d H:i:s') . " " . "[TASK {$ID}]: Verbose mode detected", __FUNCTION__, __FILE__, __LINE__); } @mkdir($mount_path_final, 0755, true); if (!$GLOBALS["NO_STANDARD_BACKUP"]) { $GLOBALS["MOUNTED_PATH_FINAL"] = $mount_path_final; $WhatToBackup_ar = null; $BACKUP_WWW_ALREADY_DONE = array(); $BACKUP_WEBGET_ALREADY_DONE = array(); $BACKUP_INSTANCES_ALREADY_DONE = array(); while (list($num, $WhatToBackup) = each($ressources)) { if (is_array($WhatToBackup)) { $WhatToBackup_ar = implode(",", $WhatToBackup); backup_events($ID, "initialization", "INFO, WhatToBackup Array = {$WhatToBackup_ar}", __LINE__); continue; } if ($WhatToBackup == "all") { backup_events($ID, "initialization", "INFO, Backup starting Running macro all cyrus, mysql, LDAP, Artica...", __LINE__); send_email_events("Backup Task {$ID}:: Backup starting Running macro all ", "Backup is running", "backup"); if ($users->cyrus_imapd_installed) { backup_events($ID, "initialization", "INFO, cyrus-imapd mailboxes processing"); backup_cyrus($ID); } backup_events($ID, "initialization", "INFO, LDAP Database processing", __LINE__); backup_ldap($ID); backup_events($ID, "initialization", "INFO, MySQL Database processing", __LINE__); backup_mysql($ID, 0); backup_events($ID, "initialization", "INFO, Restarting MySQL service...", __LINE__); mysql_admin_mysql(0, "Restarting mysql service.", null, __FILE__, __LINE__); shell_exec("/etc/init.d/mysql restart"); backup_events($ID, "initialization", "INFO, Artica settings processing", __LINE__); backup_artica($ID); if ($users->ZARAFA_INSTALLED) { if ($sock->GET_INFO("ZarafaStoreOutside") == 1) { backup_events($ID, "initialization", "INFO, Zarafa external attachments processing..."); backup_ZarafaOutside($ID); } } backup_events($ID, "initialization", "continue to next process", __LINE__); continue; } if (preg_match("#MYSQLINSTANCE:([0-9]+)#", $WhatToBackup, $re)) { $instance_id = $re[1]; backup_events($ID, "initialization", "INFO, Backup starting backup MySQL instance Number:{$instance_id}", __LINE__); if ($instance_id > 0) { if (!isset($BACKUP_INSTANCES_ALREADY_DONE[$instance_id])) { backup_mysql($ID, $instance_id); $BACKUP_INSTANCES_ALREADY_DONE[$instance_id] = true; } } continue; } if (preg_match("#FREEWEB:(.+)#", $WhatToBackup, $re)) { $sitename = $re[1]; backup_events($ID, "initialization", "INFO, Backup starting backup Website {$sitename}", __LINE__); if (!isset($BACKUP_WWW_ALREADY_DONE[$sitename])) { backup_freewebs($ID, $sitename); $BACKUP_INSTANCES_ALREADY_DONE[$sitename] = true; } continue; } if (preg_match("#WEBGET:(.+)#", $WhatToBackup, $re)) { if (!isset($BACKUP_WEBGET_ALREADY_DONE[$re[1]])) { $arr = unserialize(base64_decode($re[1])); if (!is_array($arr)) { backup_events($ID, "initialization", "ERROR, WEBGET `{$re[1]}` is not an array...", __LINE__); continue; } backup_events($ID, "initialization", "INFO, Backup remote Artica FreeWebs Website {$arr["RemoteArticaSite"]} from source {$arr["RemoteArticaServer"]}", __LINE__); backup_webget($ID, $arr); } continue; } backup_events($ID, "initialization", "INFO, `{$WhatToBackup}` could not understood", __LINE__); } } $sql = "SELECT * FROM backup_folders WHERE taskid={$ID}"; $results = $q->QUERY_SQL($sql, "artica_backup"); if (!$q->ok) { if (strpos($q->mysql_error, "gone away")) { backup_events($ID, "personal", "ERROR, mysql {$q->mysql_error} Restarting MySQL server (Patch p.20130807)", __LINE__); mysql_admin_mysql(0, "Restarting mysql service.", $q->mysql_error, __FILE__, __LINE__); shell_exec("/etc/init.d/mysql restart"); $q = new mysql(); $results = $q->QUERY_SQL($sql, "artica_backup"); } } if (!$q->ok) { backup_events($ID, "personal", "ERROR, mysql {$q->mysql_error}", __LINE__); return; } while ($ligne = @mysql_fetch_array($results, MYSQL_ASSOC)) { $dd1 = time(); if ($ligne["recursive"] == 1) { $recursive = " --recursive"; } else { $recursive = null; } $path = trim(base64_decode($ligne["path"])); if (!is_dir($path)) { backup_events($ID, "personal", "ERROR, [{$path}] no such file or directory", __LINE__); continue; } backup_events($ID, "personal", "INFO, Backup starting for {$path}", __LINE__); send_email_events("Backup Task {$ID}:: Backup starting {$path}", "Backup is running for path {$path}", "backup"); backup_mkdir($path); $results = backup_copy($path, $path, $ID); $calculate = distanceOfTimeInWords($dd1, time()); backup_events($ID, "personal", "INFO, Backup finish for {$path}\n{$results} {$calculate}", __LINE__); } writelogs(date('m-d H:i:s') . " " . "[TASK {$ID}]: Calculate directory size on {$mount_path_final}", __FUNCTION__, __FILE__, __LINE__); $du = $unix->find_program("du"); $dut1 = time(); $nice = $unix->EXEC_NICE(); $cmd = "{$nice}{$du} -s {$mount_path_final}"; exec($cmd, $du_results); $calculate = distanceOfTimeInWords($dut1, time()); $BackupSize = 0; if (preg_match("#^([0-9]+)\\s+#", @implode("", $du_results), $re)) { $BackupSize = $re[1]; backup_events($ID, "initialization", "INFO, backup size {$BackupSize} bytes time:{$calculate}", __LINE__); } if ($GLOBALS["CAN_CLEAN_CONTAINERS"]) { backup_events($ID, "initialization", "INFO, cleaning containers....", __LINE__); CleanContainers($ID, $mount_path_final); } else { backup_events($ID, "initialization", "INFO, cannot clean containers, check protocols....", __LINE__); } $GLOBAL["BACKUP_MEMORY_SQL"]["mount_path_final"] = $mount_path_final; $zmd5 = md5("{$GLOBAL["BACKUP_MEMORY_SQL"]["CONTAINER"]}{$GLOBALS["MYSERVERNAME"]}"); $cnx_params = addslashes(base64_encode(serialize($GLOBAL["BACKUP_MEMORY_SQL"]))); $sql = "INSERT IGNORE INTO backup_storages (`taskid`,`size`,`cnx_params`,`zmd5`) VALUES('{$ID}','{$BackupSize}','{$cnx_params}','{$zmd5}')"; $q->QUERY_SQL($sql, "artica_backup"); $sql = "UPDATE backup_storages SET `size`='{$BackupSize}' WHERE `zmd5`='{$zmd5}'"; $q->QUERY_SQL($sql, "artica_backup"); if (!$q->ok) { backup_events($ID, "initialization", "ERROR, {$q->mysql_error}", __LINE__); } if (!$GLOBALS["NO_UMOUNT"]) { writelogs(date('m-d H:i:s') . " " . "[TASK {$ID}]:umount {$mount_path_final}", __FUNCTION__, __FILE__, __LINE__); if (preg_match("#^\\/opt\\/artica\\/mounts\\/backup\\/[0-9]+(.+)#", $mount_path_final, $re)) { $mount_path_final = str_replace($re[1], "", $mount_path_final); writelogs(date('m-d H:i:s') . " " . "[TASK {$ID}]:translated to {$mount_path_final}", __FUNCTION__, __FILE__, __LINE__); } backup_events($ID, "initialization", "INFO, umount {$mount_path_final}", __LINE__); writelogs(date('m-d H:i:s') . " " . "[TASK {$ID}]:umount {$mount_path_final}", __FUNCTION__, __FILE__, __LINE__); exec("umount -l {$mount_path_final} 2>&1", $resultsUmount); if (count($resultsUmount) > 0) { writelogs(date('m-d H:i:s') . " " . "[TASK {$ID}]:umount : ----- \n" . @implode("\n", $resultsUmount) . "\n", __FUNCTION__, __FILE__, __LINE__); } } $date_end = time(); $calculate = distanceOfTimeInWords($date_start, $date_end); backup_events($ID, "TIME", "INFO, Time: {$calculate} ({$mount_path_final})", __LINE__); backup_events($ID, "initialization", "INFO, Backup task terminated", __LINE__); send_email_events("Backup Task {$ID}:: Backup stopping", "Backup is stopped", "backup"); shell_exec(LOCATE_PHP5_BIN2() . " " . dirname(__FILE__) . "/exec.cleanfiles.php"); }
function xupdate($aspid = false) { $unix = new unix(); $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid"; $pidtime = "/etc/artica-postfix/pids/exec.suricata.updates.php.update.time"; if (!$GLOBALS["FORCE"]) { if (system_is_overloaded()) { die; } if (!$aspid) { $pid = @file_get_contents($pidfile); if ($pid < 100) { $pid = null; } if ($unix->process_exists($pid, basename(__FILE__))) { echo "PID: {$pid} Already exists....\n"; die; } @file_put_contents($pidfile, getmypid()); $pidExec = $unix->file_time_min($pidtime); if ($pidExec < 1439) { return; } @unlink($pidtime); @file_put_contents($pidtime, time()); } } echo "Starting....\n"; $sock = new sockets(); $CurrentEmergingRulesMD5 = $sock->GET_INFO("CurrentEmergingRulesMD5"); $tmpdir = $unix->TEMP_DIR(); echo "CurrentEmergingRulesMD5={$CurrentEmergingRulesMD5} TMPDIR:{$tmpdir}\n"; $curl = new ccurl("https://rules.emergingthreatspro.com/open/suricata/emerging.rules.tar.gz.md5"); $targetpath = "{$tmpdir}/emerging.rules.tar.gz.md5"; if (!$curl->GetFile($targetpath)) { echo "{$targetpath} failed\n"; artica_update_event(0, "Unable to download emerging.rules.tar.gz.md5", $curl->errors, __FILE__, __LINE__); return; } echo "Open {$targetpath}\n"; $f = explode("\n", @file_get_contents($targetpath)); echo "{$targetpath} " . count($f) . " lines\n"; if (count($f) > 2) { artica_update_event(0, "Truncated emerging.rules.tar.gz.md5", $curl->errors, __FILE__, __LINE__); return; } @unlink($targetpath); $NewEmergingRulesMD5 = trim($f[0]); if ($NewEmergingRulesMD5 == $CurrentEmergingRulesMD5) { echo "No new updates...\n"; die; } $curl = new ccurl("https://rules.emergingthreatspro.com/open/suricata/version.txt"); $targetpath = "{$tmpdir}/version.txt"; if (!$curl->GetFile($targetpath)) { echo "{$targetpath} failed\n"; artica_update_event(0, "Unable to version.txt", $curl->errors, __FILE__, __LINE__); return; } $NextVersion = @file_get_contents($targetpath); @unlink($targetpath); $curl = new ccurl("https://rules.emergingthreatspro.com/open/suricata/emerging.rules.tar.gz"); $targetpath = "{$tmpdir}/emerging.rules.tar.gz"; if (!$curl->GetFile($targetpath)) { echo "{$targetpath} failed\n"; artica_update_event(0, "Unable to download emerging.rules.tar.gz", $curl->errors, __FILE__, __LINE__); return; } $FileMD5 = md5_file($targetpath); if ($FileMD5 != $NewEmergingRulesMD5) { artica_update_event(0, "Corrupted emerging.rules.tar.gz file", "{$FileMD5}<>{$NewEmergingRulesMD5}", __FILE__, __LINE__); return; } echo "Extracting rules\n"; $tar = $unix->find_program("tar"); shell_exec("{$tar} xf {$targetpath} -C /etc/suricata/"); @unlink($targetpath); $sock->SET_INFO("CurrentEmergingRulesMD5", $NewEmergingRulesMD5); $sock->SET_INFO("CurrentEmergingRulesVersion", $NextVersion); $curl = new ccurl("https://rules.emergingthreatspro.com/open/suricata/classification.config"); $targetpath = "{$tmpdir}/classification.config"; if (!$curl->GetFile($targetpath)) { echo "{$targetpath} failed\n"; artica_update_event(0, "Unable to download classification.config", $curl->errors, __FILE__, __LINE__); return; } @unlink("/etc/suricata/classification.config"); @copy($targetpath, "/etc/suricata/classification.config"); @unlink($targetpath); $php = $unix->LOCATE_PHP5_BIN(); $nohup = $unix->find_program("nohup"); shell_exec("{$php} /usr/share/artica-postfix/exec.suricata.php --classifications"); $q = new postgres_sql(); $results = $q->QUERY_SQL("select signature FROM suricata_sig where enabled=0"); $nice = $unix->EXEC_NICE(); $SH[] = "#!/bin/sh"; while ($ligne = @pg_fetch_assoc($results)) { $sig = $ligne["signature"]; echo "Disable signature {$sig}\n"; $SH[] = "{$nice} /usr/share/artica-postfix/bin/sidrule -d {$sig} || true"; } $targetpath = "{$tmpdir}/sidrule-remove.sh"; $SH[] = "rm -f {$tmpdir}/sidrule-remove.sh"; $SH[] = "/etc/init.d/suricata restart\n\n"; @file_put_contents("{$tmpdir}/sidrule-remove.sh", @implode("\n", $SH)); @chmod("{$tmpdir}/sidrule-remove.sh", 0755); shell_exec("{$nohup} {$tmpdir}/sidrule-remove.sh >/dev/null 2>&1 &"); artica_update_event(2, "Success updating emergingthreatspro IDS patterns v{$NextVersion}", null, __FILE__, __LINE__); BlockIPs(); }
function debian_size() { $sock = new sockets(); $unix = new unix(); $MirrorEnableDebian = $sock->GET_INFO("MirrorEnableDebian"); $MirrorDebianDir = $sock->GET_INFO("MirrorDebianDir"); $MirrorDebianBW = $sock->GET_INFO("MirrorDebianBW"); if (!is_numeric($MirrorEnableDebian)) { $MirrorEnableDebian = 0; } if (!is_numeric($MirrorDebianBW)) { $MirrorDebianBW = 500; } if ($MirrorDebianDir == null) { $MirrorDebianDir = "/home/mirrors/Debian"; } $unix = new unix(); $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid"; $pidTime = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".time"; $extime = $unix->file_time_min($pidTime); if ($GLOBALS["VERBOSE"]) { echo "{$extime}Mn\n"; } $pid = $unix->get_pid_from_file($pidfile); if ($unix->process_exists($pid, basename(__FILE__))) { $time = $unix->PROCCESS_TIME_MIN($pid); writelogs("Already process exists pid {$pid} running since {$time}mn", __FUNCTION__, __FILE__, __LINE__); return; } @file_put_contents($pidfile, getmypid()); if (!$GLOBALS["VERBOSE"]) { $TIME = $unix->file_time_min($pidTime); if ($unix->file_time_min($pidTime) < 30) { writelogs("`{$pidTime}` {$TIME}mn, require 30mn, aborting", __FUNCTION__, __FILE__, __LINE__); ChecksLogs(); return; } } @unlink($pidTime); @file_put_contents($pidTime, time()); if (is_overloaded()) { if ($GLOBALS["VERBOSE"]) { echo "Overloaded system...\n"; } return; } $nice = $unix->EXEC_NICE(); $du = $unix->find_program("du"); if ($GLOBALS["VERBOSE"]) { echo "{$nice} {$du} -s -b {$MirrorDebianDir} 2>&1\n"; } writelogs("{$nice} {$du} -s -b {$MirrorDebianDir} 2>&1", __FUNCTION__, __FILE__, __LINE__); exec("{$nice} {$du} -s -b {$MirrorDebianDir} 2>&1", $results); writelogs("Done...", __FUNCTION__, __FILE__, __LINE__); while (list($num, $val) = each($results)) { if (!preg_match("#^([0-9\\.]+)\\s+#", $val, $re)) { continue; } if ($GLOBALS["VERBOSE"]) { echo "{$re[1]} Bytes...\n"; } $sock->SET_INFO("MirrorDebianDirSize", $re[1]); } ChecksLogs(); }
function nmap_scan() { if (isset($GLOBALS["nmap_scan_executed"])) { return; } $unix = new unix(); $pidTime = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".time"; $timeF = $unix->file_time_min($pidTime); if ($timeF < 10) { $GLOBALS["nmap_scan_executed"] = true; return; } $sock = new sockets(); $SquidPerformance = intval($sock->GET_INFO("SquidPerformance")); if ($SquidPerformance > 2) { return; } $php5 = $unix->LOCATE_PHP5_BIN(); $nohup = $unix->find_program("nohup"); $exec_nice = $unix->EXEC_NICE(); $cmdNmap = "{$exec_nice} {$nohup} {$php5} " . dirname(__FILE__) . "/exec.nmapscan.php --scan-squid >/dev/null 2>&1 &"; @file_put_contents($pidTime, time()); shell_exec($cmdNmap); $GLOBALS["nmap_scan_executed"] = true; }
function xtsart() { $unix = new unix(); $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . ".pid"; $pidTime = "/etc/artica-postfix/pids/" . basename(__FILE__) . ".time"; if ($GLOBALS["VERBOSE"]) { echo "TimeFile:{$pidTime}\n"; } $unix = new unix(); if (!$GLOBALS["VERBOSE"]) { if ($unix->file_time_min($pidTime) < 10) { die; } if ($unix->process_exists(@file_get_contents($pidfile, basename(__FILE__)))) { if ($GLOBALS["VERBOSE"]) { echo " --> Already executed.. " . @file_get_contents($pidfile) . " aborting the process\n"; } writelogs(basename(__FILE__) . ":Already executed.. aborting the process", basename(__FILE__), __FILE__, __LINE__); die; } @file_put_contents($pidfile, getmypid()); @unlink($pidTime); @file_put_contents($pidTime, time()); } $array_load = sys_getloadavg(); $internal_load = $array_load[0]; $time = time(); $BASEDIR = "/usr/share/artica-postfix"; $hash_mem = array(); @chmod("/usr/share/artica-postfix/ressources/mem.pl", 0755); $datas = shell_exec(dirname(__FILE__) . "/ressources/mem.pl"); if (preg_match('#T=([0-9]+) U=([0-9]+)#', $datas, $re)) { $ram_used = $re[2]; } $cpuUsage = null; $ps = $unix->find_program("ps"); exec("{$ps} -aux 2>&1", $processes); foreach ($processes as $process) { $cols = explode(' ', preg_replace('# +#', ' ', $process)); if (strpos($cols[2], '.') > -1) { $cpuUsage += floatval($cols[2]); } } if ($GLOBALS["VERBOSE"]) { echo "CPU: {$cpuUsage}, LOAD: {$internal_load}, MEM: {$ram_used}\n"; } $q = new postgres_sql(); $q->CREATE_TABLES(); $proxyname = $unix->hostname_g(); $time = date("Y-m-d H:i:s"); $sql = "INSERT INTO system (zdate,proxyname,load_avg,mem_stats,cpu_stats)\n\tVALUES('{$time}','{$proxyname}','{$internal_load}','" . intval($ram_used) . "','{$cpuUsage}')"; if ($GLOBALS["VERBOSE"]) { echo $sql . "\n"; } $q->QUERY_SQL($sql); if (!$q->ok) { echo $q->mysql_error . "\n"; } RXTX(); if (system_is_overloaded(basename(__FILE__))) { $date = time(); @mkdir("/var/log/artica-postfix/sys_alerts", 0755, true); if (!is_file("/var/log/artica-postfix/sys_alerts/{$date}")) { $ps = $unix->find_program("ps"); $nohup = $unix->find_program($nohup); $nice = $unix->EXEC_NICE(); $load = $GLOBALS["SYSTEM_INTERNAL_LOAD"]; if (!$unix->process_exists($unix->PIDOF_PATTERN("{$ps}"))) { $cmd = trim("{$nohup} {$nice} {$ps} auxww >/var/log/artica-postfix/sys_alerts/{$date}-{$load} 2>&1"); shell_exec($cmd); } } } }
function squidz($aspid = false) { $unix = new unix(); 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); system_admin_events("restart_squid::Already task running PID {$pid} since {$time}mn", __FUNCTION__, __FILE__, __LINE__, "proxy"); return; } @file_put_contents($pidfile, getmypid()); } echo date("Y/m/d H:i:s") . " Arti| Stopping Squid\n"; echo date("Y/m/d H:i:s") . " Arti| Please wait....\n"; stop_squid(true); $squidbin = $unix->LOCATE_SQUID_BIN(); $su_bin = $unix->find_program("su"); $t1 = time(); exec("{$su_bin} squid -c \"{$squidbin} -z\" 2>&1", $results); echo date("Y/m/d H:i:s") . " Arti| Checking caches `{$squidbin}`....Please wait\n"; while (list($index, $val) = each($results)) { echo $val . "\n"; } $execnice = $unix->EXEC_NICE(); $nohup = $unix->find_program("nohup"); $chown = $unix->find_program("chown"); $tail = $unix->find_program("tail"); $GetCachesInsquidConf = $unix->SQUID_CACHE_FROM_SQUIDCONF(); while (list($CacheDirectory, $type) = each($GetCachesInsquidConf)) { echo date("Y/m/d H:i:s") . " Arti| Lauching a chown task in background mode on `{$CacheDirectory}`... this could take a while....\n"; $unix->chmod_alldirs(0755, $CacheDirectory); $cmd = "{$execnice}{$nohup} {$chown} -R squid:squid {$CacheDirectory} >/dev/null 2>&1 &"; echo date("Y/m/d H:i:s") . " Arti| {$cmd}\n"; shell_exec($cmd); } echo date("Y/m/d H:i:s") . " Arti| Starting squid....Please wait\n"; start_squid(true); sleep(5); exec("{$tail} -n 100 /var/log/squid/cache.log 2>&1", $results2); while (list($index, $val) = each($results2)) { echo $val . "\n"; } echo date("Y/m/d H:i:s") . " Arti| Done...\n"; echo date("Y/m/d H:i:s") . " Arti| Took " . $unix->distanceOfTimeInWords($t1, time()) . "\n"; }
function ufdb_save_update_settings() { $unix = new unix(); $CategoriesDatabasesByCron = intval(@file_get_contents("/etc/artica-postfix/settings/Daemons/CategoriesDatabasesByCron")); if ($CategoriesDatabasesByCron == 0) { if (is_file("/etc/cron.d/webfiltering-update")) { @unlink("/etc/cron.d/webfiltering-update"); system("/etc/init.d/cron reload"); } return; } $WebFUpdateH = intval(@file_get_contents("/etc/artica-postfix/settings/Daemons/WebFUpdateH")); $WebFUpdateM = intval(@file_get_contents("/etc/artica-postfix/settings/Daemons/WebFUpdateM")); $NICE = $unix->EXEC_NICE(); $php = $unix->LOCATE_PHP5_BIN(); $f[] = "MAILTO=\"\""; $f[] = "{$WebFUpdateM} {$WebFUpdateH} * * * root {$NICE} {$php} /usr/share/artica-postfix/exec.squid.blacklists.php --update --bycron >/dev/null 2>&1"; $f[] = ""; @file_put_contents("/etc/cron.d/webfiltering-update", @implode("\n", $f)); system("/etc/init.d/cron reload"); }
function rebuildcaches() { $logFile = "/usr/share/artica-postfix/ressources/logs/web/rebuild-cache.txt"; $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid"; $pid = @file_get_contents($pidfile); if ($pid < 100) { $pid = null; } $unix = new unix(); $sock = new sockets(); if ($unix->process_exists($pid, basename(__FILE__))) { ouputz("Already process exists {$pid}, aborting", __LINE__); build_progress("Already process exists {$pid}, aborting", 110); die; } $mypid = getmypid(); @file_put_contents($pidfile, $mypid); @unlink($logFile); build_progress("Listing caches....", 10); ouputz("Please wait, rebuild caches....", __LINE__); $t = time(); ouputz("Listing caches....", __LINE__); $array = ListCaches(); $mv = $unix->find_program("mv"); $rm = $unix->find_program("rm"); $php5 = $unix->LOCATE_PHP5_BIN(); build_progress(count($array) . " Caches to delete...", 15); ouputz(count($array) . " caches to delete...", __LINE__); if (count($array) == 0) { build_progress("Fatal, unable to list available caches.", 110); ouputz("Fatal, unable to list available caches...", __LINE__); squid_admin_mysql(0, "Fatal, unable to list available caches", null, __FILE__, __LINE__); @unlink("/etc/artica-postfix/squid.lock"); die; } $t = time(); @unlink("/etc/artica-postfix/squid.lock"); @file_put_contents("/etc/artica-postfix/squid.lock", time()); $squidbin = $unix->LOCATE_SQUID_BIN(); if (!is_file($squidbin)) { ouputz("squid, no such binary file", __LINE__); @unlink("/etc/artica-postfix/squid.lock"); return; } build_progress("{stopping_proxy_service}", 20); squid_admin_mysql(1, "Stopping Proxy service in order to rebuild caches", null, __FILE__, __LINE__); ouputz("Stopping squid, please wait...", __LINE__); 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"; } } shell_exec("/etc/init.d/squid stop --force --script=" . basename(__FILE__)); if ($GLOBALS["REPORT"]) { while (list($cache_dir, $ligne) = each($array)) { $DIRARRAY = $unix->DIR_STATUS($cache_dir); $size = $array["SIZE"]; $used = $array["USED"]; $pourc = $array["POURC"]; $mounted = $array["MOUNTED"]; $logs[] = "{$cache_dir} size: {$size}, used:{$used} {$pourc}% mounted on {$mounted}"; } squid_admin_mysql(2, "Report on caches status", @implode("\n", $logs), __FILE__, __LINE__); } reset($array); while (list($cache_dir, $ligne) = each($array)) { build_progress("Checking {$cache_dir}", 30); if (preg_match("#MemBooster#", $cache_dir)) { squid_admin_mysql(1, "Removing cache {$cache_dir}", null, __FILE__, __LINE__); ouputz("Removing {$cache_dir} content...", __LINE__); squid_admin_mysql(2, "Removing cache {$cache_dir} done", null, __FILE__, __LINE__); shell_exec("{$rm} -rf {$cache_dir}/*"); continue; } $DISK_STATUS = $unix->DF_SATUS_K($cache_dir); $DIRECTORY_SIZE = $unix->DIRSIZE_BYTES($cache_dir) / 1024 / 1024; $AIVA = $DISK_STATUS["AIVA"] * 1024; ouputz("Removing {$cache_dir} '{$DIRECTORY_SIZE}'M Available {$AIVA}M", __LINE__); shell_exec("{$rm} -rf {$cache_dir}"); ouputz("re-create {$cache_dir}", __LINE__); squid_admin_mysql(2, "Re-create {$cache_dir}", null, __FILE__, __LINE__); @mkdir($cache_dir, 0755, true); @chown($cache_dir, "squid"); @chgrp($cache_dir, "squid"); } $su = $unix->find_program("su"); $results = array(); build_progress("Create {$cache_dir}", 30); ouputz("Building new caches {$su} -c \"{$squidbin} -z\" squid", __LINE__); exec("{$su} -c \"{$squidbin} -z\" squid 2>&1", $results); while (list($num, $ligne) = each($results)) { ouputz("{$ligne}", __LINE__); } ouputz("Remove lock file...", __LINE__); @unlink("/etc/artica-postfix/squid.lock"); ouputz("Starting squid, please wait...", __LINE__); build_progress("{starting_proxy_service}", 35); 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(2, "Starting Proxy Service after rebuilding caches", null, __FILE__, __LINE__); shell_exec("{$php5} /usr/share/artica-postfix/exec.squid.watchdog.php --start --script=" . basename(__FILE__)); for ($i = 0; $i < 60; $i++) { $array = $unix->squid_get_cache_infos(); if (count($array) > 0) { break; } ouputz("Waiting {$i}s/60 cache is not ready...", __LINE__); sleep(1); } ouputz("Done... Squid-cache seems to be ready...", __LINE__); $NICE = $unix->EXEC_NICE(); $nohup = $unix->find_program("nohup"); build_progress("Refresh caches infos...", 50); ouputz("Refresh caches information, please wait...", __LINE__); shell_exec("{$php5} /usr/share/artica-postfix/exec.squid.php --cache-infos --force"); if (is_array($cachesRename)) { reset($cachesRename); while (list($index, $cache_dir) = each($cachesRename)) { build_progress("Removing old {$cache_dir}", 60); $cmd = "{$NICE} {$rm} -rf {$cache_dir} >/dev/null 2>&1 &"; squid_admin_mysql(2, "Ask to delete old cache dir {$cache_dir} done", "{$called}", __FILE__, __LINE__); ouputz("Deleting {$cache_dir} {$cmd}", __LINE__); shell_exec($cmd); } } build_progress("{done}", 100); $took = $unix->distanceOfTimeInWords($t, time()); squid_admin_mysql(2, "All Proxy caches was rebuilded took: {$took}", "{$called}", __FILE__, __LINE__); }
function restore_squidlogs($sourceDir) { if (!($handle = opendir("{$sourceDir}/squidlogs"))) { echo "Failed open {$sourceDir}/squidlogs\n"; return; } $password = null; $unix = new unix(); if (!$unix->is_socket("/var/run/mysqld/squid-db.sock")) { system_admin_events("Error,/var/run/mysqld/squid-db.sock no such socket", __FUNCTION__, __FILE__, __LINE__); return false; } $sock = new sockets(); $gunzip = $unix->find_program("gunzip"); $mysql = $unix->find_program("mysql"); $BLACKLIST = array(); $nice = $unix->EXEC_NICE(); $q = new mysql_squid_builder(); $sock = new sockets(); $BackupArticaRestoreNetwork = intval($sock->GET_INFO("BackupArticaRestoreNetwork")); if ($GLOBALS["NOT_RESTORE_NETWORK"]) { $BackupArticaRestoreNetwork = 0; } if ($BackupArticaRestoreNetwork == 0) { $BLACKLIST["dns_servers.gz"] = true; $BLACKLIST["dnsmasq_records.gz"] = true; } if ($q->mysql_password != null) { $password = "******" . $unix->shellEscapeChars($q->mysql_password); } $prefix = trim("{$mysql} --force -S /var/run/mysqld/squid-db.sock -u {$q->mysql_admin}{$password} squidlogs"); while (false !== ($filename = readdir($handle))) { if ($filename == ".") { continue; } if ($filename == "..") { continue; } if (isset($BLACKLIST[$filename])) { continue; } $SourceFile = "{$sourceDir}/squidlogs/{$filename}"; if (is_dir($SourceFile)) { continue; } echo "Restoring Proxy database/{$filename}\n"; $cmd = trim("{$nice} {$gunzip} -c {$SourceFile} |{$prefix}"); system($cmd); } }
function logrotate() { $unix = new unix(); $sock = new sockets(); $BackupMailLogPath = $sock->GET_INFO("BackupMailLogPath"); $BackupMailLogMaxTimeCompressed = $sock->GET_INFO("BackupMailLogMaxTimeCompressed"); if (!is_numeric($BackupMailLogMaxTimeCompressed)) { $BackupMailLogMaxTimeCompressed = 10080; } if ($BackupMailLogPath == null) { $BackupMailLogPath = "/home/logrotate_backup"; } $du = $unix->find_program("du"); $gzip = $unix->find_program("gzip"); @mkdir("{$BackupMailLogPath}", true, 660); if (!is_dir("{$BackupMailLogPath}")) { $unix->send_email_events("PostFinder:Error while creating {$BackupMailLogPath}"); return; } $nice = $unix->EXEC_NICE(); $timestart = time(); $log = array(); foreach (glob("{$BackupMailLogPath}/*.log") as $filename) { $timefile = $unix->file_time_min($filename); $basename = basename($filename); if ($GLOBALS["VERBOSE"]) { echo "{$basename}: {$timefile} minutes (need {$BackupMailLogMaxTimeCompressed} minutes)\n"; } if ($timefile > $BackupMailLogMaxTimeCompressed) { $targetgzip = "{$BackupMailLogPath}/{$basename}.gz"; $cmd = trim("{$nice}{$gzip} -c {$filename} >{$targetgzip}"); if ($GLOBALS["VERBOSE"]) { echo "{$cmd}\n"; } $time = time(); shell_exec($cmd); if (is_file($targetgzip)) { $ev = "{$basename} -> {$targetgzip} " . $unix->distanceOfTimeInWords($time, time()); if ($GLOBALS["VERBOSE"]) { echo "{$ev}\n"; } $log[] = $ev; @unlink($filename); } } } $strings = null; exec("{$du} -h -s {$BackupMailLogPath}", $results); $strings = @implode("", $results); if (preg_match("#^(.+?)\\s+#", $strings, $re)) { $final_size = $re[1]; } @file_put_contents("/usr/share/artica-postfix/ressources/logs/postfinder.dirsize.txt", $final_size); @chmod("/usr/share/artica-postfix/ressources/logs/postfinder.dirsize.txt", 777); if (count($log) > 0) { $unix->send_email_events("Postfinder: Directory size: {$strings} - " . count($log) . " maillog compressed (" . $unix->distanceOfTimeInWords($timestart, time()) . ")", "Directory: {$BackupMailLogPath}\n" . @implode("\n", $log), "postfix"); } }
function build_system_defaults() { $unix = new unix(); $sock = new sockets(); $nice = $unix->EXEC_NICE(); $php = $unix->LOCATE_PHP5_BIN(); $ArticaBackupEnabled = intval($sock->GET_INFO("ArticaBackupEnabled")); $users = new usersMenus(); @unlink("/etc/cron.d/artica-cron-backup"); @unlink("/etc/cron.d/artica-cron-pflogsumm"); if (is_file('/etc/artica-postfix/artica-backup.conf')) { if ($ArticaBackupEnabled == 1) { $ini = new Bs_IniHandler(); $ini->loadFile('/etc/artica-postfix/artica-backup.conf'); if (!isset($ini->_params["backup"]["backup_time"])) { $ini->_params["backup"]["backup_time"] = "03:00"; } if (preg_match("#([0-9]+):([0-9]+)#", $ini->_params["backup"]["backup_time"], $re)) { $backup_hour = intval($re[1]); $backup_min = intval($re[2]); $f[] = "MAILTO=\"\""; $f[] = "{$backup_min} {$backup_hour} * * * root {$nice} /usr/share/artica-postfix/bin/artica-backup --backup >/dev/null 2>&1"; $f[] = ""; @file_put_contents("/etc/cron.d/artica-cron-backup", @implode("\n", $f)); $f = array(); } } } if (is_file('/etc/artica-postfix/settings/Daemons/pflogsumm')) { $ini = new Bs_IniHandler(); $ini->loadFile('/etc/artica-postfix/settings/Daemons/pflogsumm'); $schedule_time = trim($ini->_params['SETTINGS']['schedule']); if ($schedule_time != null) { $f[] = "MAILTO=\"\""; $f[] = "{$schedule_time} root {$nice} {$php} /usr/share/artica-postfix/exec.postfix.reports.php >/dev/null 2>&1"; $f[] = ""; @file_put_contents("/etc/cron.d/artica-cron-pflogsumm", @implode("\n", $f)); $f = array(); } } $prefix = "/usr/share/artica-postfix"; $f = array(); $f[] = "MAILTO=\"\""; $f[] = "@reboot root {$nice} /sbin/modprobe cifs && echo 0 > /proc/fs/cifs/OplockEnabled >/dev/null 2>&1"; $f[] = ""; @file_put_contents("/etc/cron.d/cifs-fix", @implode("\n", $f)); $f = array(); $f[] = "MAILTO=\"\""; $f[] = "@reboot root {$nice} {$php} {$prefix}/exec.schedules.php >/dev/null 2>&1"; $f[] = ""; @file_put_contents("/etc/cron.d/schedules", @implode("\n", $f)); $f = array(); $f[] = "MAILTO=\"\""; $f[] = "7,14,21,28,35,42,49,56 0 * * * * root {$nice} {$php} {$prefix}/exec.dnsmasq.php --varrun >/dev/null 2>&1"; $f[] = ""; @file_put_contents("/etc/cron.d/artica-dnsmasqrun", @implode("\n", $f)); $f = array(); $f[] = "MAILTO=\"\""; $f[] = "10,34,51 0 * * * * root {$nice} {$php} {$prefix}/exec.watchdog.php --monit >/dev/null 2>&1"; $f[] = ""; @file_put_contents("/etc/cron.d/artica-dnsmasqrun", @implode("\n", $f)); $f = array(); $f[] = "MAILTO=\"\""; $f[] = "0,2,4,6,8,10,12,14,16,18,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,58 * * * * root {$nice} {$php} {$prefix}/exec.parse-orders.php >/dev/null 2>&1"; $f[] = ""; @file_put_contents("/etc/cron.d/artica-parseorders", @implode("\n", $f)); $f = array(); if ($users->spamassassin_installed) { $f[] = "MAILTO=\"\""; $f[] = "10 3,6,9,12,15,18,21,23 * * * root {$nice} {$php} {$prefix}/exec.sa-learn-cyrus.php --execute >/dev/null 2>&1"; $f[] = ""; @file_put_contents("/etc/cron.d/artica-salearn-cyrus", @implode("\n", $f)); $f = array(); } if ($users->fetchmail_installed) { $f[] = "MAILTO=\"\""; $f[] = "0,2,4,6,8,10,12,14,16,18,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,58 * * * * root {$nice} {$php} {$prefix}/exec.fetchmail.sql.php >/dev/null 2>&1"; $f[] = ""; @file_put_contents("/etc/cron.d/artica-ftechmailsql", @implode("\n", $f)); $f = array(); } }
function build_dd($path, $size) { $dir = dirname($path); if (!is_dir($dir)) { writelogs("{$dir} no such directory, create it", __FUNCTION__, __FILE__, __LINE__); @mkdir(dirname($path), 644, true); } if (!is_dir($dir)) { writelogs("{$dir} no such directory", __FUNCTION__, __FILE__, __LINE__); return false; } $unix = new unix(); $dd = $unix->find_program("dd"); $size = $size * 1024; $NICE = $unix->EXEC_NICE(); $cmd = trim("{$NICE} {$dd} if=/dev/zero of={$path} bs=1024 count={$size} 2>&1"); if ($GLOBALS["VERBOSE"]) { echo "{$cmd}\n"; } exec($cmd, $results); echo "build_dd() {$cmd} " . count($results) . " rows\n"; while (list($num, $ligne) = each($results)) { echo "build_dd() {$ligne}\n"; } if (!stat_system($path)) { echo "build_dd() {$path} no such block\n"; return false; } if (build_loop($path)) { return true; } }
if (!is_dir("/usr/share/artica-postfix/ressources/logs/web/queue/sessions")) { @mkdir("/usr/share/artica-postfix/ressources/logs/web/queue/sessions", 0755, true); } writeprogress(5, "artica-postfix/bin"); $unix->chmod_func(0755, "/usr/share/artica-postfix/bin/*"); $unix->chmod_func(0755, "/usr/share/artica-postfix/ressources/mem.pl"); $unix->chmod_func(0644, "/usr/share/artica-postfix/bin/install/amavis/check-external-users.conf"); $unix->chown_func("root", "root", "/usr/share/artica-postfix/bin/*"); $unix->chown_func("root", "root", "/usr/share/artica-postfix/bin/install/amavis"); $unix->chown_func($username, $groupname, "/var/lib/php/session/*"); $unix->chown_func($username, $groupname, "/var/lib/php5/*"); $unix->chown_func($username, $groupname, "/var/lighttpd/upload"); $unix->chown_func("mysql", "mysql", "/var/run/mysqld/*"); writeprogress(5, "/var/lib/mysql"); $chown = $unix->find_program("chown"); $nice = $unix->EXEC_NICE(); $nohup = $unix->find_program("nohup"); $rm = $unix->find_program("rm"); if (system_is_overloaded(basename(__FILE__))) { die; } $tmpf = $unix->FILE_TEMP(); $sh[] = "#!/bin/sh"; $sh[] = "{$nice} {$chown} -R mysql:mysql /var/lib/mysql >/dev/null 2>&1"; $sh[] = "{$rm} -f {$tmpf}.sh"; $sh[] = "\n"; @file_put_contents("{$tmpf}.sh", @implode("\n", $sh)); @chmod("{$tmpf}.sh", 0755); system("{$nohup} {$tmpf}.sh >/dev/null 2>&1 &"); $sh = array(); $postconf = $unix->find_program("postconf");
<?php if (posix_getuid() != 0) { die("Cannot be used in web server mode\n\n"); } include_once dirname(__FILE__) . '/ressources/class.os.system.inc'; include_once dirname(__FILE__) . "/framework/frame.class.inc"; include_once dirname(__FILE__) . "/framework/class.unix.inc"; include_once dirname(__FILE__) . "/framework/class.settings.inc"; $GLOBALS["EXEC_PID_FILE"] = "/etc/artica-postfix/" . basename(__FILE__) . ".damon.pid"; $pid = @file_get_contents($GLOBALS["EXEC_PID_FILE"]); $unix = new unix(); $GLOBALS["EXEC_NICE"] = $unix->EXEC_NICE(); $GLOBALS["NOHUP"] = $unix->find_program("nohup"); if ($unix->process_exists($pid)) { $ProcessTime = $unix->PROCCESS_TIME_MIN($pid); events("artica-background already executed pid {$pid} since {$ProcessTime} Minutes", __FUNCTION__, __LINE__); echo "Starting......: " . date("H:i:s") . " artica-background Already executed pid {$pid}\n"; die; } if ($argv[1] == "--manual") { FillMemory(); die; } $sock = new sockets(); $EnableArticaBackground = $sock->GET_INFO("EnableArticaBackground"); if (!is_numeric($EnableArticaBackground)) { $EnableArticaBackground = 1; } if ($EnableArticaBackground == 0) { die;
function backup_cyrus() { $unix = new unix(); $tempdir = $unix->TEMP_DIR(); $q = new mysql(); $users = new usersMenus(); if (!$users->cyrus_imapd_installed) { cyrus_admin_mysql(0, "Unable to backup: cyrus-impad NOT Installed", null, __FILE__, __LINE__); return true; } $partition_default = $users->cyr_partition_default; $config_directory = $users->cyr_config_directory; $tar = $unix->find_program("tar"); $su = $unix->find_program("su"); $rsync = $unix->find_program("rsync"); @mkdir("{$GLOBALS["MOUNTED_PATH_FINAL"]}/cyrus-imap", 0755, true); if (!is_dir("{$GLOBALS["MOUNTED_PATH_FINAL"]}/cyrus-imap")) { cyrus_admin_mysql(0, __LINE__ . "]: Unable to backup: Permission denied", "On NAS {$GLOBALS["MOUNTED_PATH_FINAL"]}/cyrus-imap no such directory", __FILE__, __LINE__); return; } if ($GLOBALS["VERBOSE"]) { echo "{$GLOBALS["MOUNTED_PATH_FINAL"]}/cyrus-imap OK\n"; } if (!is_file("{$users->ctl_mboxlist}")) { cyrus_admin_mysql(0, "Unable to backup: ctl_mboxlist no such binary", null, __FILE__, __LINE__); return; } $L = explode("\n", @file_get_contents("/etc/security/limits.conf")); $T = array(); while (list($index, $line) = each($L)) { $line = trim($line); if (trim($line) == null) { continue; } if (substr($line, 0, 1) == "#") { continue; } if (preg_match("#^cyrus#", $line)) { continue; } $T[] = $line; } $T[] = "cyrus soft nofile 64000"; $T[] = "cyrus hard nofile 64000"; @file_put_contents("/etc/security/limits.conf", @implode("\n", $T) . "\n"); $L = array(); $T = array(); @chmod("{$tempdir}", 0777); $cmd = "{$su} - cyrus -c \"{$users->ctl_mboxlist} -d >{$tempdir}/mailboxlist.txt\""; if ($GLOBALS["VERBOSE"]) { echo $cmd . "\n"; } exec($cmd, $results); if (!is_file("{$tempdir}/mailboxlist.txt")) { cyrus_admin_mysql(0, "Unable to backup: unable to export mailbox list", "file {$tempdir}/mailboxlist.txt not exists\n****\n{$cmd}\n****\n\n" . implode("\n", $results), __FILE__, __LINE__); } else { if ($GLOBALS["CyrusBackupNas"]["COMPRESS_ENABLE"] == 0) { if (!@copy("{$tempdir}/mailboxlist.txt", "{$GLOBALS["MOUNTED_PATH_FINAL"]}/cyrus-imap/mailboxlist.txt")) { cyrus_admin_mysql(0, "Unable to backup: Permission denied on resource", "{$GLOBALS["MOUNTED_PATH_FINAL"]}/cyrus-imap permission denied"); @unlink("{$tempdir}/mailboxlist.txt"); return; } $size = @filesize("{$GLOBALS["MOUNTED_PATH_FINAL"]}/cyrus-imap/mailboxlist.txt"); $size = FormatBytes($size / 1024); cyrus_admin_mysql(2, "mailboxlist.txt - {$size} - success", null, __FILE__, __LINE__); } if ($GLOBALS["CyrusBackupNas"]["COMPRESS_ENABLE"] == 1) { if (!$unix->compress("{$tempdir}/mailboxlist.txt", "{$GLOBALS["MOUNTED_PATH_FINAL"]}/cyrus-imap/mailboxlist.txt.gz")) { cyrus_admin_mysql(0, "Unable to backup: Permission denied on resource", "{$GLOBALS["MOUNTED_PATH_FINAL"]}/cyrus-imap permission denied"); @unlink("{$tempdir}/mailboxlist.txt"); return; } $size = @filesize("{$GLOBALS["MOUNTED_PATH_FINAL"]}/cyrus-imap/mailboxlist.txt.gz"); $size = FormatBytes($size / 1024); cyrus_admin_mysql(2, "mailboxlist.txt.gz - {$size} - success", null, __FILE__, __LINE__); } } $results = array(); if ($GLOBALS["CyrusBackupNas"]["COMPRESS_ENABLE"] == 0) { if (!is_file($rsync)) { cyrus_admin_mysql(0, "Rsync is not present, backup operation will be stopped...", null, __FILE__, __LINE__); return false; } cyrus_admin_mysql(2, "Starting backup {$partition_default} and {$config_directory}", null, __FILE__, __LINE__); $cmd = "{$rsync} -vaR --delete --delete-after {$partition_default} {$config_directory} {$GLOBALS["MOUNTED_PATH_FINAL"]}/cyrus-imap"; $t = time(); exec($cmd, $results); cyrus_admin_mysql(2, "Backup: took " . $unix->distanceOfTimeInWords($t, time()), @implode("\n", $results), __FILE__, __LINE__); InsertToMysql(); return; } @chdir($partition_default); $nice = $unix->EXEC_NICE(); if ($GLOBALS["CyrusBackupNas"]["COMPRESS_ENABLE"] == 1) { cyrus_admin_mysql(2, "Starting Compressing {$partition_default}", null, __FILE__, __LINE__); $cmd = "{$nice} {$tar} -Pcjf {$GLOBALS["MOUNTED_PATH_FINAL"]}/cyrus-imap/mail-data-backup.tar.bz2 * >{$GLOBALS["MOUNTED_PATH_FINAL"]}/cyrus-imap/mail-data-backup.report.txt"; } if ($GLOBALS["VERBOSE"]) { echo $cmd . "\n"; } shell_exec($cmd); $data = @file_get_contents("{$GLOBALS["MOUNTED_PATH_FINAL"]}/cyrus-imap/mail-data-backup.report.txt"); if (!is_file("{$GLOBALS["MOUNTED_PATH_FINAL"]}/cyrus-imap/mail-data-backup.tar.bz2")) { cyrus_admin_mysql(0, "Unable to backup: mail-data-backup.tar.bz2 Permission denied or compression failed", $data, __FILE__, __LINE__); return; } $size = @filesize("{$GLOBALS["MOUNTED_PATH_FINAL"]}/cyrus-imap/mail-data-backup.tar.bz2"); $size = FormatBytes($size / 1024); cyrus_admin_mysql(2, "cyrus-imap/mail-data-backup.tar.bz2 - {$size} - success", $data, __FILE__, __LINE__); $results = array(); @chdir($config_directory); if ($GLOBALS["VERBOSE"]) { echo $cmd . "\n"; } cyrus_admin_mysql(2, "Starting Compressing {$config_directory}", null, __FILE__, __LINE__); $cmd = "{$nice} {$tar} -Pcjf {$GLOBALS["MOUNTED_PATH_FINAL"]}/cyrus-imap/configdirectory.tar.bz2 * >{$GLOBALS["MOUNTED_PATH_FINAL"]}/cyrus-imap/configdirectory.report.txt"; shell_exec($cmd); $data = @file_get_contents("{$GLOBALS["MOUNTED_PATH_FINAL"]}/cyrus-imap/configdirectory.report.txt"); if (!is_file("{$GLOBALS["MOUNTED_PATH_FINAL"]}/cyrus-imap/configdirectory.tar.bz2")) { cyrus_admin_mysql(0, "Unable to backup: configdirectory.tar.bz2 Permission denied or compression failed", $data, __FILE__, __LINE__); return; } $size = @filesize("{$GLOBALS["MOUNTED_PATH_FINAL"]}/cyrus-imap/configdirectory.tar.bz2"); $size = FormatBytes($size / 1024); cyrus_admin_mysql(2, "cyrus-imap/mail-data-backup.tar.bz2 - {$size} - success", $data, __FILE__, __LINE__); InsertToMysql(); }
function ExportDrop() { if ($GLOBALS["EnablePostfixAutoBlock"] != 1) { if ($GLOBALS["VERBOSE"]) { echo "EnablePostfixAutoBlock={$GLOBALS["EnablePostfixAutoBlock"]}, aborting..\n"; } return; } $pidpath = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid"; $pid = @file_get_contents($pidpath); $unix = new unix(); if ($unix->process_exists($pid)) { if ($GLOBALS["VERBOSE"]) { echo "Already executed {$pid}\n"; } return; } @file_put_contents($pidpath, getmypid()); $grep = $unix->find_program("grep"); $tail = $unix->find_program("tail"); $syslog = $unix->LOCATE_SYSLOG_PATH(); $NICE = $unix->EXEC_NICE(); $syslogSize = $unix->file_size($syslog); if ($syslogSize > 512000000) { include_once dirname(__FILE__) . "/ressources/class.templates.inc"; $unix->send_email_events("{$syslog} too big (" . str_replace(" ", " ", FormatBytes($syslogSize / 1024)) . "...", __FUNCTION__ . " is aborted from script " . basename(__FILE__), "system"); return; } $cmd = "{$NICE}{$grep} -E \"kernel.*?SMTP DROP\" {$syslog} |{$tail} -n 2000 >/usr/share/artica-postfix/ressources/logs/iptables-smtp-drop.log"; if ($GLOBALS["VERBOSE"]) { echo "{$cmd}\n"; } shell_exec($cmd); @chmod("/usr/share/artica-postfix/ressources/logs/iptables-smtp-drop.log", 0777); }
function vacuumdb() { $unix = new unix(); $TimeFile = "/usr/local/ArticaStats/bin/vacuumdb.forced.time"; $pidfile = "/usr/local/ArticaStats/bin/vacuumdb.forced.pid"; $pid = $unix->get_pid_from_file($pidfile); if ($unix->process_exists($pid, basename(__FILE__))) { return; } @file_put_contents($pidfile, getmypid()); $TimeExec = $unix->file_time_min($TimeFile); if ($TimeExec < 10080) { return; } @unlink($TimeFile); @file_put_contents($TimeFile, time()); $postgres = new postgres_sql(true); if ($postgres->isRemote) { return; } if (!class_exists("usersMenus")) { include_once dirname(__FILE__) . "/ressources/class.users.menus.inc"; } $users = new usersMenus(); $InfluxAdminRetentionTime = intval(@file_get_contents("/etc/artica-postfix/settings/Daemons/InfluxAdminRetentionTime")); if ($InfluxAdminRetentionTime == 0) { $InfluxAdminRetentionTime = 365; } if (!$users->CORP_LICENSE) { $InfluxAdminRetentionTime = 5; } $postgres->QUERY_SQL("DELETE FROM access_log WHERE time < NOW() - INTERVAL '{$InfluxAdminRetentionTime} days'"); $postgres->QUERY_SQL("DELETE FROM main_size WHERE zdate < NOW() - INTERVAL '{$InfluxAdminRetentionTime} days'"); $postgres->QUERY_SQL("DELETE FROM system WHERE zdate < NOW() - INTERVAL '30 days'"); $t1 = time(); $NICE = $unix->EXEC_NICE(); exec("{$NICE} /usr/local/ArticaStats/bin/vacuumdb -f -v -h /var/run/ArticaStats --dbname=proxydb --username=ArticaStats 2>&1", $results); $Took = $unix->distanceOfTimeInWords($t1, time()); squid_admin_mysql(2, "Indexing Statistics Database took: {$Took}", @implode("\n", $results), __FILE__, __LINE__); InfluxDbSize(); }
function execute_hourly() { $unix = new unix(); $pidFile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid"; $pid = @file_get_contents($pidFile); if ($unix->process_exists($pid, basename(__FILE__))) { sargevents("execute_hourly(): {$pid} already running"); if ($GLOBALS["VERBOSE"]) { echo " {$pid} already running\n"; } die; } @file_put_contents($pidFile, getmypid()); $pidTime = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".time"; if ($GLOBALS["VERBOSE"]) { echo "Time: {$pidTime}"; } $pidTimeEx = $unix->file_time_min($pidTime); if ($GLOBALS["VERBOSE"]) { echo " {$pidTimeEx} mn"; } if (!$GLOBALS["FORCE"]) { if ($pidTimeEx < 60) { sargevents("{$pidTime} = {$pidTimeEx}Mn require 60mn"); return; } } @unlink($pidTime); @file_put_contents($pidTime, time()); sarg_admin_events("Executing hourly task...", __FUNCTION__, __FILE__, __LINE__); $t = time(); buildconf(); $unix = new unix(); $t = time(); $TODAY = date("d/m/Y"); $sock = new sockets(); $date = new DateTime(); $date->sub(new DateInterval('P1D')); $YESTERDAY = $date->format("d/m/Y"); $LASTHOUR = date("H", time() - 3600); $HOUR = date("H", time()); $nice = $unix->EXEC_NICE(); $sarg_bin = $unix->find_program("sarg"); $results[] = "Today: {$TODAY}"; $results[] = "Last Hour: {$LASTHOUR}"; $results[] = "Current Hour: {$LASTHOUR}"; $SargOutputDir = $sock->GET_INFO("SargOutputDir"); if ($SargOutputDir == null) { $SargOutputDir = "/var/www/html/squid-reports"; } $lighttpd_user = $unix->APACHE_SRC_ACCOUNT(); $results[] = "Output directory: {$SargOutputDir}\n"; $results[] = "Web service user: {$lighttpd_user}\n"; $results[] = "Sarg binary: {$sarg_bin}"; $results[] = "Nice command: {$nice}"; @mkdir("{$SargOutputDir}/daily", 0755, true); $unix->chown_func($lighttpd_user, $lighttpd_user, "{$SargOutputDir}/*"); @mkdir("{$SargOutputDir}/hourly", 0755); $squid = new squidbee(); if ($squid->is_auth()) { $usersauth = true; } if ($usersauth) { events("User authentification enabled"); $u = " -i "; } else { events("User authentification disabled"); } $cmds[] = "{$nice}{$sarg_bin} {$u}-f /etc/squid3/sarg.conf"; $cmds[] = "-l /var/log/squid/access.log -o \"{$SargOutputDir}/hourly\" -z -d {$TODAY}-{$TODAY}"; $cmds[] = "-t \"{$LASTHOUR}:00-{$HOUR}:00\""; buildconf(); $cmline = @implode(" ", $cmds); sargevents("execute_hourly(): {$cmline}"); exec("{$cmline} 2>&1", $results); $took = $unix->distanceOfTimeInWords($t, time()); sargevents("Hourly {$LASTHOUR}:00-{$HOUR}:00 report generated took: {$took}"); sarg_admin_events("Hourly {$LASTHOUR}:00-{$HOUR}:00 report generated took: {$took}\n" . @implode("\n", $results), __FUNCTION__, __FILE__, __LINE__, "sarg"); build_index_page(); $unix->chown_func($lighttpd_user, $lighttpd_user, "{$SargOutputDir}/*"); }
function GetIndex() { $WORKING_DIR = "/home/working_toulouse_databases"; $WORKING_DOWNLOAD = "{$WORKING_DIR}/dowloads"; $WORKING_UPLOAD = "{$WORKING_DIR}/uploads"; @mkdir($WORKING_DOWNLOAD, 0755, true); @mkdir($WORKING_UPLOAD, 0755, true); $unix = new unix(); $tar = $unix->find_program("tar"); $catz = new mysql_catz(); $tmpfile = $unix->FILE_TEMP(); $tmpdir = $unix->TEMP_DIR(); $rm = $unix->find_program("rm"); $mainuri = "ftp://ftp.univ-tlse1.fr/pub/reseau/cache/squidguard_contrib"; $EXEC_NICE = $unix->EXEC_NICE(); $ufdbGenTable = $unix->find_program("ufdbGenTable"); $curl = new ccurl("{$mainuri}/MD5SUM.LST"); if (!$curl->GetFile($tmpfile)) { echo "Failed to download MD5SUM.LST\n"; return; } $tr = explode("\n", @file_get_contents($tmpfile)); while (list($index, $line) = each($tr)) { if (preg_match("#(.+?)\\s+(.+)#", $line, $re)) { $filename = trim($re[1]); $md5 = trim($re[2]); $array[$md5] = $filename; } } @unlink($tmpfile); $q = new mysql_squid_builder(); $TLSE_CONVERTION = TLSE_CONVERTION(); $FINAL_ARRAY = array(); while (list($filename, $md5) = each($array)) { $category = str_replace(".tar.gz", "", $filename); if (isset($TLSE_CONVERTION[$category])) { $FINAL_ARRAY[$filename] = $md5; } } $UPDATED = 0; $MAIN_ARRAY = unserialize(base64_decode(@file_get_contents("{$WORKING_UPLOAD}/index.txt"))); while (list($filename, $md5) = each($FINAL_ARRAY)) { $TargetFile = "{$WORKING_DOWNLOAD}/{$filename}"; $categoryname = str_replace(".tar.gz", "", $filename); if ($categoryname == "adult") { continue; } if ($categoryname == "aggressive") { continue; } if ($categoryname == "agressif") { continue; } if ($categoryname == "redirector") { continue; } if ($categoryname == "ads") { continue; } if ($categoryname == "drogue") { continue; } $MyStoreMd5 = md5_file($TargetFile); if ($MyStoreMd5 == $md5) { echo "Skipping {$filename}\n"; continue; } echo "Downloading {$filename}\n"; $curl = new ccurl("{$mainuri}/{$filename}"); $tmpfile = $unix->FILE_TEMP(); if (!$curl->GetFile($tmpfile)) { echo "Failed {$curl->error}\n"; @unlink($tmpfile); continue; } $md5_tmp = md5_file($tmpfile); if ($md5_tmp != $md5) { echo "Failed Corrupted file\n"; @unlink($tmpfile); continue; } if (is_file($TargetFile)) { @unlink($TargetFile); } if (!@copy($tmpfile, $TargetFile)) { echo "Failed Copy file\n"; @unlink($tmpfile); @unlink($TargetFile); continue; } @unlink($tmpfile); $MyStoreMd5 = md5_file($TargetFile); if ($MyStoreMd5 != $md5) { echo "Failed MD5 file\n"; @unlink($TargetFile); continue; } @mkdir("{$WORKING_DIR}/{$categoryname}", 0755, true); echo "Extracting {$TargetFile}\n"; $cmd = "{$tar} xvf {$TargetFile} -C {$WORKING_DIR}/{$categoryname}/"; echo $cmd . "\n"; system($cmd); $SOURCE_DIR = find_sources("{$WORKING_DIR}/{$categoryname}"); if (!is_file("{$SOURCE_DIR}/domains")) { echo "Failed {$SOURCE_DIR}/domains no such file\n"; @unlink($TargetFile); continue; } $COUNT_OF_DOMAINS = $unix->COUNT_LINES_OF_FILE("{$SOURCE_DIR}/domains"); echo "{$categoryname} {$COUNT_OF_DOMAINS} domains\n"; if ($COUNT_OF_DOMAINS == 0) { shell_exec("{$rm} -rf {$WORKING_DIR}/{$categoryname}"); @unlink($TargetFile); continue; } if (is_file("{$SOURCE_DIR}/domains.ufdb")) { @unlink("{$SOURCE_DIR}/domains.ufdb"); } if (!is_file("{$SOURCE_DIR}/urls")) { @touch("{$SOURCE_DIR}/urls"); } $u = " -u {$SOURCE_DIR}/urls"; $d = " -d {$SOURCE_DIR}/domains"; $cmd = "{$EXEC_NICE}{$ufdbGenTable} -n -q -W -t {$categoryname}{$d}{$u}"; echo $cmd . "\n"; shell_exec($cmd); if (!is_file("{$SOURCE_DIR}/domains.ufdb")) { echo "Failed to compile {$categoryname}\n"; @unlink($TargetFile); continue; } $MD5SRC = md5_file("{$SOURCE_DIR}/domains.ufdb"); if (is_file("{$WORKING_UPLOAD}/{$categoryname}.gz")) { @unlink("{$WORKING_UPLOAD}/{$categoryname}.gz"); } $unix->compress("{$SOURCE_DIR}/domains.ufdb", "{$WORKING_UPLOAD}/{$categoryname}.gz"); $MD5GZ = md5_file("{$WORKING_UPLOAD}/{$categoryname}.gz"); $UPDATED++; $NOTIFICATIONS[] = "{$categoryname} updated with {$COUNT_OF_DOMAINS} domains"; $MAIN_ARRAY[$categoryname]["ROWS"] = $COUNT_OF_DOMAINS; $MAIN_ARRAY[$categoryname]["MD5SRC"] = $MD5SRC; $MAIN_ARRAY[$categoryname]["MD5GZ"] = $MD5GZ; $MAIN_ARRAY[$categoryname]["TIME"] = time(); $MAIN_ARRAY[$categoryname]["SIZE"] = @filesize("{$WORKING_UPLOAD}/{$categoryname}.gz"); @file_put_contents("{$WORKING_UPLOAD}/index.txt", base64_encode(serialize($MAIN_ARRAY))); } if ($UPDATED > 0) { PushToRepo_alls(); sendEmail("{$UPDATED} Toulouse Unversity databases uploaded.", @implode("\n", $NOTIFICATIONS)); } }
function apps_upgrade() { $unix = new unix(); $nohup = $unix->find_program("nohup"); $chmod = $unix->find_program("chmod"); $php5 = $unix->LOCATE_PHP5_BIN(); $NICE = $unix->EXEC_NICE(); @unlink("/etc/cron.d/apps-upgrade"); $cmd = trim("{$NICE} {$php5} /usr/share/artica-postfix/exec.setup-center.php --install >/dev/null 2>&1 &"); shell_exec("{$cmd}"); writelogs_framework($cmd, __FUNCTION__, __FILE__, __LINE__); }
function test_sensors() { $unix = new unix(); $q = new mysql(); $sock = new sockets(); $cachefile = "/usr/share/artica-postfix/ressources/logs/web/sensors.array"; $pidtime = "/etc/artica-postfix/pids/exec.lm-sensors.php.time"; $LMSensorsEnable = intval($sock->GET_INFO("LMSensorsEnable")); if ($LMSensorsEnable == 0) { if (is_file("/etc/cron.d/lm-sensors")) { @unlink("/etc/cron.d/lm-sensors"); } @unlink($cachefile); return; } if (!is_file("/etc/cron.d/lm-sensors")) { $nice = $unix->EXEC_NICE(); $php5 = $unix->LOCATE_PHP5_BIN(); $me = __FILE__; $cmdline = trim("{$nice} {$php5} {$me} --test --cron"); $f[] = "MAILTO=\"\""; $f[] = "0,15,30,45 * * * * root {$cmdline} >/dev/null 2>&1"; $f[] = ""; @file_put_contents("/etc/cron.d/lm-sensors", @implode("\n", $f)); } if (!$GLOBALS["FORCE"]) { $time = $unix->file_time_min($pidtime); if ($time < 15) { events("Current {$time}Mn, require 15Mn...", __FUNCTION__, __LINE__); return; } } @unlink($pidtime); @file_put_contents($pidtime, time()); $sensors = $unix->find_program("sensors"); events("Running sensors...", __FUNCTION__, __LINE__); exec("{$sensors} 2>&1", $results); $CurrentDay = date("Ymd"); if (!$q->TABLE_EXISTS("{$CurrentDay}_sensors", "artica_events")) { $sql = "CREATE TABLE IF NOT EXISTS `{$CurrentDay}_sensors` (\n\t\t`adaptater` varchar(90) NOT NULL,\n\t\t`zkey` varchar(90) NOT NULL,\n\t\t`percent` FLOAT,\n\t\t`zDate` DATETIME,\n\t\tKEY `adaptater` (`adaptater`),\n\t\tKEY `zDate` (`zDate`),\n\t\tKEY `zkey` (`zkey`),\n\t\tKEY `percent` (`percent`)\n\t\t\n\t\t) ENGINE=MYISAM;"; $q->QUERY_SQL($sql, "artica_events"); } $rows = array(); while (list($path, $val) = each($results)) { $HIGH = null; if (preg_match("#Adapter:(.*)#i", $val, $re)) { $adaptater = trim($re[1]); } if (preg_match("#(.*?):\\s+\\+([0-9\\.]+).*?\\((.*?)\\)#", $val, $re)) { $KEY = $re[1]; $TEMP = $re[2]; $POSZ = $re[3]; if (preg_match("#high.*?=\\s+\\+([0-9\\.]+)#", $POSZ, $re)) { $HIGH = $re[1]; } if (preg_match("#crit.*?=\\s+\\+([0-9\\.]+)#", $POSZ, $re)) { $CRIT = $re[1]; } if ($HIGH == null) { $HIGH = $CRIT; } $xtime = date("Y-m-d H:i:s"); $ARRAY[$adaptater][$KEY]["TEMP"] = $TEMP; $ARRAY[$adaptater][$KEY]["HIGH"] = $HIGH; $ARRAY[$adaptater][$KEY]["CRIT"] = $CRIT; $percent = $TEMP / $CRIT; $percent = $percent * 100; $ARRAY[$adaptater][$KEY]["PERC"] = round($percent, 2); $rows[] = "('{$adaptater}','{$KEY}','{$xtime}','{$percent}')"; if ($ARRAY[$adaptater][$KEY]["PERC"] > 90) { squid_admin_mysql(0, "Warning {$ARRAY[$adaptater][$KEY]["PERC"]}% of temperature reached!", "Adaptater:{$adaptater}\nType:{$KEY}\nTemperature: {$TEMP}°C\nCritic:{$CRIT}°C", __FILE__, __LINE__); } } } if (count($rows) > 0) { $sql = "INSERT IGNORE INTO `{$CurrentDay}_sensors` (`adaptater`,`zkey`,`zDate`,`percent`) VALUES " . @implode(",", $rows); $q->QUERY_SQL($sql, "artica_events"); } events("Saving /usr/share/artica-postfix/ressources/logs/web/sensors.array", __FUNCTION__, __LINE__); @file_put_contents("/usr/share/artica-postfix/ressources/logs/web/sensors.array", serialize($ARRAY)); @chmod("/usr/share/artica-postfix/ressources/logs/web/sensors.array", 0755); }
function FillMemory() { $unix = new unix(); $GLOBALS["TIME"] = unserialize(@file_get_contents("/etc/artica-postfix/pids/" . basename(__FILE__) . ".GLOBALS")); if (GET_INFO_DAEMON("cpuLimitEnabled") == 1) { $GLOBALS["cpuLimitEnabled"] = true; } else { $GLOBALS["cpuLimitEnabled"] = false; } $_GET["NICE"] = $unix->EXEC_NICE(); $GLOBALS["EXEC_NICE"] = $_GET["NICE"]; $GLOBALS["PHP5"] = $unix->LOCATE_PHP5_BIN(); $GLOBALS["SU"] = $unix->find_program("su"); $users = new settings_inc(); $sock = new sockets(); $DisableArticaStatusService = $sock->GET_INFO("DisableArticaStatusService"); $EnableArticaExecutor = $sock->GET_INFO("EnableArticaExecutor"); if (!is_numeric($DisableArticaStatusService)) { $DisableArticaStatusService = 0; } if (!is_numeric($EnableArticaExecutor)) { $EnableArticaExecutor = 1; } $GLOBALS["KAV4PROXY_INSTALLED"] = false; $GLOBALS["SPAMASSASSIN_INSTALLED"] = $users->spamassassin_installed; $GLOBALS["ARTICA_STATUS_DISABLED"] = $DisableArticaStatusService; $GLOBALS["EXECUTOR_DAEMON_ENABLED"] = $EnableArticaExecutor; $GLOBALS["SQUID_INSTALLED"] = $users->SQUID_INSTALLED; $GLOBALS["KAV4PROXY_INSTALLED"] = $users->KAV4PROXY_INSTALLED; $GLOBALS["MILTER_GREYLIST_INSTALLED"] = $users->MILTERGREYLIST_INSTALLED; $GLOBALS["POSTFIX_INSTALLED"] = $users->POSTFIX_INSTALLED; $GLOBALS["SAMBA_INSTALLED"] = $users->SAMBA_INSTALLED; $GLOBALS["GREYHOLE_INSTALLED"] = $users->GREYHOLE_INSTALLED; $GLOBALS["MUNIN_CLIENT_INSTALLED"] = $users->SAMBA_INSTALLED; $GLOBALS["CYRUS_IMAP_INSTALLED"] = $users->cyrus_imapd_installed; $_GET["MIME_DEFANGINSTALLED"] = $users->MIMEDEFANG_INSTALLED; $GLOBALS["DANSGUARDIAN_INSTALLED"] = $users->DANSGUARDIAN_INSTALLED; $GLOBALS["OPENVPN_INSTALLED"] = $users->OPENVPN_INSTALLED; $GLOBALS["OCS_INSTALLED"] = $users->OCSI_INSTALLED; $GLOBALS["UFDBGUARD_INSTALLED"] = $users->APP_UFDBGUARD_INSTALLED; $GLOBALS["KAS_INSTALLED"] = $users->kas_installed; $GLOBALS["ZARAFA_INSTALLED"] = $users->ZARAFA_INSTALLED; $GLOBALS["XAPIAN_PHP_INSTALLED"] = $users->XAPIAN_PHP_INSTALLED; $GLOBALS["AUDITD_INSTALLED"] = $users->APP_AUDITD_INSTALLED; $GLOBALS["VIRTUALBOX_INSTALLED"] = $users->VIRTUALBOX_INSTALLED; $GLOBALS["DRUPAL7_INSTALLED"] = $users->DRUPAL7_INSTALLED; $GLOBALS["CGROUPS_INSTALLED"] = $users->CGROUPS_INSTALLED; if ($GLOBALS["VERBOSE"]) { writelogs("DANSGUARDIAN_INSTALLED={$GLOBALS["DANSGUARDIAN_INSTALLED"]}", "MAIN", __FILE__, __LINE__); } $GLOBALS["EnableArticaWatchDog"] = GET_INFO_DAEMON("EnableArticaWatchDog"); if ($GLOBALS["VERBOSE"]) { if ($GLOBALS["POSTFIX_INSTALLED"]) { events("Postfix is installed..."); } } if ($GLOBALS["VERBOSE"]) { events("Nice=\"\", php5 {$GLOBALS["PHP5"]}"); } $GLOBALS["EnableInterfaceMailCampaigns"] = $sock->GET_INFO("EnableInterfaceMailCampaigns"); $GLOBALS["CLASS_SOCKETS"] = $sock; $GLOBALS["TOTAL_MEMORY_MB"] = $unix->TOTAL_MEMORY_MB(); if (!$GLOBALS["KAV4PROXY_INSTALLED"]) { if (is_file("/etc/artica-postfix/KASPERSKY_WEB_APPLIANCE")) { $GLOBALS["KAV4PROXY_INSTALLED"] = true; } } $sock = null; $unix = null; $users = null; }
function build() { $users = new usersMenus(); $sock = new sockets(); $unix = new unix(); $SystemLoadNotif = $sock->GET_INFO("SystemLoadNotif"); if (!is_numeric($SystemLoadNotif)) { $SystemLoadNotif = 0; } $EnableSyslogDB = $sock->GET_INFO("EnableSyslogDB"); if (!is_numeric($EnableSyslogDB)) { $EnableSyslogDB = 0; } $MySQLSyslogType = $sock->GET_INFO("MySQLSyslogType"); if (!is_numeric($MySQLSyslogType)) { $MySQLSyslogType = 1; } $SquidPerformance = intval($sock->GET_INFO("SquidPerformance")); $EnableIntelCeleron = intval(@file_get_contents("/etc/artica-postfix/settings/Daemons/EnableIntelCeleron")); $python = $unix->find_program("python"); $nice = $unix->EXEC_NICE(); $ps = $unix->find_program("ps"); $sort = $unix->find_program("sort"); $head = $unix->find_program("head"); $echo = $unix->find_program("echo"); $date = $unix->find_program("date"); $mkdir = $unix->find_program("mkdir"); $php5 = $unix->LOCATE_PHP5_BIN(); $ZarafaDedicateMySQLServer = $sock->GET_INFO("ZarafaDedicateMySQLServer"); if (!is_numeric($ZarafaDedicateMySQLServer)) { $ZarafaDedicateMySQLServer = 0; } build_progress_restart("{reconfiguring}", 22); $ini = new Bs_IniHandler(); $ini->loadFile('/etc/artica-postfix/smtpnotif.conf'); if (!is_numeric($ini->_params["SMTP"]["EnableNotifs"])) { $ini->_params["SMTP"]["EnableNotifs"] = 0; } if (!is_numeric($ini->_params["SMTP"]["tls_enabled"])) { $ini->_params["SMTP"]["tls_enabled"] = 0; } $smtp_server = trim($ini->_params["SMTP"]['smtp_server_name']); $smtp_server_port = $ini->_params["SMTP"]['smtp_server_port']; $smtp_dest = $ini->_params["SMTP"]['smtp_dest']; $smtp_sender = $ini->_params["SMTP"]['smtp_sender']; $smtp_auth_user = $ini->_params["SMTP"]['smtp_auth_user']; $smtp_auth_passwd = $ini->_params["SMTP"]['smtp_auth_passwd']; $tls_enabled = $ini->_params["SMTP"]["tls_enabled"]; $recipientsZ = explode("\n", "/etc/artica-postfix/settings/Daemons/SmtpNotificationConfigCC"); $recipients = array(); while (list($index, $to) = each($recipientsZ)) { if (trim($to) == null) { continue; } $recipients[] = $to; } if ($smtp_server == null) { $ini->_params["SMTP"]["EnableNotifs"] = 0; } if ($smtp_dest == null) { if (count($recipients) == 0) { $ini->_params["SMTP"]["EnableNotifs"] = 0; } } if (!is_numeric($smtp_server_port)) { $smtp_server_port = 25; } $EnableNotifs = $ini->_params["SMTP"]["EnableNotifs"]; $monit_not_on = 'instance,action'; $f[] = 'set daemon 60 with start delay 5'; $f[] = 'set idfile /var/run/monit/monit.id'; $cpunum = $unix->CPU_NUMBER(); $normal = $cpunum * 2 + 1; $normal2 = $cpunum * 2; $busy = $cpunum * 4; build_progress_restart("{reconfiguring}", 23); $EnableMONITSmtpNotif = $sock->GET_INFO("EnableMONITSmtpNotif"); if (!is_numeric($EnableMONITSmtpNotif)) { $EnableMONITSmtpNotif = 1; } $MonitCPUUsage = intval($sock->GET_INFO("MonitCPUUsage")); $MonitCPUUsageCycles = intval($sock->GET_INFO("MonitCPUUsageCycles")); $MonitMemUsage = intval($sock->GET_INFO("MonitMemUsage")); $MonitMemUsageCycles = intval($sock->GET_INFO("MonitMemUsageCycles")); $MonitReportLoadVG1mn = intval($sock->GET_INFO("MonitReportLoadVG1mn")); $MonitReportLoadVG1mnCycles = intval($sock->GET_INFO("MonitReportLoadVG1mnCycles")); if ($MonitReportLoadVG1mnCycles == 0) { $MonitReportLoadVG1mnCycles = 5; } $MonitReportLoadVG5mn = intval($sock->GET_INFO("MonitReportLoadVG5mn")); $MonitReportLoadVG5mnCycles = intval($sock->GET_INFO("MonitReportLoadVG5mnCycles")); if ($MonitReportLoadVG5mnCycles == 0) { $MonitReportLoadVG5mnCycles = 15; } $MonitReportLoadVG15mn = intval($sock->GET_INFO("MonitReportLoadVG15mn")); $MonitReportLoadVG15mnCycles = intval($sock->GET_INFO("MonitReportLoadVG15mnCycles")); if ($MonitReportLoadVG15mnCycles == 0) { $MonitReportLoadVG15mnCycles = 60; } $MonitMemPurgeCache = intval($sock->GET_INFO("MonitMemPurgeCache")); $MonitMemPurgeCacheCycles = intval($sock->GET_INFO("MonitMemPurgeCacheCycles")); if ($MonitMemPurgeCache == 0) { $MonitMemPurgeCache = 70; } if ($MonitMemPurgeCacheCycles == 0) { $MonitMemPurgeCacheCycles = 5; } if ($MonitMemUsageCycles == 0) { $MonitMemUsageCycles = 5; } if ($MonitCPUUsageCycles == 0) { $MonitCPUUsageCycles = 15; } if ($MonitCPUUsage > 0) { if ($MonitCPUUsage < 50) { $MonitCPUUsage = 90; } } if ($MonitMemUsage > 0) { if ($MonitMemUsage < 50) { $MonitMemUsage = 90; } } build_progress_restart("{reconfiguring}", 24); $rmbin = $unix->find_program("rm"); $echo = $unix->find_program("echo"); $SQUIDEnable = $sock->GET_INFO("SQUIDEnable"); if (!is_numeric($SQUIDEnable)) { $SQUIDEnable = 1; } $f[] = 'set logfile syslog facility log_daemon'; $f[] = 'set statefile /var/run/monit/monit.state'; $f[] = ''; if ($EnableNotifs == 1) { if ($EnableMONITSmtpNotif == 1) { $f[] = "set mailserver {$smtp_server} PORT {$smtp_server_port}"; if (strlen($smtp_auth_user) > 0) { $f[] = "\tUSERNAME \"{$smtp_auth_user}\" PASSWORD \"{$smtp_auth_passwd}\""; } if ($tls_enabled == 1) { $f[] = "\tusing TLSV1"; } $f[] = "\tset eventqueue"; $f[] = "\tbasedir /var/monit"; $f[] = "\tslots 100"; $f[] = "\tset mail-format {"; $f[] = "\t\tfrom: {$smtp_sender}"; $f[] = "\t\tsubject: Artica service monitor: \$SERVICE \$EVENT"; $f[] = "\t\tmessage: Artica service monitor \$ACTION \$SERVICE at \$DATE on \$HOST: \$DESCRIPTION"; $f[] = "\t}"; $f[] = "set alert {$smtp_dest} but not on {{$monit_not_on}}"; if ($recipients > 0) { while (list($index, $to) = each($recipientsZ)) { $f[] = "set alert {$to} but not on {{$monit_not_on}}"; } } } } build_progress_restart("{reconfiguring}", 25); $allips = $unix->NETWORK_ALL_INTERFACES(true); $f[] = "set httpd port 2874 and use address 127.0.0.1"; $f[] = "\tallow 127.0.0.1"; while (list($tcpi, $to) = each($allips)) { $f[] = "\tallow {$tcpi}"; } $top = $unix->find_program("top"); $hostname = $unix->hostname_g(); $TSCR = array(); if ($MonitReportLoadVG1mn > 0) { $TSCR[] = "\tif loadavg (1min) > {$MonitReportLoadVG1mn} for {$MonitReportLoadVG1mnCycles} cycles then exec \"/bin/artica-system-alert.sh LOAD_1 {$MonitReportLoadVG1mn}\""; } if ($MonitReportLoadVG5mn > 0) { $TSCR[] = "\tif loadavg (5min) > {$MonitReportLoadVG5mn} for {$MonitReportLoadVG5mnCycles} cycles then exec \"/bin/artica-system-alert.sh LOAD_5 {$MonitReportLoadVG5mn}\""; } if ($MonitReportLoadVG15mn > 0) { $TSCR[] = "\tif loadavg (15min) > {$MonitReportLoadVG15mn} for {$MonitReportLoadVG15mnCycles} cycles then exec \"/bin/artica-system-alert.sh LOAD_15 {$MonitReportLoadVG15mn}\""; } if ($MonitCPUUsage > 0) { if ($MonitCPUUsage < 75) { $MonitCPUUsage = 75; } $TSCR[] = "\tif cpu usage(system) > {$MonitCPUUsage}% for {$MonitCPUUsageCycles} cycles then exec \"/bin/artica-system-alert.sh CPU_SYSTEM {$MonitCPUUsage}\""; $TSCR[] = "\tif cpu usage(user) > {$MonitCPUUsage}% for {$MonitCPUUsageCycles} cycles then exec \"/bin/artica-system-alert.sh CPU_USER {$MonitCPUUsage}\""; $TSCR[] = "\tif cpu usage(wait) > {$MonitCPUUsage}% for {$MonitCPUUsageCycles} cycles then exec \"/bin/artica-system-alert.sh CPU_WAIT {$MonitCPUUsage}\""; } if ($MonitMemUsage > 0) { if ($MonitMemUsage < 75) { $MonitMemUsage = 75; } $TSCR[] = "\tif memory > {$MonitMemUsage}% for {$MonitMemUsageCycles} cycles then exec \"/bin/artica-system-alert.sh MEM {$MonitMemUsage}\""; } if ($MonitMemPurgeCache > 5) { @chmod("/usr/share/artica-postfix/exec.kernel.purge.cache.php", 0755); $TSCR[] = "\tif memory > {$MonitMemPurgeCache}% for {$MonitMemPurgeCacheCycles} cycles then exec \"/usr/share/artica-postfix/exec.kernel.purge.cache.php\""; } if (count($TSCR) > 1) { $f[] = "check system " . $unix->hostname_g(); $f[] = @implode("\n", $TSCR); } $TSCR = array(); $SCRIPT = array(); $SCRIPT[] = "#!/bin/sh"; $SCRIPT[] = "CURRENT=`{$date} +%s`"; $SCRIPT[] = "DIR=\"/home/artica/system/perf-queue/\$CURRENT\""; $SCRIPT[] = "{$mkdir} -p \"\$DIR\""; $SCRIPT[] = "{$echo} \$CURRENT >\$DIR/time.txt"; $SCRIPT[] = "{$echo} \$1 >\$DIR/why.txt"; $SCRIPT[] = "{$echo} \$2 >\$DIR/why2.txt"; $iotop = $unix->find_program("iotop"); if (is_file($iotop)) { $SCRIPT[] = "{$iotop} -o -a -b -q -t -n 20 >\$DIR/iotop.txt || true"; } $SCRIPT[] = "{$nice} {$python} /usr/share/artica-postfix/bin/ps_mem.py >\$DIR/psmem.txt 2>&1"; $SCRIPT[] = "{$ps} --no-heading -eo user,pid,pcpu,args|{$sort} -grbk 3|{$head} -50 >\$DIR/TOP50-CPU.txt 2>&1"; $SCRIPT[] = "{$ps} --no-heading -eo user,pid,pmem,args|{$sort} -grbk 3|{$head} -50 >\$DIR/TOP50-MEM.txt 2>&1"; $SCRIPT[] = "{$ps} auxww >\$DIR/ALLPS.txt 2>&1"; $SCRIPT[] = ""; @file_put_contents("/bin/artica-system-alert.sh", @implode("\n", $SCRIPT)); @chmod("/bin/artica-system-alert.sh", 0755); $SCRIPT = array(); $f[] = ""; $f[] = "check host loopback with address 127.0.0.1"; $f[] = "\tif failed icmp type echo with timeout 1 seconds then exec \"/bin/loopbackfailed.sh\""; $f[] = ""; $loopbackfailed[] = "#!/bin/sh"; $loopbackfailed[] = "{$php5} /usr/share/artica-postfix/exec.virtuals-ip.php --loopback"; $loopbackfailed[] = ""; @file_put_contents("/bin/loopbackfailed.sh", @implode("\n", $loopbackfailed)); @chmod("/bin/loopbackfailed.sh", 0755); $loopbackfailed = array(); build_progress_restart("{reconfiguring}", 25); //******************************************************************************************************************** $f[] = "check file php.log with path /var/log/php.log"; $f[] = "\tif size > 100 MB then"; $f[] = "\t\texec \"/bin/clean-phplog.sh\""; $f[] = ""; $f[] = "check file usrphp.log with path /usr/share/artica-postfix/ressources/logs/php.log"; $f[] = " if size > 100 MB then"; $f[] = "\t\texec \"/bin/clean-phplog.sh\""; $f[] = ""; $f[] = "check file squid-logger-start.log with path /var/log/artica-postfix/squid-logger-start.log"; $f[] = "\tif size > 100 MB then"; $f[] = "\t\texec \"/bin/squid-logger-start.sh\""; $f[] = ""; build_progress_restart("{reconfiguring}", 26); $f[] = "include /etc/monit/conf.d/*"; @file_put_contents("/etc/monit/monitrc", @implode("\n", $f)); if ($GLOBALS["OUTPUT"]) { echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} /etc/monit/monitrc done...\n"; } $AA[] = "#!/bin/sh"; $AA[] = "{$echo} \"#\" >/var/log/artica-postfix/squid-logger-start.log"; $AA[] = ""; @file_put_contents("/bin/squid-logger-start.sh", @implode("\n", $AA)); @chmod("/bin/squid-logger-start.sh", 0755); $AA = array(); $AA[] = "#!/bin/sh"; $AA[] = "{$echo} \"#\" >/var/log/php.log"; $AA[] = ""; @file_put_contents("/bin/clean-phplog.sh", @implode("\n", $AA)); @chmod("/bin/clean-phplog.sh", 0755); $AA = array(); $monit = new monit(); $monit->save(); $INITD_PATH = $unix->SLAPD_INITD_PATH(); $SLAPD_PID_FILE = $unix->SLAPD_PID_PATH(); $squidbin = $unix->LOCATE_SQUID_BIN(); @unlink("/etc/monit/conf.d/APP_OPENLDAP.monitrc"); //******************************************************************************************************************** $f = array(); //******************************************************************************************************************** build_progress_restart("{reconfiguring}", 27); $f = array(); $f[] = "check process APP_FRAMEWORK"; $f[] = "with pidfile /var/run/lighttpd/framework.pid"; $f[] = "start program = \"/etc/init.d/artica-framework start --monit\""; $f[] = "stop program = \"/etc/init.d/artica-framework stop --monit\""; $f[] = "if 5 restarts within 5 cycles then timeout"; @file_put_contents("/etc/monit/conf.d/articaframework.monitrc", @implode("\n", $f)); $f = array(); //******************************************************************************************************************** $f = array(); @unlink("/etc/monit/conf.d/APP_OPENSSH.monitrc"); @unlink("/etc/monit/conf.d/APP_MYSQLD.monitrc"); //******************************************************************************************************************** $f = array(); build_progress_restart("{reconfiguring}", 28); $f[] = "check process APP_ARTICA_STATUS with pidfile /etc/artica-postfix/exec.status.php.pid"; $f[] = "\tstart program = \"/etc/init.d/artica-status start --monit\""; $f[] = "\tstop program = \"/etc/init.d/artica-status stop --monit\""; $f[] = "\tif 5 restarts within 5 cycles then timeout"; $f[] = ""; if ($GLOBALS["OUTPUT"]) { echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring Artica Status...\n"; } @file_put_contents("/etc/monit/conf.d/APP_ARTICASTATUS.monitrc", @implode("\n", $f)); //******************************************************************************************************************** $f = array(); $EnableInflux = 1; if ($SquidPerformance > 2) { $EnableInflux = 0; } $InfluxUseRemote = intval($sock->GET_INFO("InfluxUseRemote")); $EnableInfluxDB = intval($sock->GET_INFO("EnableInfluxDB")); if ($InfluxUseRemote == 1) { $EnableInfluxDB = 0; } if ($EnableIntelCeleron == 1) { $EnableInflux = 0; } if ($EnableInfluxDB == 0) { $EnableInflux = 0; } if (is_file("/etc/artica-postfix/STATS_APPLIANCE")) { $EnableInflux = 1; } build_progress_restart("{reconfiguring}", 29); @unlink("/etc/monit/conf.d/APP_INFLUXDB.monitrc"); @unlink("/etc/monit/conf.d/APP_POSTGRES.monitrc"); if (is_file("/usr/local/ArticaStats/bin/postgres")) { if ($EnableInflux == 1) { $InfluxRestartMem = intval(@file_get_contents("/etc/artica-postfix/settings/Daemons/InfluxRestartMem")); $f[] = "check process APP_POSTGRES with pidfile /home/ArticaStatsDB/postmaster.pid"; $f[] = "\tstart program = \"/etc/init.d/artica-postgres start --monit\""; $f[] = "\tstop program = \"/etc/init.d/artica-postgres --monit\""; $f[] = "\tif 5 restarts within 5 cycles then timeout"; if ($InfluxRestartMem > 50) { $f[] = "\tif totalmem > {$InfluxRestartMem} MB for 5 cycles then restart"; } $f[] = ""; if ($GLOBALS["OUTPUT"]) { echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring Artica Status...\n"; } @file_put_contents("/etc/monit/conf.d/APP_POSTGRES.monitrc", @implode("\n", $f)); //******************************************************************************************************************** } } $f = array(); @unlink("/etc/monit/conf.d/squid.monitrc"); @unlink("/etc/monit/conf.d/APP_SQUIDMAIN.monitrc"); // ******************************************************************************************************************** $f = array(); @unlink("/etc/monit/conf.d/APP_SQUIDDB.monitrc"); build_progress_restart("{reconfiguring} Proxy service", 30); if (is_dir("/opt/squidsql/data")) { if ($SQUIDEnable == 1) { $f = array(); $f[] = "check process APP_SQUID_DB with pidfile /var/run/squid-db.pid"; $f[] = "\tstart program = \"/etc/init.d/squid-db start --monit\""; $f[] = "\tstop program = \"/etc/init.d/squid-db stop --monit\""; $f[] = "\tif failed unixsocket /var/run/mysqld/squid-db.sock then restart"; $f[] = "\tif 5 restarts within 5 cycles then timeout"; $f[] = ""; if ($GLOBALS["OUTPUT"]) { echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring Squid MySQL DB...\n"; } @file_put_contents("/etc/monit/conf.d/APP_SQUIDDB.monitrc", @implode("\n", $f)); } } // ******************************************************************************************************************** $f = array(); build_progress_restart("{reconfiguring} Dnsmasq", 31); @unlink("/etc/monit/conf.d/APP_DNSMASQ.monitrc"); if ($users->dnsmasq_installed) { $enabled = $sock->dnsmasq_enabled(); if ($enabled == 1) { $f[] = "check process APP_DNSMASQ with pidfile /var/run/dnsmasq.pid"; $f[] = "\tstart program = \"/etc/init.d/dnsmasq start --monit\""; $f[] = "\tstop program = \"/etc/init.d/dnsmasq stop --monit\""; $f[] = "\tif 5 restarts within 5 cycles then timeout"; $f[] = ""; if ($GLOBALS["OUTPUT"]) { echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring DnsMASQ...\n"; } @file_put_contents("/etc/monit/conf.d/APP_DNSMASQ.monitrc", @implode("\n", $f)); } } // ******************************************************************************************************************** $f = array(); build_progress_restart("{reconfiguring} Proftpd", 31); @unlink("/etc/monit/conf.d/APP_PROFTPD.monitrc"); $proftpd = $unix->find_program("proftpd"); if (is_file($proftpd)) { $enabled = intval(@file_get_contents("/etc/artica-postfix/settings/Daemons/EnableProFTPD")); if ($enabled == 1) { $f[] = "check process APP_PROFTPD with pidfile /var/run/proftpd.pid"; $f[] = "\tstart program = \"/etc/init.d/proftpd start --monit\""; $f[] = "\tstop program = \"/etc/init.d/proftpd stop --monit\""; $f[] = "\tif 5 restarts within 5 cycles then timeout"; $f[] = ""; if ($GLOBALS["OUTPUT"]) { echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring DnsMASQ...\n"; } @file_put_contents("/etc/monit/conf.d/APP_PROFTPD.monitrc", @implode("\n", $f)); } } // ******************************************************************************************************************** $f = array(); build_progress_restart("{reconfiguring} Bandwidthd", 31); @unlink("/etc/monit/conf.d/APP_BANDWIDTHD.monitrc"); if (is_file("/usr/bandwidthd/bandwidthd")) { $enabled = $sock->Bandwidthd_enabled(); if ($enabled == 1) { $f[] = "check process APP_BANDWIDTHD with pidfile /var/run/bandwidthd.pid"; $f[] = "\tstart program = \"/etc/init.d/bandwidthd start --monit\""; $f[] = "\tstop program = \"/etc/init.d/bandwidthd stop --monit\""; $f[] = "\tif 5 restarts within 5 cycles then timeout"; $f[] = ""; if ($GLOBALS["OUTPUT"]) { echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring DnsMASQ...\n"; } @file_put_contents("/etc/monit/conf.d/APP_BANDWIDTHD.monitrc", @implode("\n", $f)); } } // ******************************************************************************************************************** $f = array(); build_progress_restart("{reconfiguring} rsyslog", 32); $rsyslogd = $unix->find_program("rsyslogd"); @unlink("/etc/monit/conf.d/APP_RSYSLOG.monitrc"); if (is_file($rsyslogd)) { $SCRIPT = array(); $SCRIPT[] = "#!/bin/sh"; $SCRIPT[] = "{$php5} /usr/share/artica-postfix/exec.watchdog.rsyslogd.php --start"; $SCRIPT[] = ""; @file_put_contents("/bin/artica-rsyslog-start.sh", @implode("\n", $SCRIPT)); @chmod("/bin/artica-rsyslog-start.sh", 0755); $SCRIPT = array(); $SCRIPT[] = "#!/bin/sh"; $SCRIPT[] = "{$php5} /usr/share/artica-postfix/exec.watchdog.rsyslogd.php --stop"; $SCRIPT[] = ""; @file_put_contents("/bin/artica-rsyslog-stop.sh", @implode("\n", $SCRIPT)); @chmod("/bin/artica-rsyslog-stop.sh", 0755); $SCRIPT = array(); $f[] = "check process APP_RSYSLOG with pidfile /var/run/rsyslogd.pid"; $f[] = "\tstart program = \"/bin/artica-rsyslog-start.sh\""; $f[] = "\tstop program = \"/bin/artica-rsyslog-stop.sh\""; $f[] = "\tif 5 restarts within 5 cycles then timeout"; $f[] = ""; if ($GLOBALS["OUTPUT"]) { echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring rsyslogd...\n"; } @file_put_contents("/etc/monit/conf.d/APP_RSYSLOG.monitrc", @implode("\n", $f)); } // ******************************************************************************************************************** build_progress_restart("{reconfiguring} Squid-tail", 32); $APP_ARTICA_SQUID_TAIL = $unix->SQUID_TAIL_ENABLED(); @unlink("/etc/monit/conf.d/APP_ARTICA_SQUID_TAIL.monitrc"); if ($APP_ARTICA_SQUID_TAIL == 1) { $f = array(); $f[] = "check process APP_ARTICA_SQUID_TAIL with pidfile /etc/artica-postfix/pids/exec.logfile_daemon.php.pid"; $f[] = "\tstart program = \"/etc/init.d/squid-tail start\""; $f[] = "\tstop program = \"/etc/init.d/squid-tail stop\""; $f[] = "\tif cpu usage > 95% for 5 cycles then restart"; $f[] = "\tif totalmem > 550.0 MB for 5 cycles then restart"; $f[] = "\tif 5 restarts within 5 cycles then timeout"; $f[] = ""; if ($GLOBALS["OUTPUT"]) { echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring squid-tail...\n"; } @file_put_contents("/etc/monit/conf.d/APP_ARTICA_SQUID_TAIL.monitrc", @implode("\n", $f)); } // ******************************************************************************************************************** build_progress_restart("{reconfiguring} Squid-Proxy", 32); $APP_SQUID = $unix->SQUID_ENABLED(); @unlink("/etc/monit/conf.d/APP_SQUID.monitrc"); if ($APP_SQUID == 1) { $MonitConfig = unserialize(base64_decode(@file_get_contents("/etc/artica-postfix/settings/SquidWatchdogMonitConfig"))); if (!isset($MonitConfig["watchdog"])) { $MonitConfig["watchdog"] = 1; } if (!is_numeric($MonitConfig["watchdog"])) { $MonitConfig["watchdog"] = 1; } $f = array(); if ($MonitConfig["watchdog"] == 1) { $MonitSquidMaxRestartMem = intval(@file_get_contents("/etc/artica-postfix/settings/Daemons/MonitSquidMaxRestartMem")); $MonitSquidMaxCPU = intval(@file_get_contents("/etc/artica-postfix/settings/Daemons/MonitSquidMaxCPU")); $f[] = "check process APP_SQUID with pidfile /var/run/squid/squid.pid"; $f[] = "\tstart program = \"/etc/init.d/squid start --monit\""; $f[] = "\tstop program = \"/etc/init.d/squid stop --monit\""; if ($MonitSquidMaxCPU > 0) { $f[] = "\tif cpu usage > {$MonitSquidMaxCPU}% for 5 cycles then restart"; } if ($MonitSquidMaxRestartMem > 0) { $f[] = "\tif totalmem > {$MonitSquidMaxRestartMem}.0 MB for 5 cycles then restart"; } $f[] = "\tif 5 restarts within 5 cycles then timeout"; $f[] = ""; if ($GLOBALS["OUTPUT"]) { echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring squid...\n"; } @file_put_contents("/etc/monit/conf.d/APP_SQUID.monitrc", @implode("\n", $f)); } } // ******************************************************************************************************************** build_progress_restart("{reconfiguring} OpenLDAP", 32); $EnableOpenLDAP = intval(@file_get_contents("/etc/artica-postfix/settings/Daemons/EnableOpenLDAP")); $SLAPD_PID_FILE = $unix->SLAPD_PID_PATH(); @unlink("/etc/monit/conf.d/APP_SLAPD.monitrc"); if ($EnableOpenLDAP == 1) { if ($EnableIntelCeleron == 0) { $f = array(); $f[] = "check process APP_SLAPD with pidfile {$SLAPD_PID_FILE}"; $f[] = "\tstart program = \"/etc/init.d/slapd start --force --monit\""; $f[] = "\tstop program = \"/etc/init.d/slapd stop --force\""; $f[] = "\tif cpu usage > 95% for 5 cycles then restart"; $f[] = "\tif totalmem > 550.0 MB for 5 cycles then restart"; $f[] = "\tif failed unixsocket /var/run/slapd/slapd.sock then restart"; $f[] = "\tif 5 restarts within 5 cycles then timeout"; $f[] = ""; if ($GLOBALS["OUTPUT"]) { echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring slapd...\n"; } @file_put_contents("/etc/monit/conf.d/APP_SLAPD.monitrc", @implode("\n", $f)); } } // ******************************************************************************************************************** $f = array(); build_progress_restart("{reconfiguring} Suricata", 32); $EnableSuricata = intval(@file_get_contents("/etc/artica-postfix/settings/Daemons/EnableSuricata")); @unlink("/etc/monit/conf.d/APP_SURICATA.monitrc"); @unlink("/etc/monit/conf.d/APP_SURICATA_TAIL.monitrc"); $suricata = $unix->find_program("suricata"); if (is_file($suricata)) { if ($EnableSuricata == 1) { $f[] = "check process APP_SURICATA with pidfile /var/run/suricata/suricata.pid"; $f[] = "\tstart program = \"/etc/init.d/suricata start --monit\""; $f[] = "\tstop program = \"/etc/init.d/suricata stop --monit\""; $f[] = "\tif cpu usage > 95% for 5 cycles then restart"; $f[] = "\tif 5 restarts within 5 cycles then timeout"; $f[] = ""; if ($GLOBALS["OUTPUT"]) { echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring Suricata...\n"; } @file_put_contents("/etc/monit/conf.d/APP_SURICATA.monitrc", @implode("\n", $f)); $f = array(); $f[] = "check process APP_SURICATA_TAIL with pidfile /etc/artica-postfix/exec.suricata-tail.php.pid"; $f[] = "\tstart program = \"/etc/init.d/suricata-tail start --monit\""; $f[] = "\tstop program = \"/etc/init.d/suricata-tail stop --monit\""; $f[] = "\tif 5 restarts within 5 cycles then timeout"; $f[] = ""; if ($GLOBALS["OUTPUT"]) { echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring Suricata tail...\n"; } @file_put_contents("/etc/monit/conf.d/APP_SURICATA_TAIL.monitrc", @implode("\n", $f)); } } // ******************************************************************************************************************** $f = array(); build_progress_restart("{reconfiguring}", 32); $winbind = $unix->find_program("winbindd"); if (is_file("/etc/monit/conf.d/winbindd.monitrc")) { @unlink("/etc/monit/conf.d/winbindd.monitrc"); } @unlink("/etc/monit/conf.d/winbind.monitrc"); $EnableKerbAuth = intval(@file_get_contents("/etc/artica-postfix/settings/Daemons/EnableKerbAuth")); if (is_file($winbind)) { if ($EnableKerbAuth == 1) { $f[] = "check process winbindd with pidfile /var/run/samba/winbindd.pid"; $f[] = "\tstart program = \"/etc/init.d/winbind start\""; $f[] = "\tstop program = \"/etc/init.d/winbind stop\""; $f[] = "\tif 5 restarts within 5 cycles then timeout"; $f[] = ""; if ($GLOBALS["OUTPUT"]) { echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring winbindd...\n"; } @file_put_contents("/etc/monit/conf.d/winbind.monitrc", @implode("\n", $f)); } } // ******************************************************************************************************************** $f = array(); build_progress_restart("{reconfiguring}", 33); @unlink("/etc/monit/conf.d/APP_CICAP.monitrc"); if ($users->C_ICAP_INSTALLED) { if ($SQUIDEnable == 1) { $CicapEnabled = $sock->GET_INFO("CicapEnabled"); if (!is_numeric($CicapEnabled)) { $CicapEnabled = 0; } if ($CicapEnabled == 1) { $f[] = "check process APP_C_ICAP with pidfile /var/run/c-icap/c-icap.pid"; $f[] = "\tstart program = \"/etc/init.d/artica-postfix start cicap\""; $f[] = "\tstop program = \"/etc/init.d/artica-postfix stop cicap\""; $f[] = "\tif 5 restarts within 5 cycles then timeout"; $f[] = ""; if ($GLOBALS["OUTPUT"]) { echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring C-ICAP...\n"; } @file_put_contents("/etc/monit/conf.d/APP_CICAP.monitrc", @implode("\n", $f)); } } } // ******************************************************************************************************************** build_progress_restart("{reconfiguring}", 34); @unlink("/etc/monit/conf.d/APP_SYSLOGDB.monitrc"); if ($EnableSyslogDB == 1) { if ($MySQLSyslogType == 1) { $f = array(); $f[] = "check process APP_SYSLOG_DB with pidfile /var/run/syslogdb.pid"; $f[] = "\tstart program = \"/etc/init.d/syslog-db start --monit\""; $f[] = "\tstop program = \"/etc/init.d/syslog-db stop --monit\""; $f[] = "\tif failed unixsocket /var/run/syslogdb.sock then restart"; $f[] = "\tif 5 restarts within 5 cycles then timeout"; $f[] = ""; if ($GLOBALS["OUTPUT"]) { echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring syslogd...\n"; } @file_put_contents("/etc/monit/conf.d/APP_SYSLOGDB.monitrc", @implode("\n", $f)); $f = array(); } } //******************************************************************************************************************** $f = array(); @unlink("/etc/monit/conf.d/cron.monitrc"); if (is_file("/etc/monit/templates/rootbin")) { $f[] = "check process crond with pidfile /var/run/crond.pid"; $f[] = " group system"; $f[] = " group crond"; $f[] = " start program = \"/etc/init.d/cron start\""; $f[] = " stop program = \"/etc/init.d/cron stop\""; $f[] = " if 5 restarts with 5 cycles then timeout"; $f[] = " depend cron_bin"; $f[] = " depend cron_rc"; $f[] = " depend cron_spool"; $f[] = ""; $f[] = " check file cron_bin with path /usr/sbin/cron"; $f[] = " group crond"; $f[] = " include /etc/monit/templates/rootbin"; $f[] = ""; $f[] = " check file cron_rc with path \"/etc/init.d/cron\""; $f[] = " group crond"; $f[] = " include /etc/monit/templates/rootbin"; $f[] = ""; $f[] = " check directory cron_spool with path /var/spool/cron/crontabs"; $f[] = " group crond"; $f[] = " if failed permission 1730 then unmonitor"; $f[] = " if failed uid root then unmonitor"; $f[] = " if failed gid crontab then unmonitor"; if ($GLOBALS["OUTPUT"]) { echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring cron...\n"; } @file_put_contents("/etc/monit/conf.d/cron.monitrc", @implode("\n", $f)); $f = array(); } @unlink("/etc/monit/conf.d/APP_ZARAFASERVER.monitrc"); @unlink("/etc/monit/conf.d/APP_ZARAFAGATEWAY.monitrc"); @unlink("/etc/monit/conf.d/APP_ZARAFAAPACHE.monitrc"); @unlink("/etc/monit/conf.d/APP_ZARAFAWEB.monitrc"); @unlink("/etc/monit/conf.d/APP_ZARAFASPOOLER.monitrc"); @unlink("/etc/monit/conf.d/APP_ZARAFADB.monitrc"); build_progress_restart("{reconfiguring}", 35); if (is_file($unix->find_program("zarafa-server"))) { $ZarafaApacheEnable = $sock->GET_INFO("ZarafaApacheEnable"); if (!is_numeric($ZarafaApacheEnable)) { $ZarafaApacheEnable = 1; } $ZarafaApachePort = $sock->GET_INFO("ZarafaApachePort"); if (!is_numeric($ZarafaApachePort)) { $ZarafaApachePort = 9010; } if ($ZarafaDedicateMySQLServer == 1) { $f = array(); $f[] = "check process APP_ZARAFA_DB with pidfile /var/run/zarafa-db.pid"; $f[] = "\tstart program = \"/etc/init.d/zarafa-db start --monit\""; $f[] = "\tstop program = \"/etc/init.d/zarafa-db stop --monit\""; $f[] = "\tif failed unixsocket /var/run/mysqld/zarafa-db.sock then restart"; $f[] = "\tif 5 restarts within 5 cycles then timeout"; $f[] = ""; if ($GLOBALS["OUTPUT"]) { echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring Zarafa Database...\n"; } @file_put_contents("/etc/monit/conf.d/APP_ZARAFADB.monitrc", @implode("\n", $f)); } $f = array(); $f[] = "check process APP_ZARAFA_SERVER with pidfile /var/run/zarafa-server.pid"; $f[] = "\tstart program = \"/etc/init.d/zarafa-server start --monit\""; $f[] = "\tstop program = \"/etc/init.d/zarafa-server stop --monit\""; $f[] = "\tif failed unixsocket /var/run/zarafa then restart"; $f[] = "\tif 5 restarts within 5 cycles then timeout"; $f[] = ""; if ($GLOBALS["OUTPUT"]) { echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring Zarafa Server...\n"; } @file_put_contents("/etc/monit/conf.d/APP_ZARAFASERVER.monitrc", @implode("\n", $f)); $f = array(); $f[] = "check process APP_ZARAFA_SPOOLER with pidfile /var/run/zarafa-spooler.pid"; $f[] = "\tstart program = \"/etc/init.d/zarafa-spooler start --monit\""; $f[] = "\tstop program = \"/etc/init.d/zarafa-spooler stop --monit\""; $f[] = "\tif 5 restarts within 5 cycles then timeout"; $f[] = ""; if ($GLOBALS["OUTPUT"]) { echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring Zarafa Spooler...\n"; } @file_put_contents("/etc/monit/conf.d/APP_ZARAFASPOOLER.monitrc", @implode("\n", $f)); $f = array(); $f[] = "check process APP_ZARAFA_GATEWAY with pidfile /var/run/zarafa-gateway.pid"; $f[] = "\tstart program = \"/etc/init.d/zarafa-gateway start --monit\""; $f[] = "\tstop program = \"/etc/init.d/zarafa-gateway stop --monit\""; $f[] = "\tif 5 restarts within 5 cycles then timeout"; $f[] = ""; if ($GLOBALS["OUTPUT"]) { echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring Zarafa Gateway...\n"; } @file_put_contents("/etc/monit/conf.d/APP_ZARAFAGATEWAY.monitrc", @implode("\n", $f)); } //******************************************************************************************************************** build_progress_restart("{reconfiguring}", 36); $EnableClamavDaemon = $sock->GET_INFO("EnableClamavDaemon"); $EnableClamavDaemonForced = $sock->GET_INFO("EnableClamavDaemonForced"); $CicapEnabled = $sock->GET_INFO("CicapEnabled"); $SQUIDEnable = $sock->GET_INFO("SQUIDEnable"); if (!is_numeric($EnableClamavDaemon)) { $EnableClamavDaemon = 0; } if (!is_numeric($EnableClamavDaemonForced)) { $EnableClamavDaemonForced = 0; } if (!is_numeric($SQUIDEnable)) { $SQUIDEnable = 1; } if (!is_numeric($CicapEnabled)) { $CicapEnabled = 0; } if ($SQUIDEnable == 1) { if ($CicapEnabled == 1) { $EnableClamavDaemon = 1; } } if ($EnableClamavDaemonForced == 1) { $EnableClamavDaemon = 1; } //******************************************************************************************************************** build_progress_restart("{reconfiguring}", 37); @unlink("/etc/monit/conf.d/APP_CLAMAV.monitrc"); $MasterBin = $unix->find_program("clamd"); if (is_file($MasterBin)) { if ($EnableClamavDaemon == 1) { $f = array(); $f[] = "check process APP_CLAMAV"; $f[] = "with pidfile /var/run/clamav/clamd.pid"; $f[] = "start program = \"/etc/init.d/clamav-daemon start --monit\""; $f[] = "stop program = \"/etc/init.d/clamav-daemon stop --monit\""; $f[] = "if 5 restarts within 5 cycles then timeout"; if ($GLOBALS["OUTPUT"]) { echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring Clamd service...\n"; } @file_put_contents("/etc/monit/conf.d/APP_CLAMAV.monitrc", @implode("\n", $f)); $f = array(); } } //******************************************************************************************************************** @unlink("/etc/monit/conf.d/ufdb.monitrc"); @unlink("/etc/monit/conf.d/ufdbweb.monitrc"); $ufdbbin = $unix->find_program("ufdbguardd"); build_progress_restart("{reconfiguring}", 38); if (is_file($ufdbbin)) { $EnableUfdbGuard = intval($sock->EnableUfdbGuard()); $UseRemoteUfdbguardService = $sock->GET_INFO('UseRemoteUfdbguardService'); $EnableSquidGuardHTTPService = $sock->GET_INFO("EnableSquidGuardHTTPService"); $SquidPerformance = intval($sock->GET_INFO("SquidPerformance")); $EnableWebProxyStatsAppliance = $sock->GET_INFO("EnableWebProxyStatsAppliance"); $SquidGuardApachePort = $sock->GET_INFO("SquidGuardApachePort"); $SquidGuardApacheSSLPort = $sock->GET_INFO("SquidGuardApacheSSLPort"); if (!is_numeric($UseRemoteUfdbguardService)) { $UseRemoteUfdbguardService = 0; } if (!is_numeric($EnableUfdbGuard)) { $EnableUfdbGuard = 0; } if (!is_numeric($EnableSquidGuardHTTPService)) { $EnableSquidGuardHTTPService = 1; } if (!is_numeric($EnableWebProxyStatsAppliance)) { $EnableWebProxyStatsAppliance = 0; } if ($EnableUfdbGuard == 0) { $EnableSquidGuardHTTPService = 0; } if ($EnableWebProxyStatsAppliance == 1) { $EnableSquidGuardHTTPService = 1; } if (!is_numeric($SquidGuardApachePort)) { $SquidGuardApachePort = "9020"; } if (!is_numeric($SquidGuardApacheSSLPort)) { $SquidGuardApacheSSLPort = 9025; } if ($SquidPerformance > 2) { $EnableSquidGuardHTTPService = 0; } if ($SQUIDEnable == 1) { if ($EnableSquidGuardHTTPService == 1) { $f = array(); $f[] = "check process APP_SQUIDGUARD_HTTP"; $f[] = "with pidfile /var/run/lighttpd/squidguard-lighttpd.pid"; $f[] = "start program = \"/etc/init.d/squidguard-http start --monit\""; $f[] = "stop program = \"/etc/init.d/squidguard-http stop --monit\""; $f[] = "if failed host 127.0.0.1 port {$SquidGuardApachePort} then restart"; $f[] = "if 5 restarts within 5 cycles then timeout"; if ($GLOBALS["OUTPUT"]) { echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring Web filtering HTTP service...\n"; } @file_put_contents("/etc/monit/conf.d/ufdbweb.monitrc", @implode("\n", $f)); } } } //******************************************************************************************************************** $EnableArticaFrontEndToNGninx = $sock->GET_INFO("EnableArticaFrontEndToNGninx"); $EnableArticaFrontEndToApache = $sock->GET_INFO("EnableArticaFrontEndToApache"); if (!is_numeric($EnableArticaFrontEndToNGninx)) { $EnableArticaFrontEndToNGninx = 0; } if (!is_numeric($EnableArticaFrontEndToApache)) { $EnableArticaFrontEndToApache = 0; } $EnableNginx = $sock->GET_INFO("EnableNginx"); $EnableFreeWeb = $sock->GET_INFO("EnableFreeWeb"); if (!is_numeric($EnableFreeWeb)) { $EnableFreeWeb = 0; } if (!is_numeric($EnableNginx)) { $EnableNginx = 1; } if ($EnableNginx == 0) { $EnableArticaFrontEndToNGninx = 0; } $pid = null; build_progress_restart("{reconfiguring}", 39); @unlink("/etc/monit/conf.d/APP_LIGHTTPD.monitrc"); if ($EnableArticaFrontEndToNGninx == 0) { $pid = "/var/run/lighttpd/lighttpd.pid"; if ($EnableArticaFrontEndToApache == 1) { $pid = "/var/run/artica-apache/apache.pid"; } $f = array(); $f[] = "check process APP_ARTICAWEBCONSOLE with pidfile {$pid}"; $f[] = "\tstart program = \"/etc/init.d/artica-webconsole start --monit\""; $f[] = "\tstop program = \"/etc/init.d/artica-webconsole stop --monit\""; $f[] = "\tif 5 restarts within 5 cycles then timeout"; $f[] = ""; if ($GLOBALS["OUTPUT"]) { echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring Artica Web Console...\n"; } @file_put_contents("/etc/monit/conf.d/APP_LIGHTTPD.monitrc", @implode("\n", $f)); } //******************************************************************************************************************** @unlink("/etc/monit/conf.d/APP_NGINX.monitrc"); $nginx = $unix->find_program("nginx"); if (is_file($nginx)) { if ($EnableNginx == 1) { $f = array(); $f[] = "check process APP_NGINX with pidfile /var/run/nginx.pid"; $f[] = "\tstart program = \"/etc/init.d/nginx start --monit\""; $f[] = "\tstop program = \"/etc/init.d/nginx stop --monit\""; $f[] = "\tif 5 restarts within 5 cycles then timeout"; $f[] = ""; if ($GLOBALS["OUTPUT"]) { echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring NgINX...\n"; } @file_put_contents("/etc/monit/conf.d/APP_NGINX.monitrc", @implode("\n", $f)); } } //******************************************************************************************************************** build_progress_restart("{reconfiguring}", 40); $f = array(); if (is_file("/etc/init.d/sysklogd")) { $f[] = "check process APP_SYSLOGD with pidfile /var/run/syslogd.pid"; $f[] = "\tstart program = \"/etc/init.d/sysklogd start --monit\""; $f[] = "\tstop program = \"/etc/init.d/sysklogd stop --monit\""; $f[] = "\tif 5 restarts within 5 cycles then timeout"; $f[] = "\tcheck file syslogd_file with path /var/log/syslog"; $f[] = "\tif timestamp > 10 minutes then restart"; $f[] = ""; if ($GLOBALS["OUTPUT"]) { echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring sysklogd...\n"; } @file_put_contents("/etc/monit/conf.d/APP_SYSKLOGD.monitrc", @implode("\n", $f)); } //******************************************************************************************************************** build_progress_restart("{reconfiguring}", 41); $binpath = $unix->DHCPD_BIN_PATH(); @unlink("/etc/monit/conf.d/APP_DHCPD.monitrc"); $f = array(); if (is_file($binpath)) { $EnableDHCPServer = $sock->GET_INFO("EnableDHCPServer"); if (!is_numeric($EnableDHCPServer)) { $EnableDHCPServer = 0; } if ($EnableDHCPServer == 1) { $f[] = "check process APP_DHCP with pidfile /var/run/dhcpd.pid"; $f[] = "\tstart program = \"/etc/init.d/isc-dhcp-server start --monit\""; $f[] = "\tstop program = \"/etc/init.d/isc-dhcp-server stop --monit\""; $f[] = "\tif 5 restarts within 5 cycles then timeout"; $f[] = ""; if ($GLOBALS["OUTPUT"]) { echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring DHCP Service...\n"; } @file_put_contents("/etc/monit/conf.d/APP_DHCPD.monitrc", @implode("\n", $f)); } } //******************************************************************************************************************** $binpath = $unix->find_program("rdpproxy"); build_progress_restart("{reconfiguring}", 42); @unlink("/etc/monit/conf.d/APP_RDPPROXY.monitrc"); $f = array(); if (is_file($binpath)) { $EnableRDPProxy = $sock->GET_INFO("EnableRDPProxy"); if (!is_numeric($EnableRDPProxy)) { $EnableRDPProxy = 0; } if ($EnableRDPProxy == 1) { $f[] = "check process APP_RDPPROXY with pidfile /var/run/redemption/rdpproxy.pid"; $f[] = "\tstart program = \"/etc/init.d/rdpproxy start --monit\""; $f[] = "\tstop program = \"/etc/init.d/rdpproxy stop --monit\""; $f[] = "\tif 5 restarts within 5 cycles then timeout"; $f[] = ""; if ($GLOBALS["OUTPUT"]) { echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring RDP Proxy...\n"; } @file_put_contents("/etc/monit/conf.d/APP_RDPPROXY.monitrc", @implode("\n", $f)); } } //******************************************************************************************************************** build_progress_restart("{reconfiguring}", 43); @unlink("/etc/monit/conf.d/APP_DNSMASQ.monitrc"); $f = array(); $binpath = $unix->find_program("dnsmasq"); if (is_file($binpath)) { $EnableDNSMASQ = $users->EnableDNSMASQ(); if ($EnableDNSMASQ == 1) { $f[] = "check process APP_DNSMASQ with pidfile /var/run/dnsmasq.pid"; $f[] = "\tstart program = \"/etc/init.d/dnsmasq start --monit\""; $f[] = "\tstop program = \"/etc/init.d/dnsmasq stop --monit\""; $f[] = "\tif 5 restarts within 5 cycles then timeout"; $f[] = ""; if ($GLOBALS["OUTPUT"]) { echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring DNSMasq Service...\n"; } @file_put_contents("/etc/monit/conf.d/APP_DNSMASQ.monitrc", @implode("\n", $f)); } } //******************************************************************************************************************** if ($GLOBALS["OUTPUT"]) { echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} checking syslog\n"; } if (is_file("/etc/init.d/syslog")) { checkDebSyslog(); } if ($GLOBALS["OUTPUT"]) { echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} configuration done\n"; } shell_exec($GLOBALS["MONIT_CLASS"]->monitor_all_cmdline . " 2>&1"); build_progress_restart("{reconfiguring}", 45); }