function build() { $lic[] = "ITEM\t{"; $lic[] = "\t\"KEY\"\t\"Z5C2GDANS8189Y\""; $lic[] = "\t\"SERIAL\"\t\"TE91KNNFYHLDP1\""; $lic[] = "\t\"ORGANISATION\"\t\"Free Version Edition\""; $lic[] = "\t\"LICENSE\"\t\"ARK_DISKSTORAGE\""; $lic[] = "}\n"; $lic[] = "ITEM\t{"; $lic[] = "\t\"KEY\"\t\"PPKBEZCAVKH9PB\""; $lic[] = "\t\"SERIAL\"\t\"TL92JXVFRHMDPN\""; $lic[] = "\t\"ORGANISATION\"\t\"Free Version\""; $lic[] = "\t\"LICENSE\"\t\"ARK91\""; $lic[] = "}\n"; $unix = new unix(); $hostname = $unix->hostname_g(); if (!is_file("/opt/arkeia/arkeiad/admin.cfg")) { echo "Starting......: " . date("H:i:s") . " Arkeia Network Backup writing admin.cfg for ({$hostname})\n"; @file_put_contents("/opt/arkeia/arkeiad/admin.cfg", $unix->hostname_g()); } if (!is_file("/opt/arkeia/server/dbase/f3sec/license.lst")) { echo "Starting......: " . date("H:i:s") . " Arkeia Network Backup adding Free version license...\n"; @file_put_contents("/opt/arkeia/server/dbase/f3sec/license.lst", @implode("\n", $lic)); } $users = ParseUsers(); if (!isset($users["root"])) { if ($users["root"]["PASSWORD"] == null) { echo "Starting......: " . date("H:i:s") . " Arkeia Network Backup root as no password, delete it...\n"; unset($users["root"]); } } $ldap = new clladp(); $users[$ldap->ldap_admin]["PASSWORD"] = crypt($ldap->ldap_password, "n3"); $users[$ldap->ldap_admin]["DENY"] = "*"; $users[$ldap->ldap_admin]["NODE"] = "*"; $users[$ldap->ldap_admin]["EMAIL"] = ""; $users[$ldap->ldap_admin]["ROLE"] = "ADMINISTRATOR"; $users[$ldap->ldap_admin]["NAME"] = "{$ldap->ldap_admin}"; SetUsers($users); echo "Starting......: " . date("H:i:s") . " Arkeia Network Backup edit/add {$ldap->ldap_admin} done..\n"; $arc[] = "NODE\t\"localhost\""; $arc[] = "LOGIN\t\"{$ldap->ldap_admin}\""; $arc[] = "PASSWORD\t\"{$ldap->ldap_password}\""; $arc[] = "ENCODING\t\"1\""; $arc[] = "LANG\t\"EN\""; @file_put_contents("/opt/arkeia/arkc/arkc.param", @implode("\n", $arc)); echo "Starting......: " . date("H:i:s") . " Arkeia Network Backup edit arkc.param done..\n"; $akeiad[] = "ARKEIADLOGLEVEL\t\"10\"\t"; $akeiad[] = "PORT_NUMBER\t\"617\""; $akeiad[] = "NLP_TIMEOUT\t\"60\""; $akeiad[] = "RESTART_TIMEOUT\t\"300\""; $akeiad[] = "DONT_USE_PS\t\"1\""; $akeiad[] = ""; @file_put_contents("/opt/arkeia/arkeiad/arkeiad.cfg", @implode("\n", $arc)); echo "Starting......: " . date("H:i:s") . " Arkeia Network Backup edit arkeiad.cfg done..\n"; }
function iscsi_search() { $unix = new unix(); $uuid = $unix->GetUniqueID(); $hostname = $unix->hostname_g(); $hostnameR = explode(".", $hostname); krsort($hostnameR); $hostname = @implode(".", $hostnameR); @file_put_contents("/etc/iscsi/initiatorname.iscsi", "GenerateName=yes\n"); $ip = $_GET["iscsi-search"]; $unix = new unix(); $iscsiadm = $unix->find_program("iscsiadm"); $cmd = "{$iscsiadm} --mode discovery --type sendtargets --portal {$ip} 2>&1"; writelogs_framework("{$cmd}", __FUNCTION__, __FILE__, __LINE__); exec($cmd, $results); writelogs_framework("{$cmd} = " . count($results) . " rows", __FUNCTION__, __FILE__, __LINE__); $array = array(); while (list($index, $line) = each($results)) { if (preg_match("#Invalid Initiatorname#", $line)) { shell_exec("/etc/init.d/open-iscsi restart"); return; } if (!preg_match("#([0-9\\.]+):([0-9]+),([0-9]+)\\s+(.+?):(.+)#", $line, $re)) { continue; } $array[$re[1]][] = array("PORT" => $re[2], "ID" => $re[3], "ISCSI" => $re[4], "FOLDER" => $re[5], "IP" => $re[1]); } @file_put_contents("/usr/share/artica-postfix/ressources/logs/web/iscsi-search.array", serialize($array)); @chmod("/usr/share/artica-postfix/ressources/logs/web/iscsi-search.array", 0755); }
function scan() { if (system_is_overloaded(basename(__FILE__))) { apache_admin_mysql(0, "Overloaded system, retry next time....", null, __FILE__, __LINE__); return; } $pidtime = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".time"; $pidFile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid"; $unix = new unix(); $pid = $unix->get_pid_from_file($pidFile); if ($unix->process_exists($pid)) { events("A process, {$pid} Already exists..."); return; } $GLOBALS["MYHOSTNAME_PROXY"] = $unix->hostname_g(); @file_put_contents($pidFile, getmypid()); $time = $unix->file_time_min($pidtime); if (!$GLOBALS["VERBOSE"]) { if ($time < 5) { events("{$time}mn, require minimal 5mn"); return; } } $q = new mysql_squid_builder(); $q->QUERY_SQL("CREATE TABLE IF NOT EXISTS `dashboard_apache_sizes` ( `TIME` DATETIME,\n\t\t\t`zmd5` VARCHAR(90) NOT NULL PRIMARY KEY,\n\t\t\t`SITENAME` VARCHAR(128),\n\t\t\t`SIZE` BIGINT UNSIGNED, `RQS` BIGINT UNSIGNED,\n\t\t\tKEY `TIME` (`TIME`),\n\t\t\tKEY `SIZE` (`SIZE`),\n\t\t\tKEY `RQS` (`RQS`)\n\t\t\t) ENGINE=MYISAM;"); if (!$q->ok) { apache_admin_mysql(0, "Fatal MySQL error", $q->mysql_error, __FILE__, __LINE__); return; } if (!is_file("/home/apache/artica-stats/requests.log")) { echo "/home/apache/artica-stats/requests.log no such file...\n"; return; } @mkdir("/home/apache/artica-stats/works", 0755, true); if (is_file("/home/apache/artica-stats/works/apache.log")) { echo "Parse /home/apache/artica-stats/works/apache.log\n"; Parse("/home/apache/artica-stats/works/apache.log"); return; } if (!@copy("/home/apache/artica-stats/requests.log", "/home/apache/artica-stats/works/apache.log")) { echo "Copy failed\n"; return; } if (!is_file("/home/apache/artica-stats/works/apache.log")) { echo "/home/apache/artica-stats/works/apache.log no such file...\n"; return; } @unlink("/home/apache/artica-stats/requests.log"); echo "Parse /home/apache/artica-stats/works/apache.log\n"; Parse("/home/apache/artica-stats/works/apache.log"); CLEAN_MYSQL(); }
function migrate() { $q = new mysql(); $unix = new unix(); $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid"; $pidtime = "/etc/artica-postfix/pids/exec.suricata.hourly.migrate.time"; $pid = $unix->get_pid_from_file($pidfile); if ($unix->process_exists($pid, basename(__FILE__))) { $time = $unix->PROCCESS_TIME_MIN($pid); echo "Starting......: " . date("H:i:s") . " [INIT]: Already Artica task running PID {$pid} since {$time}mn\n"; return; } @file_put_contents($pidfile, getmypid()); $timeExec = $unix->file_time_min($pidtime); if ($timeExec < 60) { return; } @unlink($pidtime); @file_put_contents($pidtime, time()); $hostname = $unix->hostname_g(); if (!$q->TABLE_EXISTS("suricata_events", "artica_events")) { return; } $results = $q->QUERY_SQL("SELECT * FROM suricata_events", "artica_events"); $postgres = new postgres_sql(); $postgres->suricata_tables(); while ($ligne = mysql_fetch_assoc($results)) { $src_ip = $ligne["src_ip"]; $zDate = $ligne["zDate"]; $dst_ip = $ligne["dst_ip"]; $dst_port = $ligne["dst_port"]; $proto = $ligne["proto"]; $signature = $ligne["signature"]; $xcount = $ligne["xcount"]; $severity = $ligne["severity"]; $f[] = "('{$zDate}','{$src_ip}','{$dst_ip}','{$proto}','{$dst_port}','{$signature}','{$severity}','{$xcount}','{$hostname}')"; } if (count($f) > 0) { $prefix = "INSERT INTO suricata_events (zDate,src_ip,dst_ip,proto,dst_port,signature,severity,xcount,proxyname) VALUES "; $postgres->QUERY_SQL($prefix . @implode(",", $f)); if (!$postgres->ok) { return; } $q->QUERY_SQL("DROP TABLE suricata_events", "artica_events"); } }
function scan() { $pidtime = "/etc/artica-postfix/pids/exec.haproxy.events-parser.php.scan.time"; $pidFile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid"; $unix = new unix(); $pid = $unix->get_pid_from_file($pidFile); if ($unix->process_exists($pid)) { events("A process, {$pid} Already exists..."); return; } $GLOBALS["MYHOSTNAME_PROXY"] = $unix->hostname_g(); @file_put_contents($pidFile, getmypid()); if (!$GLOBALS["VERBOSE"]) { $time = $unix->file_time_min($pidtime); if (!$GLOBALS["VERBOSE"]) { if ($time < 5) { events("{$time}mn, require minimal 5mn"); return; } } } $GLOBALS["LogFileDeamonLogDir"] = "/home/artica/haproxy-postgres/realtime-events"; $Workpath = "{$GLOBALS["LogFileDeamonLogDir"]}/access-work"; @file_put_contents($pidtime, time()); @mkdir($GLOBALS["LogFileDeamonLogDir"], 0755, true); $postgres = new postgres_sql(); $postgres->CREATE_TABLES(); if (!$postgres->TABLE_EXISTS("haproxy_log")) { events("haproxy_log, not such table"); die; } if (is_file("{$GLOBALS["LogFileDeamonLogDir"]}/HAPROXY.LOG")) { HAPROXY_LOG("{$GLOBALS["LogFileDeamonLogDir"]}/HAPROXY.LOG"); } HAPROXY_LOG_SCAN($Workpath); }
function start_week() { $unix = new unix(); $hostname = $unix->hostname_g(); $now = InfluxQueryFromUTC(strtotime("-7 day")); $today = date("Y-m-d", $now) . " 00:00:00"; $sql = "SELECT SUM(TX) as TX, SUM(RX) as RX,ETH FROM ethrxtx WHERE proxyname='{$hostname}' AND time >'{$today}' group by time(4h),ETH"; $influx = new influx(); echo "{$sql}\n"; $main = $influx->QUERY_SQL($sql); $c = 0; $f = array(); foreach ($main as $row) { $time = date("Y-m-d H:i:s", InfluxToTime($row->time)); $ETH = $row->ETH; if ($ETH == "lo") { continue; } $RX = $row->RX; $TX = $row->TX; $f[] = "('{$time}','{$ETH}','{$RX}','{$TX}')"; } if (count($f) == 0) { return; } $q = new mysql(); if ($q->TABLE_EXISTS("RXTX_WEEK", "artica_events")) { $q->QUERY_SQL("TRUNCATE TABLE `RXTX_WEEK`", "artica_events"); } $sql = "CREATE TABLE IF NOT EXISTS `RXTX_WEEK`\n\t(`ZDATE` DATETIME,\n\t`RX` INT UNSIGNED NOT NULL DEFAULT 1,\n\t`TX` INT UNSIGNED NOT NULL DEFAULT 1,\n\t`ETH` VARCHAR(60),\n\tKEY `ZDATE`(`ZDATE`),\n\tKEY `RX`(`RX`),\n\tKEY `TX`(`TX`),\n\tKEY `ETH`(`ETH`) ) ENGINE = MYISAM;"; $q->QUERY_SQL($sql, "artica_events"); if (!$q->ok) { return; } $q->QUERY_SQL("INSERT IGNORE INTO RXTX_WEEK (ZDATE,ETH,RX,TX) VALUES " . @implode(",", $f), "artica_events"); }
function start($id) { $GLOBALS["CACHEFILE"] = "/usr/share/artica-postfix/ressources/logs/web/mimedefang.resend.progress.{$id}"; $id = intval($id); $sock = new sockets(); $unix = new unix(); if ($id == 0) { echo "ID: {$id} not supported\n"; build_progress(110, "{failed}"); die; } $postgres = new postgres_sql(); $tempfile = $unix->FILE_TEMP(); $Dirtemp = $unix->TEMP_DIR(); $q = new postgres_sql(); $ligne = pg_fetch_array($q->QUERY_SQL("SELECT * FROM quarmsg WHERE id='{$id}'")); if (!$q->ok) { echo "PostgreSQL Error:" . $q->mysql_error . "\n"; build_progress(110, "PostgreSQL {failed}"); die; } $instance = $unix->hostname_g(); $mailfrom = $ligne["mailfrom"]; $mailto = $ligne["mailto"]; $msgmd5 = $ligne["msgmd5"]; if ($mailfrom == null) { $mailfrom = "root@{$instance}"; } echo "From: {$mailfrom}\n"; echo "To..: {$mailto}\n"; echo "ID..: {$msgmd5}\n"; build_progress(20, "{$mailfrom} {to} {$mailto} ({$msgmd5})"); $sql = "SELECT contentid FROM quardata WHERE msgmd5='{$msgmd5}'"; $ligne = pg_fetch_array($q->QUERY_SQL($sql)); if (!$q->ok) { echo "PostgreSQL Error:" . $q->mysql_error . "\n"; build_progress(110, "PostgreSQL {failed}"); die; } $contentid = $ligne["contentid"]; build_progress(30, "msg id: {$contentid}"); @mkdir($Dirtemp, 0777, true); @chmod($Dirtemp, 0777); $sql = "select lo_export({$contentid}, '{$Dirtemp}/{$msgmd5}.gz')"; if ($GLOBALS["VERBOSE"]) { echo "<hr>{$sql}<br>\n"; } $q->QUERY_SQL($sql); if (!$q->ok) { echo "PostgreSQL Error:" . $q->mysql_error . "\n"; build_progress(110, "PostgreSQL {failed}"); die; } build_progress(40, "{uncompress}"); if (!$unix->uncompress("{$Dirtemp}/{$msgmd5}.gz", "{$Dirtemp}/{$msgmd5}.msg")) { @unlink("{$Dirtemp}/{$msgmd5}.gz"); @unlink("{$Dirtemp}/{$msgmd5}.msg"); build_progress(110, "{uncompress} {failed}"); die; } $smtp = new smtp(); $TargetHostname = inet_interfaces(); if (preg_match("#all#is", $TargetHostname)) { $TargetHostname = "127.0.0.1"; } $params["helo"] = $instance; $params["debug"] = true; $params["host"] = $TargetHostname; $params["bindto"] = "127.0.0.1"; build_progress(50, "{connecting}"); if (!$smtp->connect($params)) { build_progress(110, "{connect} {failed}"); @unlink("{$Dirtemp}/{$msgmd5}.msg"); echo "{$smtp->error_number}: Could not connect to `{$TargetHostname}` {$smtp->error_text}\n"; return; } $finalbody = @file_get_contents("{$Dirtemp}/{$msgmd5}.msg"); build_progress(90, "{sending}"); if (!$smtp->send(array("from" => $mailfrom, "recipients" => $mailto, "body" => $finalbody, "headers" => null))) { build_progress(110, "{sending} {failed}"); @unlink("{$Dirtemp}/{$msgmd5}.msg"); echo "{$smtp->error_number}: Could not connect to `{$TargetHostname}` {$smtp->error_text}\n"; $smtp->quit(); return; } @unlink("{$Dirtemp}/{$msgmd5}.msg"); $smtp->quit(); build_progress(100, "{success}"); }
function GRAB_DATAS($ligne, $md5) { $GLOBALS["zMD5"] = $md5; $params = unserialize($ligne["params"]); $influx = new influx(); $mintime = strtotime("2008-01-01 00:00:00"); $params["TO"] = intval($params["TO"]); $params["FROM"] = abs(intval($params["FROM"])); if ($params["FROM"] < $mintime) { $params["FROM"] = strtotime(date("Y-m-d 00:00:00")); } $params["TO"] = intval($params["TO"]); if ($params["TO"] < $mintime) { $params["TO"] = time(); } $influx = new influx(); $from = $params["FROM"]; $to = $params["TO"]; $interval = $params["INTERVAL"]; $USER_FIELD = $params["USER"]; $md5_table = md5(__FUNCTION__ . "." . "{$from}{$to}"); $searchsites = trim($params["searchsites"]); $searchuser = trim($params["searchuser"]); $searchsites_sql = null; $searchuser_sql = null; if ($searchsites == "*") { $searchsites = null; } if ($searchuser == "*") { $searchuser = null; } $SSEARCH = array(); $distance = $influx->DistanceHour($from, $to); echo "Distance: {$distance} hours\n"; $TimeGroup = "date_trunc('hour', zdate) as zdate"; $SQLA[] = "SELECT SUM(xcount) as xcount,{$TimeGroup},src_ip,dst_ip,dst_port,proto,severity,signature FROM suricata_events"; $SQLA[] = "WHERE"; $SQLA[] = "(zdate >='" . date("Y-m-d H:i:s", $from) . "' and zdate <= '" . date("Y-m-d H:i:s", $to) . "')"; $SQLA[] = "GROUP BY zdate, src_ip,dst_ip,dst_port,proto,severity,signature"; build_progress("{step} {waiting_data}: BigData engine, (websites) {please_wait}", 6); $unix = new unix(); $hostname = $unix->hostname_g(); $sql = "CREATE TABLE IF NOT EXISTS \"{$md5}report\" (\n\t\tzDate timestamp,\n\t\tsrc_ip inet,\n\t\tdst_ip inet,\n\t\tdst_port smallint NOT NULL,\n\t\tproto varchar(10) NOT NULL,\n\t\tseverity smallint NOT NULL,\n\t\tsignature BIGINT,\n\t\txcount BIGINT )"; $q = new postgres_sql(); $q->QUERY_SQL($sql); if (!$q->ok) { echo "***************\n{$q->mysql_error}\n***************\n"; return false; } $q->QUERY_SQL("create index zdate{$md5}report on \"{$md5}report\"(zdate);"); $q->QUERY_SQL("create index src_ip{$md5}report on \"{$md5}report\"(src_ip);"); $q->QUERY_SQL("create index dst_ip{$md5}report on \"{$md5}report\"(dst_ip);"); $q->QUERY_SQL("TRUNCATE TABLE \"{$md5}report\""); $sql = @implode(" ", $SQLA); $sql = "INSERT INTO \"{$md5}report\" (xcount,zdate,src_ip,dst_ip,dst_port,proto,severity,signature) {$sql}"; echo "***************\n{$sql}\n*****************\n"; $q->QUERY_SQL($sql); if (!$q->ok) { echo "***************\nERROR {$q->mysql_error}\n***************\n"; $q->QUERY_SQL("DROP TABLE \"{$md5}report\""); return false; } $ligne = pg_fetch_assoc($q->QUERY_SQL("SELECT COUNT(*) as tcount FROM \"{$md5}report\"")); if (!$q->ok) { echo "***************\nERROR {$q->mysql_error}\n***************\n"; $q->QUERY_SQL("DROP TABLE \"{$md5}report\""); return false; } $c = $ligne["tcount"]; if ($c == 0) { echo "No data....\n"; $q->QUERY_SQL("DROP TABLE \"{$md5}report\""); return false; } echo "{$c} items inserted to PostgreSQL\n"; $MAIN_ARRAY = array(); return true; }
function restore() { $sock = new sockets(); $unix = new unix(); $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid"; if ($GLOBALS["VERBOSE"]) { echo "PID: {$pidfile}\n"; } $pid = $unix->get_pid_from_file($pidfile); if ($unix->process_exists($pid)) { $TTL = $unix->PROCESS_TTL($pid); if ($TTL < 240) { return; } $kill = $unix->find_program("kill"); unix_system_kill_force($pid); } @file_put_contents($pidfile, getmypid()); $hostname = $unix->hostname_g(); progress(10, "{mounting}"); if (!restore_TestNas()) { system_admin_events("Mounting NAS filesystem report false", __FUNCTION__, __FILE__, __LINE__); progress(100, "{failed}"); return; } $BackupArticaRestoreNASIpaddr = $sock->GET_INFO("BackupArticaRestoreNASIpaddr"); $BackupArticaRestoreNASFolder = $sock->GET_INFO("BackupArticaRestoreNASFolder"); $BackupArticaRestoreNASUser = $sock->GET_INFO("BackupArticaRestoreNASUser"); $BackupArticaRestoreNASPassword = $sock->GET_INFO("BackupArticaRestoreNASPassword"); $BackupArticaRestoreNASFolderSource = $sock->GET_INFO("BackupArticaRestoreNASFolderSource"); $BackupArticaRestoreNetwork = $sock->GET_INFO("BackupArticaRestoreNetwork"); $mountPoint = "/mnt/BackupArticaRestoreNAS"; $BackupArticaRestoreNASFolderSource = str_replace("\\", "/", $BackupArticaRestoreNASFolderSource); $sourceDir = "{$mountPoint}/{$BackupArticaRestoreNASFolderSource}"; $sourceDir = str_replace("//", "/", $sourceDir); if (!is_file("{$sourceDir}/BKVERSION.txt")) { progress(100, "{failed} BKVERSION.txt no such file"); $mount = new mount("/var/log/artica-postfix/backup.debug"); if ($mount->ismounted($mountPoint)) { $mount->umount($mountPoint); } return; } $time = trim(@file_get_contents("{$sourceDir}/BKVERSION.txt")); progress(15, "{backup} " . date("Y-m-d H:i:s")); progress(20, "{restoring_ldap_database}, {please_wait}..."); Restore_ldap($sourceDir); progress(40, "{restoring_artica_settings}, {please_wait}..."); restore_artica_settings($sourceDir); progress(50, "{restoring_artica_databases}, {please_wait}..."); restore_artica_backup($sourceDir); progress(60, "{restoring_artica_databases}, {please_wait}..."); restore_ocsweb($sourceDir); progress(80, "{restoring_artica_databases}, {please_wait}..."); restore_squidlogs($sourceDir); progress(82, "{restoring} PowerDNS, {please_wait}..."); restore_powerdns($sourceDir); progress(90, "{reconfigure_server}, {please_wait}..."); $squidbin = $unix->LOCATE_SQUID_BIN(); $php = $unix->LOCATE_PHP5_BIN(); if (is_file($squidbin)) { shell_exec("{$php} /usr/share/artica-postfix/exec.squid.php --build --force"); } progress(100, "{success}"); $mount = new mount("/var/log/artica-postfix/backup.debug"); if ($mount->ismounted($mountPoint)) { $mount->umount($mountPoint); } if ($BackupArticaRestoreNetwork == 1) { $unix->THREAD_COMMAND_SET("{$php} /usr/share/artica-postfix/exec.virtuals-ip.php --build"); } return; }
function interface_menu($eth) { $ARTICAVERSION = @file_get_contents("/usr/share/artica-postfix/VERSION"); $unix = new unix(); $HOSTNAME = $unix->hostname_g(); $DIALOG = $unix->find_program("dialog"); $php = $unix->LOCATE_PHP5_BIN(); $NETWORK_ALL_INTERFACES = $unix->NETWORK_ALL_INTERFACES(); $DEFAULT = $NETWORK_ALL_INTERFACES[$eth]["IPADDR"]; $NETMASK = $NETWORK_ALL_INTERFACES[$eth]["NETMASK"]; $GATEWAY = $NETWORK_ALL_INTERFACES[$eth]["GATEWAY"]; $f[] = "#!/bin/bash"; $f[] = "INPUT=/tmp/menu.sh.\$\$"; $f[] = "OUTPUT=/tmp/output.sh.\$\$"; $f[] = "trap \"rm \$OUTPUT; rm \$INPUT; exit\" SIGHUP SIGINT SIGTERM"; $f[] = "DIALOG=\${DIALOG=dialog}"; @unlink("/etc/artica-postfix/WIZARDIP_{$eth}"); @unlink("/etc/artica-postfix/WIZARDMASK_{$eth}"); $f[] = "{$DIALOG} --clear --title \"ENTER IP ADDRESS FOR '{$eth}'\" --inputbox \"Enter your IP address for the {$eth} Interface.\\nExample: 111.112.113.114\" 10 68 {$DEFAULT} 2> /etc/artica-postfix/WIZARDIP_{$eth}"; $f[] = "if [ \$? = 1 -o \$? = 255 ]; then"; $f[] = "rm -f /etc/artica-postfix/WIZARDIP_{$eth}"; $f[] = "\treturn"; $f[] = "fi"; $f[] = "{$DIALOG} --clear --title \"ENTER IP ADDRESS FOR '{$eth}'\" --inputbox \"Enter your netmask for the {$eth} Interface.\\nExample: 255.255.255.0\" 10 68 {$NETMASK} 2> /etc/artica-postfix/WIZARDMASK_{$eth}"; $f[] = "if [ \$? = 1 -o \$? = 255 ]; then"; $f[] = "rm -f /etc/artica-postfix/WIZARDMASK_{$eth}"; $f[] = "\treturn"; $f[] = "fi"; $f[] = "{$DIALOG} --clear --title \"ENTER IP ADDRESS FOR '{$eth}'\" --inputbox \"Enter your gateway for the {$eth} Interface.\\nExample: 111.112.113.114\\nIf this interface is the main gateway of your network, set 0.0.0.0 here\" 10 68 {$GATEWAY} 2> /etc/artica-postfix/WIZARDGATEWAY_{$eth}"; $f[] = "if [ \$? = 1 -o \$? = 255 ]; then"; $f[] = "rm -f /etc/artica-postfix/WIZARDGATEWAY_{$eth}"; $f[] = "\treturn"; $f[] = "fi"; $f[] = "WIZARDIP=`cat /etc/artica-postfix/WIZARDIP_{$eth}`"; $f[] = "WIZARDMASK=`cat /etc/artica-postfix/WIZARDMASK_{$eth}`"; $f[] = "WIZARDGATEWAY=`cat /etc/artica-postfix/WIZARDGATEWAY_{$eth}`"; $f[] = "{$DIALOG} --title \"NETWORK SETUP COMPLETE\" --yesno \"Your networking system is now configured to use:\\n\$WIZARDIP/\$WIZARDMASK Gateway \$WIZARDGATEWAY\\nIs this correct? Press 'Yes' to continue, or 'No' to exit\" 0 0"; $f[] = "case \$? in"; $f[] = "0)"; $f[] = "\techo \"{$php} " . __FILE__ . " --savenic {$eth}\""; $f[] = "\t{$php} " . __FILE__ . " --savenic {$eth} >/tmp/{$eth}.log &"; $f[] = "\t{$DIALOG} --tailbox /tmp/{$eth}.log 25 150"; $f[] = "\tWIZARDRESULTS=`cat /etc/artica-postfix/WIZARDRESULT_{$eth}`"; $f[] = "\tif [ \"\$WIZARDRESULTS\" eq 0 ]; then"; $f[] = "\t{$DIALOG} --title \"{$eth} failed\" --msgbox \"Sorry, An error has occured\" 9 70"; $f[] = "\tfi"; $f[] = "\treturn;;"; $f[] = "1)"; $f[] = "\treturn;;"; $f[] = "255)"; $f[] = "\treturn;;"; $f[] = "esac"; $f[] = "\n"; @file_put_contents("/tmp/bash_network_menu_interface.sh", @implode("\n", $f)); @chmod("/tmp/bash_network_menu_interface.sh", 0755); }
function menu() { $ARTICAVERSION = @file_get_contents("/usr/share/artica-postfix/VERSION"); $unix = new unix(); $HOSTNAME = $unix->hostname_g(); $DIALOG = $unix->find_program("dialog"); $php = $unix->LOCATE_PHP5_BIN(); $echo = $unix->find_program("echo"); $diag[] = "{$DIALOG} --clear --nocancel --backtitle \"Software version {$ARTICAVERSION} on {$HOSTNAME}\""; $diag[] = "--title \"[ S Y S T E M - M E N U ]\""; $diag[] = "--menu \"You can use the UP/DOWN arrow keys\nChoose the TASK\" 20 100 10"; $diag[] = "PASSWD \"System root password\""; $diag[] = "SuperAdmin \"Web interface SuperAdmin account\""; $diag[] = "Update \"Update tasks\""; $diag[] = "BackupRestore \"Backup and restore (snapshots)\""; $diag[] = "CleanLogs \"Clean the log partition\""; $diag[] = "OPTIMIZE \"System Optimization ( SSD Disks, HyperV, XenServer, VMWare )\""; $diag[] = "Quit \"Return to main menu\" 2>\"\${INPUT}\""; $f[] = "#!/bin/bash"; $f[] = "INPUT=/tmp/menu.sh.\$\$"; $f[] = "OUTPUT=/tmp/output.sh.\$\$"; $f[] = "trap \"rm \$OUTPUT; rm \$INPUT; exit\" SIGHUP SIGINT SIGTERM"; $f[] = "DIALOG=\${DIALOG=dialog}"; $f[] = "function Updatep(){\n\tphp /usr/share/artica-postfix/exec.menu.updates.php --menu\n\t/tmp/bash_update_menu.sh\n}"; $f[] = "function BackupRestorep(){"; $f[] = "{$php} /usr/share/artica-postfix/exec.menu.snapshots.php --menu"; $f[] = "/tmp/bash_snapshots_menu.sh"; $f[] = "}"; $f[] = ""; $f[] = "function OPTIMIZE(){"; $f[] = "\t{$DIALOG} --title \"Optimize your system\" --yesno \"This operation optimize only your system when using\\n\\n- SSD disks\\n- Microsoft HyperV\\n- VMWare ESXI\\n- XenServer\\n\\n\\nYou need to reboot after this operation\\n\\n\\nDo you need to perform this operation ? Press 'Yes' to continue, or 'No' to exit\" 0 0"; $f[] = "\tcase \$? in"; $f[] = "\t\t0)"; $f[] = "\t\tif [ -f /tmp/dns.log ]; then"; $f[] = "\t\t\trm /tmp/dns.log"; $f[] = "\t\tfi"; $f[] = "\t\t{$echo} 1 >/etc/artica-postfix/settings/Daemons/EnableSystemOptimize"; $f[] = "\t\t{$php} /usr/share/artica-postfix/exec.vmware.php --optimize >/tmp/dns.log &"; $f[] = "\t{$DIALOG} --tailbox /tmp/dns.log 25 150"; $f[] = "\t\trm /etc/artica-postfix/WIZARUSERNAME"; $f[] = "\t\trm /etc/artica-postfix/WIZARUSERNAMEPASSWORD"; $f[] = "\t\treturn;;"; $f[] = "\tesac"; $f[] = "}"; $f[] = ""; $f[] = "function CleanLogsp(){"; $f[] = "\t{$DIALOG} --title \"Clean the log directory\" --yesno \"Do you need to perform this operation ? Press 'Yes' to continue, or 'No' to exit\" 0 0"; $f[] = "\tcase \$? in"; $f[] = "\t\t0)"; $f[] = "chmod 0755 /usr/share/artica-postfix/bin/remove-artica-logs.sh"; $f[] = "for i in \$(seq 0 20 80) ; do sleep 1; echo \$i | {$DIALOG} --gauge \"Please wait\" 10 70 0; done"; $f[] = "echo 90 | {$DIALOG} --gauge \"Running...\" 10 70 0"; $f[] = "/usr/share/artica-postfix/bin/remove-artica-logs.sh >/dev/null 2>&1"; $f[] = "sleep 1"; $f[] = "echo 100 | {$DIALOG} --gauge \"Please wait\" 10 70 0"; $f[] = "sleep 1"; $f[] = "\t{$DIALOG} --title \"Clean the log directory\" --msgbox \"Your log directory as been cleaned...\" 0 0"; $f[] = "\t\treturn;;"; $f[] = "\t1)"; $f[] = "\t\treturn;;"; $f[] = "\t255)"; $f[] = "\t\treturn;;"; $f[] = "\tesac"; $f[] = "}"; $f[] = ""; $f[] = "function PASSWDY(){"; $f[] = "\tpasswd root"; $f[] = "}"; $f[] = ""; $f[] = "function SuperAdmin(){"; $f[] = "\tif [ -f /tmp/dns.log ]; then"; $f[] = "\t\trm /tmp/dns.log"; $f[] = "\tfi"; $f[] = "\t{$DIALOG} --clear --title \"Username\" --inputbox \"Enter the SuperAdmin username\" 10 68 Manager 2> /etc/artica-postfix/WIZARUSERNAME"; $f[] = "\tcase \$? in"; $f[] = "\t\t1)"; $f[] = "\t\trm /etc/artica-postfix/WIZARUSERNAME || true"; $f[] = "\t\treturn"; $f[] = "\tesac"; $f[] = "WIZARUSERNAME = `cat /etc/artica-postfix/WIZARUSERNAME`"; $f[] = "\t{$DIALOG} --clear --insecure --passwordbox \"ENTER SuperAdmin Password for authentication\" 10 68 secret 2> /etc/artica-postfix/WIZARUSERNAMEPASSWORD"; $f[] = "\tcase \$? in"; $f[] = "\t\t1)"; $f[] = "\t\trm /etc/artica-postfix/WIZARUSERNAME || true"; $f[] = "\t\trm /etc/artica-postfix/WIZARUSERNAMEPASSWORD || true"; $f[] = "\t\treturn"; $f[] = "\tesac"; $f[] = "\t{$DIALOG} --title \"Change SuperAdmin Account\" --yesno \"Do you need to perform this operation ? Press 'Yes' to continue, or 'No' to exit\" 0 0"; $f[] = "\tcase \$? in"; $f[] = "\t\t0)"; $f[] = "\tif [ -f /tmp/dns.log ]; then"; $f[] = "\t\trm /tmp/dns.log"; $f[] = "\tfi"; $f[] = "\t{$php} " . __FILE__ . " --SuperAdmin >/tmp/dns.log &"; $f[] = "\t{$DIALOG} --tailbox /tmp/dns.log 25 150"; $f[] = "\t\trm /etc/artica-postfix/WIZARUSERNAME"; $f[] = "\t\trm /etc/artica-postfix/WIZARUSERNAMEPASSWORD"; $f[] = "\t\treturn;;"; $f[] = "\t1)"; $f[] = "\t\trm /etc/artica-postfix/WIZARUSERNAME"; $f[] = "\t\trm /etc/artica-postfix/WIZARUSERNAMEPASSWORD"; $f[] = "\t\treturn;;"; $f[] = "\t255)"; $f[] = "\t\trm /etc/artica-postfix/WIZARUSERNAME"; $f[] = "\t\trm /etc/artica-postfix/WIZARUSERNAMEPASSWORD"; $f[] = "\t\treturn;;"; $f[] = "\tesac"; $f[] = "}"; $f[] = ""; $f[] = ""; $f[] = "while true"; $f[] = "do"; $f[] = @implode(" ", $diag); $f[] = "menuitem=\$(<\"\${INPUT}\")"; $f[] = "case \$menuitem in"; $f[] = "OPTIMIZE) OPTIMIZE;;"; $f[] = "BackupRestore) BackupRestorep;;"; $f[] = "PASSWD) PASSWDY;;"; $f[] = "SuperAdmin) SuperAdmin;;"; $f[] = "Update) Updatep;;"; $f[] = "CleanLogs) CleanLogsp;;"; $f[] = "Quit) break;;"; $f[] = "esac"; $f[] = "done\n"; if ($GLOBALS["VERBOSE"]) { echo "Writing /tmp/bash_system_menu.sh\n"; } @file_put_contents("/tmp/bash_system_menu.sh", @implode("\n", $f)); @chmod("/tmp/bash_system_menu.sh", 0755); }
function ParseUserAuth($checkpid = false) { $unix = new unix(); $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid"; if ($checkpid) { $pid = @file_get_contents($pidfile); if ($pid < 100) { $pid = null; } if ($unix->process_exists($pid, basename(__FILE__))) { $time = $unix->PROCCESS_TIME_MIN($pid); writelogs_squid("Already executed pid {$pid} since {$time}mn-> DIE"); if ($GLOBALS["VERBOSE"]) { echo "Already executed pid {$pid} since {$time}mn\n"; } die; } @file_put_contents($pidfile, getmypid()); } $sock = new sockets(); if (isset($GLOBALS["EnableMacAddressFilter"])) { $GLOBALS["EnableMacAddressFilter"] = $sock->GET_INFO("EnableMacAddressFilter"); if (!is_numeric($GLOBALS["EnableMacAddressFilter"])) { $GLOBALS["EnableMacAddressFilter"] = 1; } } $hostname = $unix->hostname_g(); $MustContinue = false; ParseUserAuthNew(); if (function_exists("system_is_overloaded")) { $COUNT_FILES = $unix->COUNT_FILES("/var/log/artica-postfix/squid-users"); if ($COUNT_FILES < 1000) { if (system_is_overloaded()) { return; } } else { $MustContinue = true; } } $countDeFiles = 0; if (!($handle = opendir("/var/log/artica-postfix/squid-users"))) { @mkdir("/var/log/artica-postfix/squid-users", 0755, true); die; } if (!$MustContinue) { if (systemMaxOverloaded()) { return; } } $countDeFiles = 0; $prefix = "INSERT IGNORE INTO UserAutDB (zmd5,MAC,ipaddr,uid,hostname,UserAgent) VALUES "; $f = array(); while (false !== ($filename = readdir($handle))) { if ($filename == ".") { continue; } if ($filename == "..") { continue; } $targetFile = "/var/log/artica-postfix/squid-users/{$filename}"; $countDeFiles++; $content = @file_get_contents($targetFile); $array = unserialize($content); $ParseUserAuthArray = ParseUserAuthArray($array); if ($ParseUserAuthArray != null) { $f[] = $ParseUserAuthArray; } @unlink($targetFile); } if (count($f) > 0) { $q = new mysql_squid_builder(); $q->QUERY_SQL($prefix . @implode(",", $f)); } nmap_scan(); }
function RefreshIndex() { $unix = new unix(); $nice = EXEC_NICE(); $sock = new sockets(); $users = new usersMenus(); $nohup = $unix->find_program("nohup"); $php = $unix->LOCATE_PHP5_BIN(); $wget = $unix->find_program("wget"); $SYSTEMID = $unix->GetUniqueID(); if ($SYSTEMID == null) { build_progress("System ID is Null !!!", 5); return; } build_progress_index("Register server...", 10); build_progress("Register server...", 10); shell_exec("{$nohup} {$nice} {$php} /usr/share/artica-postfix/exec.web-community-filter.php --register-lic >/dev/null 2>&1 &"); if ($SYSTEMID == null) { build_progress_index("No system ID, force...", 15); build_progress("No system ID, force", 15); shell_exec("{$nice} /usr/share/artica-postfix/bin/artica-update -refresh-index --force >/dev/null 2>&1"); return; } $xMEM_TOTAL_INSTALLEE = $users->MEM_TOTAL_INSTALLEE; $CPU_NUMBER = $users->CPU_NUMBER; $LinuxDistributionFullName = $users->LinuxDistriFullName; if ($LinuxDistributionFullName == null) { $LinuxDistributionFullName = "Linux Default"; } $ARTICA_VERSION = GetCurrentVersion(); $hostname = $unix->hostname_g(); $CheckUserCount = CheckUserCount(); $RebootAfterArticaUpgrade = $sock->GET_INFO("RebootAfterArticaUpgrade"); if (!is_numeric($RebootAfterArticaUpgrade)) { $RebootAfterArticaUpgrade = 0; } $EnableScheduleUpdates = $sock->GET_INFO("EnableScheduleUpdates"); $ArticaUpdateIntervalAllways = intval($sock->GET_INFO("EnableScheduleUpdates")); if (!is_numeric($EnableScheduleUpdates)) { $EnableScheduleUpdates = 0; } $ArticaAutoUpateOfficial = $sock->GET_INFO("ArticaAutoUpateOfficial"); $ArticaAutoUpateNightly = intval($sock->GET_INFO("ArticaAutoUpateNightly")); $ArticaUpdateIntervalAllways = intval($sock->GET_INFO("ArticaUpdateIntervalAllways")); $OfficialArticaUri = $sock->GET_INFO("OfficialArticaUri"); if (!is_numeric($ArticaAutoUpateOfficial)) { $ArticaAutoUpateOfficial = 1; } if ($OfficialArticaUri == null) { $OfficialArticaUri = "http://articatech.net/artica.update.php"; } $uri = $OfficialArticaUri; $dmidecode = @file_get_contents("/etc/artica-postfix/dmidecode.cache.url"); @unlink($GLOBALS["MasterIndexFile"]); $tarballs_file = "/usr/share/artica-postfix/ressources/logs/web/tarballs.cache"; echo "Starting......: " . date("H:i:s") . " CPU NUMBER: {$CPU_NUMBER}\n"; echo "Starting......: " . date("H:i:s") . " Hostname..: {$hostname}\n"; echo "Starting......: " . date("H:i:s") . " Artica ver: {$ARTICA_VERSION}\n"; echo "Starting......: " . date("H:i:s") . " Users.....: {$CheckUserCount}\n"; build_progress_index("Configuration done...", 15); build_progress("Configuration done", 15); $DATA["UUID"] = $SYSTEMID; $DATA["MEM"] = $xMEM_TOTAL_INSTALLEE; $DATA["CPU"] = $CPU_NUMBER; $DATA["LINUX"] = $LinuxDistributionFullName; $DATA["VERSION"] = $ARTICA_VERSION; $DATA["HOSTNAME"] = $hostname; $DATA["USERS"] = $CheckUserCount; $DATA["DMICODE"] = $dmidecode; build_progress_index("Check repositories...", 20); build_progress("Check repositories", 20); $MAIN_URI = $unix->MAIN_URI(); echo "Starting......: " . date("H:i:s") . " Main URI..: {$MAIN_URI}\n"; $md5string = @md5_file($GLOBALS["MasterIndexFile"]); build_progress_index("Get Index...", 25); build_progress("Get Index...", 25); echo "Starting......: " . date("H:i:s") . " Update index file..\n"; $curl = new ccurl($OfficialArticaUri); $curl->parms["datas"] = base64_encode(serialize($DATA)); if (!$curl->get()) { echo "Last detected error: {$curl->error}\n"; build_progress_index("Get Index...{failed}", 110); build_progress("Get Index file !! FAILED !!", 110); _artica_update_event(0, "Unable to download index file with error {$curl->error_num}, {$curl->error}", null, __FILE__, __LINE__); return false; } @unlink("/etc/artica-postfix/settings/Daemons/ArticaUpdateRepos"); build_progress_index("Parse Index from repository", 40); build_progress("Parse Index from repository", 40); if (preg_match("#<ERROR>(.+?)</ERROR>#is", $curl->data, $re)) { echo "{$re[1]} !! FAILED !!\n"; build_progress_index("Corrupted index from repository !! FAILED !!", 110); build_progress("Corrupted index from repository !! FAILED !!", 110); return; } if (!preg_match("#<CONTENT>(.+?)</CONTENT>#is", $curl->data, $re)) { echo "Corrupted index from repository !! FAILED !!\n"; build_progress_index("Corrupted index from repository !! FAILED !!", 110); build_progress("Corrupted index from repository !! FAILED !!", 110); return; } $MAIN = unserialize(base64_decode($re[1])); if (!is_array($MAIN)) { echo "It is not an array...\n"; build_progress_index("Corrupted index from repository !! FAILED !!", 110); build_progress("Corrupted index from repository !! FAILED !!", 110); } build_progress_index("Retreive index from repository success", 100); @file_put_contents("/etc/artica-postfix/settings/Daemons/ArticaUpdateRepos", serialize($MAIN)); return true; }
function build() { $unix = new unix(); $sock = new sockets(); $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . "pid"; $pid = @file_get_contents($pidfile); if ($unix->process_exists($pid)) { build_progress("{$GLOBALS["deflog_start"]} Already process exists {$pid}", 110); echo "{$GLOBALS["deflog_start"]} Already process exists {$pid}\n"; return; } @file_put_contents($pidfile, getmypid()); $year = date('Y'); $month = date('m'); $EnableISCSI = intval($sock->GET_INFO("EnableISCSI")); $dd = $unix->find_program("dd"); if ($EnableISCSI == 0) { build_progress("{$GLOBALS["deflog_start"]} {service_disabled}", 110); return; } $sql = "SELECT * FROM iscsi_params ORDER BY ID DESC"; $q = new mysql(); $c = 0; $dd = $unix->find_program("dd"); $results = $q->QUERY_SQL($sql, 'artica_backup'); if (!$q->ok) { build_progress("{$GLOBALS["deflog_start"]} MySQL error", 110); echo "{$GLOBALS["deflog_start"]} {$q->mysql_error}\n"; return; } build_progress("{$GLOBALS["deflog_start"]} {building}...", 10); $max = mysql_num_rows($results); while ($ligne = mysql_fetch_array($results, MYSQL_ASSOC)) { $hostname = $ligne["hostname"]; $artica_type = $ligne["type"]; $tbl = explode(".", $hostname); echo "{$GLOBALS["deflog_start"]} [{$ligne["ID"]}] ressource type:{$artica_type} {$ligne["dev"]}\n"; build_progress("{$GLOBALS["deflog_start"]} {building} {$c}/{$max} {$artica_type} {$ligne["dev"]}", 20); if ($artica_type == "file") { if (!stat_system($ligne["dev"])) { echo "{$GLOBALS["deflog_start"]} [{$ligne["ID"]}] creating file {$ligne["dev"]} {$ligne["file_size"]}Go\n"; $countsize = $ligne["file_size"] * 1000; $cmd = "{$dd} if=/dev/zero of={$ligne["dev"]} bs=1M count={$countsize}"; if ($GLOBALS["VERBOSE"]) { echo "{$GLOBALS["deflog_start"]} [{$ligne["ID"]}] {$cmd}\n"; } shell_exec($cmd); if (!stat_system($ligne["dev"])) { build_progress("{$GLOBALS["deflog_start"]} {building} {$artica_type} {$ligne["dev"]} {failed}", 20); echo "{$GLOBALS["deflog_start"]} [{$ligne["ID"]}] failed\n"; continue; } } } krsort($tbl); $newhostname = @implode(".", $tbl); $Params = unserialize(base64_decode($ligne["Params"])); if (!isset($Params["ImmediateData"])) { $Params["ImmediateData"] = 1; } if (!isset($Params["MaxConnections"])) { $Params["MaxConnections"] = 1; } if (!isset($Params["Wthreads"])) { $Params["Wthreads"] = 8; } if (!isset($Params["IoType"])) { $Params["IoType"] = "fileio"; } if (!isset($Params["mode"])) { $Params["mode"] = "wb"; } if (!is_numeric($Params["MaxConnections"])) { $Params["MaxConnections"] = 1; } if (!is_numeric($Params["ImmediateData"])) { $Params["ImmediateData"] = 1; } if (!is_numeric($Params["Wthreads"])) { $Params["Wthreads"] = 8; } if ($Params["IoType"] == null) { $Params["IoType"] = "fileio"; } if ($Params["mode"] == null) { $Params["mode"] = "wb"; } $EnableAuth = $ligne["EnableAuth"]; $uid = trim($ligne["uid"]); echo "{$GLOBALS["deflog_start"]} [{$ligne["ID"]}] EnableAuth={$ligne["EnableAuth"]}\n"; echo "{$GLOBALS["deflog_start"]} [{$ligne["ID"]}] uid=\"{$uid}\"\n"; echo "{$GLOBALS["deflog_start"]} [{$ligne["ID"]}] Folder name=\"{$ligne["shared_folder"]} / {$ligne["type"]}\"\n"; echo "{$GLOBALS["deflog_start"]} [{$ligne["ID"]}] Path=\"{$ligne["dev"]}\"\n"; if ($ligne["type"] == "file") { if (is_dir($ligne["dev"])) { $newpath = FormatPath($ligne["dev"], $ligne["shared_folder"]); echo "{$GLOBALS["deflog_start"]} [{$ligne["ID"]}] Path is a directory assume {$newpath}\n"; $ligne["dev"] = $newpath; $q->QUERY_SQL("UPDATE iscsi_params SET `dev`='{$newpath}' WHERE ID='{$ligne["ID"]}'", "artica_backup"); } } if (is_link($ligne["dev"])) { $ligne["dev"] = @readlink($ligne["dev"]); } if ($ligne["type"] == "file") { $pathFile = $ligne["dev"]; $pathDir = dirname($ligne["dev"]); if (!is_dir($pathDir)) { @mkdir($pathDir, 0755, true); } if (!stat_system($pathFile)) { echo "{$GLOBALS["deflog_start"]} [{$ligne["ID"]}] {$pathFile} no such file, create it\n"; build_progress("{$GLOBALS["deflog_start"]} {building} {$pathFile}", 20); $countsize = $ligne["file_size"] * 1000; $cmd = "{$dd} if=/dev/zero of={$ligne["dev"]} bs=1M count={$countsize}"; echo "{$cmd}\n"; system($cmd); } } if ($Params["ImmediateData"] == 1) { $Params["ImmediateData"] = "Yes"; } else { $Params["ImmediateData"] = "No"; } $f[] = "Target iqn.{$year}-{$month}.{$newhostname}:{$ligne["shared_folder"]}"; if ($EnableAuth == 1) { if (strlen($uid) > 2) { echo "{$GLOBALS["deflog_start"]} Authentication enabled for {$ligne["dev"]} with member {$ligne["uid"]}\n"; $user = new user($ligne["uid"]); if ($user->password != null) { $f[] = "\tIncomingUser {$ligne["uid"]} {$user->password}"; } } } $f[] = "\tLun {$c} Path={$ligne["dev"]},Type={$Params["IoType"]},IOMode={$Params["mode"]}"; $f[] = "\tMaxConnections {$Params["MaxConnections"]}"; $f[] = "\tImmediateData {$Params["MaxConnections"]}"; $f[] = "\tWthreads {$Params["Wthreads"]}"; /*$f[]="\tMaxRecvDataSegmentLength 65536"; $f[]="\tMaxXmitDataSegmentLength 65536"; $f[]="\tMaxBurstLength 1048576"; $f[]="\tFirstBurstLength 262144"; $f[]="\tMaxOutstandingR2T 1"; $f[]="\tHeaderDigest None"; $f[]="\tDataDigest None"; $f[]="\tNOPInterval 60"; $f[]="\tNOPTimeout 180"; $f[]="\tQueuedCommands 64"; */ $f[] = ""; $c++; } @mkdir("/etc/iet", true, 0600); $hostname = $unix->hostname_g(); $tbl = explode(".", $hostname); krsort($tbl); $newhostname = @implode(".", $tbl); $sql = "SELECT * FROM users_containers WHERE created=1 AND onerror=0 AND iscsid=1"; $results = $q->QUERY_SQL($sql, "artica_backup"); $count = mysql_num_rows($results); if ($count > 0) { $sock = new sockets(); $sock->SET_INFO("EnableISCSI", 1); } build_progress("{checking_containers}", 30); while ($ligne = @mysql_fetch_array($results, MYSQL_ASSOC)) { $directory = trim($ligne["directory"]); $ID = $ligne["container_id"]; $container_time = $ligne["container_time"]; if (!is_numeric($container_time)) { $container_time = 0; } if ($container_time == 0) { $container_time = time(); $q->QUERY_SQL("UPDATE users_containers SET container_time={$container_time} WHERE container_id={$ID}", "artica_backup"); } $year = date("Y", $container_time); $month = date("m", $container_time); if ($directory == null) { echo "{$GLOBALS["deflog_start"]} id:{$ID} No specified main directory..."; continue; } $ContainerFullPath = $directory . "/{$ID}.disk"; $f[] = "Target iqn.{$year}-{$month}.{$newhostname}:disk{$ID}"; $webdav_creds = unserialize(base64_decode($ligne["webdav_creds"])); echo "{$GLOBALS["deflog_start"]} iqn.{$year}-{$month}.{$newhostname} {$ID}.disk LUN {$ContainerFullPath}\n"; build_progress("iqn.{$year}-{$month}.{$newhostname} {$ID}.disk", 35); $f[] = "\tIncomingUser {$webdav_creds["username"]} {$webdav_creds["password"]}"; $f[] = "\tLun {$c} Path={$ContainerFullPath},Type=fileio,IOMode=wb"; $f[] = "\tMaxConnections 5"; $f[] = "\tImmediateData Yes"; $f[] = "\tWthreads 8"; $f[] = ""; } build_progress("{saving_configuration}", 40); echo "{$GLOBALS["deflog_start"]} ietd.conf done\n"; @file_put_contents("/etc/iet/ietd.conf", @implode("\n", $f)); @file_put_contents("/etc/ietd.conf", @implode("\n", $f)); build_progress("{checking_startup_script}", 50); system($unix->LOCATE_PHP5_BIN() . " /usr/share/artica-postfix/exec.initslapd.php --iscsi"); if ($GLOBALS["PROGRESS"]) { build_progress("{restarting}", 80); system("/etc/init.d/iscsitarget restart"); } build_progress("{done}", 100); }
function BuildWarning($cpu, $time) { $load = sys_getloadavg(); $unix = new unix(); $hostname = $unix->hostname_g(); $ldtext[] = "**** Current system load ****"; $ldtext[] = "Load 1mn.: " . $load[0]; $ldtext[] = "Load 5mn.: " . $load[1]; $ldtext[] = "Load 15mn: " . $load[2]; $ldtext[] = "*****************************"; $subject = "CPU overload ({$cpu}%) and overloaded ({$GLOBALS["SYSTEM_INTERNAL_LOAD"]}/{$GLOBALS["SYSTEM_MAX_LOAD"]})"; shell_exec("/bin/ps -w axo ppid,pcpu,pmem,time,args --sort -pcpu,-pmem|/usr/bin/head --lines=20 >/tmp.top.txt 2>&1"); $top = file_get_contents("/tmp.top.txt"); @unlink("/tmp.top.txt"); $top = SafeProcesses() . "\n" . $top; $text = "Server report that your {$hostname} server has reach {$cpu}% CPU average consumption in {$time} minute(s)\n" . @implode("\n", $ldtext) . "\nYou will find below a processes report:\n---------------------------------------------\n{$top}\nGenerated by " . basename(__FILE__) . " (" . __FUNCTION__ . " on line " . __LINE__ . ") at " . date("H:i:s") . ""; send_email_events($subject, $text, 'system'); }
function ExplodeFile($filepath, $md5file = null) { $unix = new unix(); $LastScannLine = 0; $GLOBALS["MYSQL_CATZ"] = new mysql_catz(); $GLOBALS["SQUID_FAMILY_CLASS"] = new squid_familysite(); if (!isset($GLOBALS["MYHOSTNAME"])) { $unix = new unix(); $GLOBALS["MYHOSTNAME"] = $unix->hostname_g(); } $GLOBALS["SEQUENCE"] = md5_file($filepath); if (!is_file("{$filepath}.last")) { if (is_file("/home/artica/import-temp/{$GLOBALS["SEQUENCE"]}.working.log")) { $influx = new influx(); if ($influx->files_inject("/home/artica/import-temp/{$GLOBALS["SEQUENCE"]}.working.log")) { @unlink("/home/artica/import-temp/{$GLOBALS["SEQUENCE"]}.working.log"); return true; } } } $handle = @fopen($filepath, "r"); if (!$handle) { echo "Fopen failed on {$filepath}\n"; if ($md5file != null) { mysql_progress($md5file, 100, 3, "Fopen {failed} on {$filepath}"); } return false; } $countlines = 0; if ($md5file != null) { $countlines = $unix->COUNT_LINES_OF_FILE($filepath); if ($md5file != null) { mysql_progress($md5file, 10, 0, "Parsing {$countlines}"); } } if (is_file("{$filepath}.last")) { $LastScannLine = intval(@file_get_contents("{$filepath}.last")); } $c = 0; $d = 0; $e = 0; $prc = 0; $prc_text = 0; $mysql_first_time = 0; if ($LastScannLine > 0) { fseek($handle, $LastScannLine, SEEK_SET); } while (!feof($handle)) { $c++; $d++; $e++; if ($countlines > 0) { $prc = $c / $countlines; $prc = round($prc * 100); if (!isset($GLOBALS["LAST_PRC"])) { if ($GLOBALS["PROGRESS"]) { echo "{$prc}%\n"; } $GLOBALS["LAST_PRC"] = $prc; } else { if ($GLOBALS["LAST_PRC"] != $prc) { if ($GLOBALS["PROGRESS"]) { echo "{$prc}%\n"; } $GLOBALS["LAST_PRC"] = $prc; } } if ($prc > 10) { if ($prc < 99) { if ($prc > $prc_text) { $array_load = sys_getloadavg(); $internal_load = $array_load[0]; $mem = round(memory_get_usage() / 1024 / 1000, 2); $prc_design = FormatNumber($c) . "/" . FormatNumber($countlines); if ($md5file != null) { mysql_progress($md5file, $prc, 1, "{parsing} {$prc_design} {load}:{$internal_load} {memory}:{$mem}MB"); } $prc_text = $prc; } } } } if ($d > 50) { $iSeek = ftell($handle); @file_put_contents("{$filepath}.last", $iSeek); if ($GLOBALS["VERBOSE"]) { $prc_design = FormatNumber($c) . "/" . FormatNumber($countlines); echo "{$prc}% {$prc_design}\n"; } $d = 0; } if ($e > 500) { $mem = round(memory_get_usage() / 1024 / 1000, 2); $prc_design = FormatNumber($c) . "/" . FormatNumber($countlines); if ($md5file != null) { mysql_progress($md5file, $prc, 1, "{parsing} {$prc_design} {load}:{$internal_load} {memory}:{$mem}MB"); } $e = 0; } $buffer = trim(fgets($handle)); if ($buffer == null) { continue; } $array = parseAccessLine($buffer); if (count($array) == 0) { continue; } if ($mysql_first_time == 0) { if (date("Y", $array["TIME"]) > 2001) { $mysql_first_time = $array["TIME"]; mysql_first_time($md5file, $mysql_first_time); } } CachedSizeMem($array["TIME"], $array["CACHED"], $array["SIZE"]); if (intval($array["SIZE"]) == 0) { if ($GLOBALS["VERBOSE"]) { echo "Size = 0 " . __LINE__ . "\n"; } } CachedUserMem($array["TIME"], $array["SITENAME"], $array["SIZE"], null, $array["UID"], $array["IPADDR"], $array["CATEGORY"], $array["FAMILYSITE"]); } @unlink("{$filepath}.last"); mysql_last_time($md5file, $array["TIME"]); CachedUserMem_dump(); CachedSizeMem_dump(); $influx = new influx(); $size = filesize("/home/artica/import-temp/{$GLOBALS["SEQUENCE"]}.working.log"); $size = $size / 1024; $size = $size / 1024; echo "Importing {$size}MB of data....\n"; if (!$influx->files_inject("/home/artica/import-temp/{$GLOBALS["SEQUENCE"]}.working.log")) { @unlink("/home/artica/import-temp/{$GLOBALS["SEQUENCE"]}.working.log"); return false; } @unlink("/home/artica/import-temp/{$GLOBALS["SEQUENCE"]}.working.log"); return true; }
$send_listen_ip = $EnableDNSLinkerCreds["send_listen_ip"]; if (!is_numeric($listen_port)) { $listen_port = 9000; } $curl = new ccurl("https://{$hostname}:{$listen_port}/nodes.listener.php?PING=YES"); if ($send_listen_ip != null) { $curl->interface = $send_listen_ip; } $curlparms["listen_addr"] = $listen_addr; $curl = new ccurl("https://{$hostname}:{$listen_port}/nodes.listener.php"); if ($send_listen_ip != null) { $curl->interface = $send_listen_ip; } $curlparms["listen_addr"] = $listen_addr; $unix = new unix(); $curlparms["hostname"] = $unix->hostname_g(); $sql = "SELECT servername FROM freeweb"; $q = new mysql(); $results = $q->QUERY_SQL($sql, 'artica_backup'); while ($ligne = mysql_fetch_array($results, MYSQL_ASSOC)) { $curlparms["FREEWEBS_SRV"][$ligne["servername"]] = true; } @file_put_contents("/usr/share/artica-postfix/ressources/logs/web/com.txt", base64_encode(serialize($curlparms))); $net = new netagent(); $net->compress("/usr/share/artica-postfix/ressources/logs/web/com.txt", "/usr/share/artica-postfix/ressources/logs/web/com.txt.gz"); @unlink("/usr/share/artica-postfix/ressources/logs/web/com.txt"); $curl->x_www_form_urlencoded = true; if (!$curl->postFile("DNS_LINKER", "/usr/share/artica-postfix/ressources/logs/web/com.txt.gz", array("CREDS" => $EnableDNSLinkerCreds["CREDS"], "VERBOSE" => "TRUE"))) { echo "Posting informations Failed {$curl->error}...\n"; @unlink("/usr/share/artica-postfix/ressources/logs/web/com.txt.gz"); }
function SendMessage($subject, $content, $UfdbguardSMTPNotifs) { $smtp_dest = $UfdbguardSMTPNotifs["smtp_dest"]; $smtp_sender = $UfdbguardSMTPNotifs["smtp_sender"]; build_progress(15, "From {$smtp_sender}"); build_progress(20, "To {$smtp_dest}"); if ($smtp_dest == null) { build_progress(110, "To !!! {failed}"); return true; } if ($smtp_sender == null) { $unix = new unix(); $smtp_sender = "proxy@" . $unix->hostname_g(); } $mail = new PHPMailer(true); $mail->IsSMTP(); $mail->AddAddress($smtp_dest, $smtp_dest); $mail->AddReplyTo($smtp_sender, $smtp_sender); $mail->From = $smtp_sender; $mail->FromName = $smtp_sender; $mail->Subject = $subject; $mail->Body = $content; $mail->Host = $UfdbguardSMTPNotifs["smtp_server_name"]; $mail->Port = $UfdbguardSMTPNotifs["smtp_server_port"]; if ($UfdbguardSMTPNotifs["smtp_auth_user"] != null && $UfdbguardSMTPNotifs["smtp_auth_passwd"] != null) { build_progress(30, "Authenticate as {$UfdbguardSMTPNotifs["smtp_auth_user"]}"); $mail->SMTPAuth = true; $mail->Username = $UfdbguardSMTPNotifs["smtp_auth_user"]; $mail->Password = $UfdbguardSMTPNotifs["smtp_auth_passwd"]; if ($UfdbguardSMTPNotifs["tls_enabled"] == 1) { $mail->SMTPSecure = 'tls'; } if ($UfdbguardSMTPNotifs["ssl_enabled"] == 1) { $mail->SMTPSecure = 'ssl'; } } build_progress(40, "{sending_message}"); if (!$mail->Send()) { build_progress(110, "{failed}"); $function = __FUNCTION__; $line = __LINE__; if (!function_exists("syslog")) { return false; } $file = basename(__FILE__); $LOG_SEV = LOG_INFO; openlog($file, LOG_PID, LOG_SYSLOG); syslog($LOG_SEV, "**** FATAL SMTP FAILED *** [{$function}/{$line}] {$mail->MyFile}"); closelog(); return false; } build_progress(100, "{success}"); }
function archive_process($file) { $unix = new unix(); $timeMessage = filemtime($file); $fullmessagesdir = "/opt/artica/share/www/original_messages"; $target_file = $file; $filename = basename($target_file); if (!isset($GLOBALS["GREP"])) { $GLOBALS["GREP"] = $unix->find_program("grep"); } if (!isset($GLOBALS["MYHOSTNAME"])) { $GLOBALS["MYHOSTNAME"] = $unix->hostname_g(); } $grep = $GLOBALS["GREP"]; $ARCHIVED = false; $MailArchiverEnabled = $GLOBALS["MailArchiverEnabled"]; $MailArchiverToMySQL = $GLOBALS["MailArchiverToMySQL"]; $MailArchiverToMailBox = $GLOBALS["MailArchiverToMailBox"]; $MailArchiverMailBox = $GLOBALS["MailArchiverMailBox"]; $MailArchiverToSMTP = $GLOBALS["MailArchiverToSMTP"]; $MailArchiverSMTP = $GLOBALS["MailArchiverSMTP"]; $MailArchiverSMTPINcoming = $GLOBALS["MailArchiverSMTPINcoming"]; if (!is_numeric($MailArchiverSMTP)) { $MailArchiverSMTP = 0; } $realmailfrom = null; $realmailto = null; exec("{$grep} X-REAL- {$file} 2>&1", $resultsgrep); while (list($num, $line) = each($resultsgrep)) { events("[{$num}] {$line}", __LINE__); if (preg_match("#X-REAL-MAILFROM:\\s+<(.*?)>#", $line, $re)) { $realmailfrom = trim($re[1]); continue; } if (preg_match("#X-REAL-RCPTTO:\\s+<(.*?)>#", $line, $re)) { $realmailto = trim($re[1]); continue; } if ($realmailto == null) { if (preg_match("#X-REAL-RCPTTO:\\s+(.*)#", $line, $re)) { $realmailto = trim($re[1]); continue; } } if ($realmailfrom == null) { if (preg_match("#X-REAL-MAILFROM:\\s+(.*)#", $line, $re)) { $realmailfrom = trim($re[1]); continue; } } if (preg_match("#X-REAL-ARCHIVED#", $line, $re)) { events("{$file} detected as already archived...", __LINE__); $ARCHIVED = true; } } $realmailfrom = str_replace("<", "", $realmailfrom); $realmailfrom = str_replace(">", "", $realmailfrom); $realmailto = str_replace(">", "", $realmailto); $realmailto = str_replace("<", "", $realmailto); if ($GLOBALS["VERBOSE"]) { echo "X-REAL-MAILFROM: `{$realmailfrom}` X-REAL-RCPTTO: `{$realmailto}`\n"; } if ($GLOBALS["VERBOSE"]) { echo "MailArchiverToMailBox = {$MailArchiverToMailBox};MailArchiverSMTP={$MailArchiverSMTP}; \n"; } if ($MailArchiverToMailBox == 1) { if ($GLOBALS["VERBOSE"]) { echo "archive_process_smtp({$fullmessagesdir},{$realmailfrom})\n"; } if (!$ARCHIVED) { if (!archive_process_smtp($file, $realmailfrom)) { return false; } } } if ($MailArchiverSMTP == 1) { if (!$ARCHIVED) { if (!archive_process_smtpsrv($file, $realmailfrom, $realmailto)) { return false; } } } if (!$ARCHIVED) { if (!archive_process_copyto($file, $realmailfrom, $realmailto)) { return false; } } if ($MailArchiverToMySQL == 0) { return true; } $ldap = new clladp(); $q = new mysql_mailarchive_builder(); events("Unpack {$target_file}"); $mm = new demime($target_file); if (!$mm->unpack()) { events("Failed unpack with error \"{$mm->error}\""); if ($mm->MustkillMail) { @unlink($target_file); } return false; } $message_html = $mm->ExportToHtml($target_file); if (strlen($message_html) == 0) { system_admin_events("{$target_file}: HTML FAILED...", __FUNCTION__, __FILE__, __LINE__, "archive"); return false; } if (count($mm->mailto_array) == 0) { if ($realmailto != null) { $mm->mailto_array[] = $realmailto; } } if (count($mm->mailto_array) == 0) { system_admin_events("{$target_file}: Fatal No recipients Aborting", __FUNCTION__, __FILE__, __LINE__, "archive"); return true; } $filesize = @filesize($target_file); events("Message with " . count($mm->mailto_array) . " recipients html file:" . strlen($message_html) . " bytes"); if ($realmailfrom != null) { $mm->mailfrom = $realmailfrom; } if (preg_match("#(.+?)@(.+)#", $mm->mailfrom, $re)) { $domain_from = $re[2]; } $message_html = addslashes($message_html); $mm->message_date = date("Y-m-d H:i:s", $timeMessage); $tableDest = date("Ymd", $timeMessage); if (!$q->BuildDayTable($tableDest)) { system_admin_events("Fatal unable to create {$tableDest} date...", __FUNCTION__, __FILE__, __LINE__, "archive"); return false; } $SubjectMysql = addslashes(mime_decode($mm->subject)); while (list($num, $recipient) = each($mm->mailto_array)) { if (preg_match("#(.+?)@(.+)#", $recipient, $re)) { $recipient_domain = $re[2]; } $ou = $mm->GetOuFromEmail($recipient); $sql_source_file = $target_file; events("(New message)time={$mm->message_date} message-id=<{$mm->message_id}> from=<{$mm->mailfrom}> to=<{$recipient}> size={$filesize}"); $newmessageid = md5($mm->message_id . $recipient); $sqlfilesize = @filesize($target_file); $BinMessg = addslashes(fread(fopen($target_file, "r"), $sqlfilesize)); $sql = "INSERT IGNORE INTO `{$tableDest}` (\n\t\t\t\tMessageID,\n\t\t\t\tzDate,\n\t\t\t\tmailfrom,\n\t\t\t\tmailfrom_domain,\n\t\t\t\tsubject,\n\t\t\t\tMessageBody,\n\t\t\t\torganization,\n\t\t\t\tmailto,\n\t\t\t\tfile_path,\n\t\t\t\toriginal_messageid,\n\t\t\t\tmessage_size,\n\t\t\t\tBinMessg,filename,filesize\n\t\t\t\t)\n\t\t\tVALUES(\n\t\t\t\t'{$newmessageid}',\n\t\t\t\t'{$mm->message_date}',\n\t\t\t\t'{$mm->mailfrom}',\n\t\t\t\t'{$domain_from}',\n\t\t\t\t'{$SubjectMysql}',\n\t\t\t\t'{$message_html}',\n\t\t\t\t'{$ou}',\n\t\t\t\t'{$recipient}',\n\t\t\t\t'{$sql_source_file}',\n\t\t\t\t'{$mm->message_id}',\n\t\t\t\t'{$filesize}','{$BinMessg}','{$filename}','{$sqlfilesize}')"; if (!$q->QUERY_SQL($sql)) { system_admin_events("Fatal {$q->mysql_error}", __FUNCTION__, __FILE__, __LINE__, "archive"); return false; } } events("Analyze sender {$mm->mailfrom}..."); $ou = $mm->GetOuFromEmail($mm->mailfrom); if ($ou == null) { events("Not organization found for {$mm->mailfrom}..."); return true; } $recipients = $mm->mailto_array; $impled_rctp = implode(";", $recipients); $sql = "INSERT IGNORE INTO `{$tableDest}` (\n\t\t\t\tMessageID,\n\t\t\t\tzDate,\n\t\t\t\tmailfrom,\n\t\t\t\tmailfrom_domain,\n\t\t\t\tsubject,\n\t\t\t\tMessageBody,\n\t\t\t\torganization,\n\t\t\t\tmailto,\n\t\t\t\tfile_path,\n\t\t\t\toriginal_messageid,\n\t\t\t\tmessage_size,BinMessg,filename,filesize\n\t\t\t\t)\n\t\t\tVALUES(\n\t\t\t\t'{$newmessageid}',\n\t\t\t\t'{$mm->message_date}',\n\t\t\t\t'{$mm->mailfrom}',\n\t\t\t\t'{$domain_from}',\n\t\t\t\t'{$SubjectMysql}',\n\t\t\t\t'{$message_html}',\n\t\t\t\t'{$ou}',\n\t\t\t\t'{$impled_rctp}',\n\t\t\t\t'{$sql_source_file}',\n\t\t\t\t'{$mm->message_id}',\n\t\t\t\t'{$filesize}','{$BinMessg}','{$filename}','{$sqlfilesize}')"; $q->QUERY_SQL($sql); if (!$q->ok) { system_admin_events("Fatal {$q->mysql_error}", __FUNCTION__, __FILE__, __LINE__, "archive"); return false; } WriteToSyslogMail("{$mm->message_id}: <{$mm->mailfrom}> to: <{$impled_rctp}> size={$filesize} bytes (saved into backup area)", __FILE__); events("time={$mm->message_date} message-id=<{$mm->message_id}> from=<{$mm->mailfrom}> to=<{$impled_rctp}> size={$filesize}"); return true; }
CheckOutOfOffice($GLOBALS["recipients"][$i], $GLOBALS["sender"], $subject); CheckDisclaimerGlobal($GLOBALS["sender"], $GLOBALS["recipients"][$i], $tmpfname); } $sock = new sockets(); $ArticaFilterEnableRedirect = $sock->GET_INFO("ArticaFilterEnableRedirect"); if ($ArticaFilterEnableRedirect == 1) { if (mail_redirected($GLOBALS["recipients"], $GLOBALS["sender"], $tmpfname)) { exit(0); } } $unix = new unix(); if ($smtp_final_sender == null) { $smtp_final_sender = "127.0.0.1"; } $smtp_sock = new SMTP_SOCKETS(); $smtp_sock->myhostname = $unix->hostname_g(); if (!$smtp_sock->SendSMTPMailFromPath($smtp_final_sender, "33559", $GLOBALS["sender"], $GLOBALS["original_recipient"], $tmpfname)) { WriteToSyslogMail("FATAL smtp_sock from {$smtp_final_sender} ERROR" . @implode(" ", $smtp_sock->error), "artica-filter"); @unlink($tmpfname); exit(EX_TEMPFAIL); } events("from=<{$GLOBALS["sender"]}> to: <{$GLOBALS["original_recipient"]}> success delivered trough {$smtp_final_sender}:33559", "main", __LINE__); //WriteToSyslogMail("from=<{$GLOBALS["sender"]}> to: <{$GLOBALS["original_recipient"]}> success delivered trough $smtp_final_sender:33559","artica-filter"); @unlink($tmpfname); exit(0); function parse_args($opts, $args) { $ret = array(); for ($i = 0; $i < count($args); ++$i) { $arg = $args[$i]; if ($arg[0] == '-') {
function hostname_full() { $unix = new unix(); $host = $unix->hostname_g(); echo "<articadatascgi>{$host}</articadatascgi>"; }
function BlockIPs() { $ipClass = new IP(); $unix = new unix(); $tmpdir = $unix->TEMP_DIR(); $curl = new ccurl("https://rules.emergingthreatspro.com/fwrules/emerging-Block-IPs.txt"); $targetpath = "{$tmpdir}/emerging-Block-IPs.txt"; if (!$curl->GetFile($targetpath)) { echo "{$targetpath} failed\n"; artica_update_event(0, "Unable to download emerging-Block-IPs.txt", $curl->errors, __FILE__, __LINE__); return; } $f = explode("\n", @file_get_contents($targetpath)); $proxyname = $unix->hostname_g(); $q = new postgres_sql(); $q->suricata_tables(); $tr = array(); while (list($num, $ligne) = each($f)) { $ligne = trim($ligne); if ($ligne == null) { continue; } if (strpos(" {$ligne}", "#") > 0) { continue; } if (!$ipClass->isIPAddressOrRange($ligne)) { continue; } $zdate = date("Y-m-d H:i:s"); $proto = "TCP"; $dest_port = 0; $src_ip = $ligne; $uduniq = md5("0,{$src_ip},{$dest_port},{$proto}"); if ($GLOBALS["VERBOSE"]) { echo "0,{$src_ip},{$dest_port},{$proto}\n"; } $tr[] = "('{$zdate}','{$uduniq}','0','{$src_ip}','{$dest_port}','{$proto}','{$proxyname}',1)"; } if (count($tr) > 0) { $q->QUERY_SQL("DELETE FROM suricata_firewall WHERE xauto=1"); } $content = @implode(",", $tr); $prefix = "INSERT INTO suricata_firewall (zdate,uduniq,signature,src_ip,dst_port,proto,proxyname,xauto) VALUES "; $q->QUERY_SQL("{$prefix} {$content} ON CONFLICT DO NOTHING"); if (!$q->ok) { echo $q->mysql_error . "\n"; return; } $php = $unix->LOCATE_PHP5_BIN(); shell_exec("{$php} /usr/share/artica-postfix/exec.suricata-fw.php --run"); }
function parse($filename) { $unix = new unix(); $LastScannLine = 0; $GLOBALS["MYSQL_CATZ"] = new mysql_catz(); $GLOBALS["SQUID_FAMILY_CLASS"] = new squid_familysite(); if (!isset($GLOBALS["MYHOSTNAME"])) { $unix = new unix(); $GLOBALS["MYHOSTNAME"] = $unix->hostname_g(); } $filesource = dirname(__FILE__) . "/ressources/conf/upload/{$filename}"; if (!is_file($filesource)) { build_progress(110, "{$filename} no such file"); return; } $tmpfile = $unix->FILE_TEMP(); if (!@copy($filesource, $tmpfile)) { @unlink($filesource); build_progress(110, "{$filename} -> {$tmpfile} {failed}"); return; } @unlink($filesource); $SumOflines = $unix->COUNT_LINES_OF_FILE($tmpfile); echo "{$tmpfile} {$SumOflines} lines\n"; $handle = @fopen($tmpfile, "r"); if (!$handle) { echo "Fopen failed on {$tmpfile}\n"; build_progress(110, "{$tmpfile} {failed}"); @unlink($tmpfile); return false; } $c = 0; $d = 0; $e = 0; $prc = 0; $prc_text = 0; $mysql_first_time = 0; $SITES = array(); $NOT_CATEGORIZED = array(); $CATEGORIZED = array(); $RQS = array(); $IPClass = new IP(); $FIRSTTIME = 0; $LASTTIME = 0; $TIME1 = time(); while (!feof($handle)) { $c++; $d++; $e++; $prc = $c / $SumOflines; $prc = round($prc * 100); $buffer = trim(fgets($handle)); if ($buffer == null) { continue; } $stats_sites = count($SITES); $stats_categorized = count($CATEGORIZED); $stats_not_categorized = count($NOT_CATEGORIZED); if (!isset($GLOBALS["LAST_PRC"])) { build_progress($prc, "{$c}/{$SumOflines} {please_wait}"); $GLOBALS["LAST_PRC"] = $prc; } if ($prc > 5) { if ($prc < 95) { if ($GLOBALS["LAST_PRC"] != $prc) { $array_load = sys_getloadavg(); $internal_load = $array_load[0]; $mem = round(memory_get_usage() / 1024 / 1000, 2); echo "Load: {$internal_load}, Memory {$mem}MB\n"; echo "Categorized: " . FormatNumber($stats_categorized) . "\n"; echo "Unknown....: " . FormatNumber($stats_not_categorized) . "\n"; echo "Web sites..: " . FormatNumber($stats_sites) . "\n"; build_progress($prc, FormatNumber($c) . "/" . FormatNumber($SumOflines) . " {please_wait} - {$mem}MB {memory}"); $GLOBALS["LAST_PRC"] = $prc; } } } $array = parseAccessLine($buffer); if (count($array) == 0) { continue; } $TIME = $array["TIME"]; $LASTTIME = $TIME; if ($FIRSTTIME == 0) { $FIRSTTIME = $TIME; } $CATEGORY = $array["CATEGORY"]; $FAMILYSITE = $array["FAMILYSITE"]; $SIZE = intval($array["SIZE"]); if ($IPClass->isIPAddress($FAMILYSITE)) { if (!isset($IPADDRESSES[$FAMILYSITE]["RQS"])) { $IPADDRESSES[$FAMILYSITE]["RQS"] = 1; $IPADDRESSES[$FAMILYSITE]["SIZE"] = 0; $IPADDRESSES[$FAMILYSITE]["CATEGORY"] = $CATEGORY; } else { $IPADDRESSES[$FAMILYSITE]["RQS"] = $IPADDRESSES[$FAMILYSITE]["RQS"] + 1; $IPADDRESSES[$FAMILYSITE]["SIZE"] = $IPADDRESSES[$FAMILYSITE]["SIZE"] + $SIZE; } continue; } if (!isset($SITES[$FAMILYSITE])) { $SITES[$FAMILYSITE] = 0; } if (!isset($RQS[$FAMILYSITE])) { $RQS[$FAMILYSITE] = 0; } $SITES[$FAMILYSITE] = $SITES[$FAMILYSITE] + $SIZE; $RQS[$FAMILYSITE] = $RQS[$FAMILYSITE] + 1; if ($CATEGORY != null) { $CATEGORIZED[$FAMILYSITE] = $CATEGORY; continue; } $NOT_CATEGORIZED[$FAMILYSITE] = true; } fclose($handle); @unlink($tmpfile); build_progress(91, "{building_report}"); $TIME2 = time(); $stats_sites = count($SITES); $stats_categorized = count($CATEGORIZED); $stats_not_categorized = count($NOT_CATEGORIZED); $ARRAY["DURATION"] = $unix->distanceOfTimeInWords($TIME1, $TIME2); $ARRAY["SumOflines"] = $SumOflines; $ARRAY["stats_sites"] = $stats_sites; $ARRAY["stats_ip"] = count($IPADDRESSES); $ARRAY["firsttime"] = $FIRSTTIME; $ARRAY["lasttime"] = $LASTTIME; $ARRAY["stats_categorized"] = $stats_categorized; $ARRAY["stats_not_categorized"] = $stats_not_categorized; build_progress(92, "{building_report}"); $CSV1[] = array("website", "size", "requests"); while (list($familysite, $ligne) = each($NOT_CATEGORIZED)) { $CSV1[] = array($familysite, $SITES[$familysite], $RQS[$familysite]); } build_progress(95, "{building_report}"); $CSV2[] = array("website", "category", "size", "requests"); while (list($familysite, $category) = each($CATEGORIZED)) { $CSV2[] = array($familysite, $category, $SITES[$familysite], $RQS[$familysite]); } build_progress(97, "{building_report}"); $CSV3[] = array("Public IP addresses", "category", "size", "requests"); while (list($ip, $ARRAYIPS) = each($IPADDRESSES)) { $category = $ARRAYIPS["CATEGORY"]; $size = $ARRAYIPS["SIZE"]; $RQS = $ARRAYIPS["RQS"]; $CSV3[] = array($ip, $category, $size, $RQS); } build_progress(99, "{saving_reports}"); outputCSV($CSV1, "/usr/share/artica-postfix/ressources/logs/notcategorized.csv"); outputCSV($CSV2, "/usr/share/artica-postfix/ressources/logs/categorized.csv"); outputCSV($CSV3, "/usr/share/artica-postfix/ressources/logs/ipcategorized.csv"); @file_put_contents("/usr/share/artica-postfix/ressources/logs/categorized.array", serialize($ARRAY)); @chmod("/usr/share/artica-postfix/ressources/logs/notcategorized.csv", 0755); @chmod("/usr/share/artica-postfix/ressources/logs/ipcategorized.csv", 0755); @chmod("/usr/share/artica-postfix/ressources/logs/categorized.csv", 0755); @chmod("/usr/share/artica-postfix/ressources/logs/categorized.array", 0755); build_progress(100, "{done}"); }
function BuildTunServer(){ LoadArgvs(); $unix=new unix(); if(isset($GLOBALS["CLASS_SOCKETS"])){$sock=$GLOBALS["CLASS_SOCKETS"];}else{$GLOBALS["CLASS_SOCKETS"]=new sockets();$sock=$GLOBALS["CLASS_SOCKETS"];} $servername=$unix->hostname_g(); $routess=array(); $duplicate_cn=null; if(preg_match("#^(.+?)\.#",$servername,$re)){$servername=$re[1];} $servername=strtoupper($servername); echo "Starting......: OpenVPN building settings for $servername...\n"; $ini=new Bs_IniHandler(); $ini->loadString($sock->GET_INFO("ArticaOpenVPNSettings")); if(!isset($ini->_params["GLOBAL"]["ENABLE_BRIDGE_MODE"])){$ini->_params["GLOBAL"]["ENABLE_BRIDGE_MODE"]=0;} if(!isset($ini->_params["GLOBAL"]["IP_START"])){$ini->_params["GLOBAL"]["IP_START"]="10.8.0.0";} if(!isset($ini->_params["GLOBAL"]["NETMASK"])){$ini->_params["GLOBAL"]["NETMASK"]="255.255.255.0";} if($ini->_params["GLOBAL"]["ENABLE_BRIDGE_MODE"]==1){ echo "Starting......: OpenVPN building settings mode bridge enabled...\n"; BuildBridgeServer(); return; } $IPTABLES_ETH=$GLOBALS["IPTABLES_ETH"]; $DEV_TYPE=$ini->_params["GLOBAL"]["DEV_TYPE"]; $port=$ini->_params["GLOBAL"]["LISTEN_PORT"]; $IP_START=$ini->_params["GLOBAL"]["IP_START"]; $NETMASK=$ini->_params["GLOBAL"]["NETMASK"]; $bind_addr=$ini->_params["GLOBAL"]["LOCAL_BIND"]; $LISTEN_PROTO=$ini->_params["GLOBAL"]["LISTEN_PROTO"]; if($LISTEN_PROTO==null){$LISTEN_PROTO="udp";} if($LISTEN_PROTO=="udp"){$proto="--proto udp";}else{$proto="--proto tcp-server";} if(trim($port)==null){$port=1194;} if(trim($IP_START)==null){$IP_START="10.8.0.0";} if(trim($NETMASK)==null){$NETMASK="255.255.255.0";} $nic=new networking(); while (list ($num, $ligne) = each ($nic->array_TCP) ){ if($ligne==null){continue;} $eths[][$num]=$num; $ethi[$num]=$ligne; } if($IPTABLES_ETH<>null){ echo "Starting......: OpenVPN linked to $IPTABLES_ETH ({$ethi[$IPTABLES_ETH]})...\n"; $IPTABLES_ETH_ROUTE=IpCalcRoute($ethi[$IPTABLES_ETH]); }else{ echo "Starting......: OpenVPN no local NIC linked...\n"; } $ca='/etc/artica-postfix/openvpn/keys/allca.crt'; $dh='/etc/artica-postfix/openvpn/keys/dh1024.pem'; $key="/etc/artica-postfix/openvpn/keys/vpn-server.key"; $crt="/etc/artica-postfix/openvpn/keys/vpn-server.crt"; $route=''; //$IPTABLES_ETH_IP= if (is_file('/etc/artica-postfix/settings/Daemons/OpenVPNRoutes')){ $routes=(explode("\n",@file_get_contents("/etc/artica-postfix/settings/Daemons/OpenVPNRoutes"))); while (list ($num, $ligne) = each ($routes) ){ if(!preg_match("#(.+?)\s+(.+)#",$ligne,$re)){continue;} $routess[]="--push \"route {$re[1]} {$re[2]}\""; } } $GetRoutes=GetRoutes(); $routess=$routess+$GetRoutes; if(count($routess)==0){ if($IPTABLES_ETH_ROUTE<>null){ echo "Starting......: OpenVPN IP adding default route \"$IPTABLES_ETH_ROUTE\"\n"; $routess[]="--push \"route $IPTABLES_ETH_ROUTE\""; } }else{ echo "Starting......: OpenVPN IP adding ".count($routess)." routes\n"; } if(trim($bind_addr)<>null){ $local=" --local $bind_addr"; echo "Starting......: OpenVPN IP bind $bind_addr\n"; } $IP_START=FIX_IP_START($IP_START,$local); $ini->set("GLOBAL","IP_START",$IP_START); if(preg_match("#(.+?)\.([0-9]+)$#",$IP_START,$re)){ $calc_ip=" {$re[1]}.0"; $calc_ip_end="{$re[1]}.254"; echo "Starting......: OpenVPN IP pool from {$re[1]}.2 to {$re[1]}.254 mask:$NETMASK\n"; $server_ip="{$re[1]}.1"; $IP_START_PREFIX=$re[1]; } if($NETMASK==null){ $ip=new IP(); $cdir=$ip->ip2cidr($calc_ip,$calc_ip_end); $arr=$ip->parseCIDR($cdir); $rang=$arr[0]; $netbit=$arr[1]; $ipv=new ipv4($calc_ip,$netbit); $NETMASK=$ipv->netmask(); if($NETMASK=="255.255.255.255"){$NETMASK="255.255.255.0";} echo "Starting......: OpenVPN Netmask is null for the range $calc_ip, assume $NETMASK\n"; $ini->set("GLOBAL","NETMASK",$NETMASK); } $OpenVpnPasswordCert=$sock->GET_INFO("OpenVpnPasswordCert"); if($OpenVpnPasswordCert==null){$OpenVpnPasswordCert="MyKey";} $askpass=null; if(is_file("/etc/artica-postfix/openvpn/keys/password")){ $askpass="******"; } $ifconfig_pool_persist=" --ifconfig-pool-persist /etc/artica-postfix/openvpn/ipp.txt "; if(isset($GLOBALS["OPENVPNPARAMS"]["duplicate-cn"])){ echo "Starting......: OpenVPN duplicate-cn is enabled\n"; $duplicate_cn=" --duplicate-cn "; $ifconfig_pool_persist=null; } if(isset($GLOBALS["OPENVPNPARAMS"]["script-security"])){ echo "Starting......: OpenVPN script-security is enabled\n"; $script_security=" --script-security 2"; } if(!is_dir("/etc/openvpn/cdd")){@mkdir("/etc/openvpn/cdd");} $already=array(); echo "Starting......: OpenVPN get remote sites routes...\n"; $sql="SELECT sitename,IP_START,netmask,remote_site_routes,FixedIPAddr FROM vpnclient WHERE connexion_type=1"; $q=new mysql(); $results=$q->QUERY_SQL($sql,"artica_backup"); if(!$q->ok){echo2("Starting......: OpenVPN : $q->mysql_error");} while($ligne=mysql_fetch_array($results,MYSQL_ASSOC)){ $iroute=array(); $sitename=$ligne["sitename"]; $FixedIPAddr=$ligne["FixedIPAddr"]; if(!is_numeric($FixedIPAddr)){$FixedIPAddr=0;} if($IP_START_PREFIX<>null){ if($FixedIPAddr>2){ if($FixedIPAddr<255){ echo "Starting......: OpenVPN $sitename $IP_START_PREFIX.$FixedIPAddr fixed IP address\n"; $iroute[]="ifconfig-push $IP_START_PREFIX.$FixedIPAddr $IP_START_PREFIX.2"; } } } if(!isset($already[$ligne["IP_START"]])){ echo "Starting......: OpenVPN $sitename ({$ligne["IP_START"]} {$ligne["netmask"]})\n"; $rou[]=" --route {$ligne["IP_START"]} {$ligne["netmask"]}"; $iroute[]="iroute {$ligne["IP_START"]} {$ligne["netmask"]}"; $already[$ligne["IP_START"]]=true; } $remote_site_routes=unserialize(base64_decode($ligne["remote_site_routes"])); while (list ($num, $site_mask) = each ($remote_site_routes) ){ if(!isset($already[$num])){ echo "Starting......: OpenVPN $sitename ($num $site_mask)\n"; $rou[]=" --route $num $site_mask"; $iroute[]="iroute $num $site_mask"; $already[$num]=true; } } echo "Starting......: OpenVPN cdd $sitename\n"; @file_put_contents("/etc/openvpn/cdd/$sitename",@implode("\n", $iroute) ); } if(count($rou)>0){ $localroutes=@implode(" ", $rou); $client_config_dir=" --client-config-dir /etc/openvpn/cdd"; } $LDAP_AUTH=$ini->_params["GLOBAL"]["LDAP_AUTH"]; if($LDAP_AUTH==1){ if(is_file("/usr/lib/openvpn/openvpn-auth-pam.so")){ $plugin=" --plugin /usr/lib/openvpn/openvpn-auth-pam.so common-auth"; echo "Starting......: OpenVPN auth is enabled\n"; shell_exec("/usr/share/artica-postfix/bin/artica-install --nsswitch"); } } @mkdir("/etc/openvpn/ccd",0666,true); $php5=$unix->LOCATE_PHP5_BIN(); $me=__FILE__; $cmd=" --port $port --dev tun $proto --server $IP_START $NETMASK$localroutes$client_config_dir --comp-lzo $local --ca $ca --dh $dh --key $key --cert $crt"; $cmd=$cmd. "$ifconfig_pool_persist " . implode(" ",$routess); $cmd=$cmd. " $askpass$duplicate_cn--client-to-client$script_security$plugin --learn-address \"$php5 $me --client-connect\" --keepalive 10 60 --persist-tun --verb 5 --daemon --writepid /var/run/openvpn/openvpn-server.pid --log \"/var/log/openvpn/openvpn.log\""; $cmd=$cmd. " --status /var/log/openvpn/openvpn-status.log 10"; echo "Starting......: OpenVPN building /etc/openvpn/cmdline.conf done\n"; @file_put_contents("/etc/openvpn/cmdline.conf",$cmd); $sock->SaveConfigFile($ini->toString(),"ArticaOpenVPNSettings"); send_email_events("OpenVPN was successfully reconfigured",$cmd,"VPN"); echo "Starting......: OpenVPN building settings done.\n"; if($GLOBALS["VERBOSE"]){writelogs("$cmd",__FUNCTION__,__FILE__,__LINE__);} }
function BackupToNas($directory) { if (!is_dir($directory)) { return; } $syslog = new mysql_storelogs(); $sock = new sockets(); $users = new usersMenus(); $unix = new unix(); $myHostname = $unix->hostname_g(); $DirSuffix = basename($directory); $mount = new mount("/var/log/artica-postfix/logrotate.debug"); $BackupSquidLogsNASIpaddr = $sock->GET_INFO("BackupSquidLogsNASIpaddr"); $BackupSquidLogsNASFolder = $sock->GET_INFO("BackupSquidLogsNASFolder"); $BackupSquidLogsNASUser = $sock->GET_INFO("BackupSquidLogsNASUser"); $BackupSquidLogsNASPassword = $sock->GET_INFO("BackupSquidLogsNASPassword"); $BackupSquidLogsNASRetry = $sock->GET_INFO("BackupSquidLogsNASRetry"); if (!is_numeric($BackupSquidLogsNASRetry)) { $BackupSquidLogsNASRetry = 0; } $mount = new mount("/var/log/artica-postfix/logrotate.debug"); $BackupSquidLogsNASIpaddr = $sock->GET_INFO("BackupSquidLogsNASIpaddr"); $BackupSquidLogsNASFolder = $sock->GET_INFO("BackupSquidLogsNASFolder"); $BackupSquidLogsNASUser = $sock->GET_INFO("BackupSquidLogsNASUser"); $BackupSquidLogsNASPassword = $sock->GET_INFO("BackupSquidLogsNASPassword"); $BackupSquidLogsNASRetry = $sock->GET_INFO("BackupSquidLogsNASRetry"); if (!is_numeric($BackupSquidLogsNASRetry)) { $BackupSquidLogsNASRetry = 0; } $mv = $unix->find_program("mv"); if ($BackupSquidLogsNASIpaddr == null) { $this->events("Backup via NAS is disabled, skip", __FUNCTION__, __FILE__, __LINE__, "logrotate"); return false; } $mountPoint = "/mnt/BackupSquidLogsUseNas"; if (!$mount->smb_mount($mountPoint, $BackupSquidLogsNASIpaddr, $BackupSquidLogsNASUser, $BackupSquidLogsNASPassword, $BackupSquidLogsNASFolder)) { $syslog->events("Unable to connect to NAS storage system (1): {$BackupSquidLogsNASUser}@{$BackupSquidLogsNASIpaddr}", __FUNCTION__, __FILE__, __LINE__, "logrotate"); if ($BackupSquidLogsNASRetry == 0) { return; } sleep(3); $mount = new mount("/var/log/artica-postfix/logrotate.debug"); if (!$mount->smb_mount($mountPoint, $BackupSquidLogsNASIpaddr, $BackupSquidLogsNASUser, $BackupSquidLogsNASPassword, $BackupSquidLogsNASFolder)) { $syslog->events("Unable to connect to NAS storage system (1): {$BackupSquidLogsNASUser}@{$BackupSquidLogsNASIpaddr}", __FUNCTION__, __FILE__, __LINE__, "logrotate"); return; } } $syslog->events("Hostname={$myHostname} Suffix = {$DirSuffix} {$BackupSquidLogsNASIpaddr}/{$BackupSquidLogsNASFolder}", __FUNCTION__, __LINE__); $BackupMaxDaysDir = "{$mountPoint}/artica-backup-syslog"; @mkdir("{$BackupMaxDaysDir}", 0755, true); if (!is_dir($BackupMaxDaysDir)) { $syslog->events("Fatal {$BackupMaxDaysDir} permission denied", __FUNCTION__, __LINE__); if ($GLOBALS["VERBOSE"]) { echo "Fatal {$BackupMaxDaysDir} permission denied\n"; } squid_admin_mysql(0, "SYSLOG: FATAL {$BackupMaxDaysDir} permission denied", null, __FILE__, __LINE__); $mount->umount($mountPoint); return false; } $t = time(); @file_put_contents("{$BackupMaxDaysDir}/{$t}", time()); if (!is_file("{$BackupMaxDaysDir}/{$t}")) { $syslog->events("Fatal {$BackupMaxDaysDir} permission denied ({$BackupMaxDaysDir}/{$t}) test failed", __FUNCTION__, __LINE__); squid_admin_mysql(0, "SYSLOG: FATAL {$BackupMaxDaysDir} permission denied", null, __FILE__, __LINE__); $mount->umount($mountPoint); return false; } @unlink("{$BackupMaxDaysDir}/{$t}"); exec("{$mv} --force {$directory} --target-directory={$BackupMaxDaysDir}/ 2>&1", $results); while (list($index, $line) = each($results)) { $syslog->events("{$line}", __FUNCTION__, __LINE__); } analyze_destination_directory($BackupMaxDaysDir . "/proxy"); $mount->umount($mountPoint); return true; }
function zarafa_server2_config() { $unix = new unix(); $hostname = $unix->hostname_g(); $f[] = "server_bind\t\t\t= 0.0.0.0"; $f[] = "server_hostname\t\t= {$hostname}"; $f[] = "server_tcp_enabled\t= no"; $f[] = "server_tcp_port\t\t= 236"; $f[] = "server_pipe_enabled\t= yes"; $f[] = "server_pipe_name\t\t= /var/run/zarafa2"; $f[] = "server_pipe_priority = /var/run/zarafa-prio2"; $f[] = "server_name \t\t\t= Zarafa2"; $f[] = "database_engine\t\t= mysql"; $f[] = "allow_local_users\t\t= yes"; $f[] = "local_admin_users\t\t= root vmail mail "; $f[] = "system_email_address\t= postmaster@localhost"; $f[] = "run_as_user\t\t\t= "; $f[] = "run_as_group\t\t\t= "; $f[] = "pid_file\t\t\t\t= /var/run/zarafa-server2.pid"; $f[] = "running_path \t\t\t= /"; $f[] = "session_timeout\t\t= 300"; $f[] = "license_socket\t\t= /var/run/zarafa-licensed2"; $f[] = "log_method\t\t\t= file"; $f[] = "audit_log_enabled\t\t= yes"; $f[] = "audit_log_method\t\t= syslog"; $f[] = "audit_log_file\t\t= -"; $f[] = "audit_log_level\t\t= 3"; $f[] = "audit_log_timestamp\t= 0"; $f[] = "log_file\t\t\t\t= /var/log/zarafa/server2.log"; $f[] = "log_level\t\t\t\t= 9"; $f[] = "log_timestamp\t\t\t= 1"; $f[] = "mysql_socket\t\t\t= /var/run/mysqld/zarafa-db.sock"; $f[] = "mysql_user\t\t\t= root"; $f[] = "mysql_database\t\t= zarafa"; $f[] = "attachment_storage\t= database"; $f[] = "attachment_path\t\t= /var/lib/zarafa"; $f[] = "attachment_compression= 6"; $f[] = "index_services_enabled= no"; $f[] = "enable_enhanced_ics\t= yes"; $f[] = "search_enabled \t\t= no"; $f[] = "enable_sso_ntlmauth\t= no"; $f[] = "server_ssl_enabled\t= no"; $f[] = "server_ssl_port\t\t= 237"; $f[] = "sslkeys_path\t\t\t= /etc/ssl/certs/zarafa"; $f[] = "softdelete_lifetime\t= 30"; $f[] = "sync_lifetime\t\t\t= 730"; $f[] = "sync_log_all_changes \t= yes"; $f[] = "enable_gab \t\t\t= yes"; $f[] = "auth_method \t\t\t= plugin"; $f[] = "pam_service \t\t\t= passwd"; $f[] = "cache_cell_size\t\t= 16777216"; $f[] = "cache_object_size\t\t= 5242880"; $f[] = "cache_indexedobject_size= 16777216"; $f[] = "cache_quota_size\t\t= 1048576"; $f[] = "cache_acl_size\t\t= 1048576"; $f[] = "cache_user_size\t\t= 1048576"; $f[] = "cache_userdetails_size= 1048576"; $f[] = "cache_server_size\t\t= 1048576"; $f[] = "cache_quota_lifetime\t= 1"; $f[] = "cache_userdetails_lifetime= 5"; $f[] = "thread_stacksize \t\t= 512"; $f[] = "quota_warn\t\t\t= 0"; $f[] = "quota_soft\t\t\t= 0"; $f[] = "quota_hard\t\t\t= 0"; $f[] = "companyquota_warn \t= 0"; $f[] = "user_plugin\t\t\t= ldap"; $f[] = "user_plugin_config\t= /etc/zarafa/ldap.openldap.cfg"; $f[] = "# Multi-tenancy configurations"; $f[] = "enable_hosted_zarafa\t= yes"; $f[] = "enable_distributed_zarafa = false"; $f[] = "storename_format \t\t= %f"; $f[] = "loginname_format \t\t= %u"; $f[] = "client_update_enabled = true"; $f[] = "client_update_path \t= /var/lib/zarafa/client"; $f[] = "hide_everyone \t\t= no"; $f[] = "plugin_path\t\t\t= /usr/lib/zarafa"; $f[] = "user_safe_mode \t\t= no"; $f[] = "disabled_features \t=\n"; @file_put_contents("/etc/zarafa/server2.cfg", @implode("\n", $f)); if ($GLOBALS["OUTPUT"]) { echo "Starting......: " . date("H:i:s") . " [INIT]: `/etc/zarafa/server2.cfg` success...\n"; } }
function RefreshIndex() { $unix = new unix(); $nice = EXEC_NICE(); $sock = new sockets(); $users = new usersMenus(); $nohup = $unix->find_program("nohup"); $php = $unix->LOCATE_PHP5_BIN(); $wget = $unix->find_program("wget"); $SYSTEMID = $unix->GetUniqueID(); if ($SYSTEMID == null) { build_progress("System ID is Null !!!", 5); return; } build_progress("Register server...", 10); shell_exec("{$nohup} {$nice} {$php} /usr/share/artica-postfix/exec.web-community-filter.php --register-lic >/dev/null 2>&1 &"); if ($SYSTEMID == null) { build_progress("No system ID, force", 15); shell_exec("{$nice} /usr/share/artica-postfix/bin/artica-update -refresh-index --force >/dev/null 2>&1"); return; } $xMEM_TOTAL_INSTALLEE = $users->MEM_TOTAL_INSTALLEE; $CPU_NUMBER = $users->CPU_NUMBER; $LinuxDistributionFullName = $users->LinuxDistriFullName; if ($LinuxDistributionFullName == null) { $LinuxDistributionFullName = "Linux Default"; } $ARTICA_VERSION = GetCurrentVersion(); $hostname = $unix->hostname_g(); $CheckUserCount = CheckUserCount(); $dmidecode = @file_get_contents("/etc/artica-postfix/dmidecode.cache.url"); $uriplus = "{$SYSTEMID};{$xMEM_TOTAL_INSTALLEE};{$CPU_NUMBER};{$LinuxDistributionFullName};{$ARTICA_VERSION};{$hostname};{$CheckUserCount};{$dmidecode}"; $uriplus = urlencode($uriplus); @unlink($GLOBALS["MasterIndexFile"]); $tarballs_file = "/usr/share/artica-postfix/ressources/logs/web/tarballs.cache"; echo "Starting......: " . date("H:i:s") . " CPU NUMBER: {$CPU_NUMBER}\n"; echo "Starting......: " . date("H:i:s") . " Hostname..: {$hostname}\n"; echo "Starting......: " . date("H:i:s") . " Artica ver: {$ARTICA_VERSION}\n"; echo "Starting......: " . date("H:i:s") . " Users.....: {$CheckUserCount}\n"; build_progress("Configuration done", 15); $ini = new iniFrameWork(); $ini->loadFile('/etc/artica-postfix/artica-update.conf'); if (trim($ini->_params["AUTOUPDATE"]["uri"]) == null) { $ini->_params["AUTOUPDATE"]["uri"] = "http://www.articatech.net/auto.update.php"; } if (!isset($ini->_params["AUTOUPDATE"]["enabled"])) { $ini->_params["AUTOUPDATE"]["enabled"] = "yes"; } if ($ini->_params["AUTOUPDATE"]["enabled"] == null) { $ini->_params["AUTOUPDATE"]["enabled"] = "yes"; } if (!is_numeric(trim($ini->_params["AUTOUPDATE"]["CheckEveryMinutes"]))) { $ini->_params["AUTOUPDATE"]["CheckEveryMinutes"] = 60; } $uri = $ini->_params["AUTOUPDATE"]["uri"]; $arrayURI = parse_url($uri); build_progress("Check repositories", 20); $MAIN_URI = $unix->MAIN_URI(); echo "Starting......: " . date("H:i:s") . " Main URI..: {$MAIN_URI}\n"; $md5string = @md5_file($GLOBALS["MasterIndexFile"]); build_progress("Get TarBalls...", 25); echo "Starting......: " . date("H:i:s") . " Update tarballs..\n"; $curl = new ccurl("{$MAIN_URI}/tarballs.php?time=" . time()); @unlink($tarballs_file); $curl->NoHTTP_POST = true; if (!$curl->GetFile($tarballs_file)) { build_progress("Get TarBalls !! FAILED !!", 30); _artica_update_event(0, "Unable to download tarballs file with error {$curl->error_num}, {$curl->error}", null, __FILE__, __LINE__); @unlink($tarballs_file); } build_progress("Ping repositories...", 35); @chmod($tarballs_file, 0755); echo "Starting......: " . date("H:i:s") . " dmidecode = " . strlen($dmidecode) . " bytes\n"; echo "Starting......: " . date("H:i:s") . " Updating repository information..\n"; $curl = new ccurl("{$MAIN_URI}/routers.inject.php?time=" . time()); $curl->NoHTTP_POST = true; $curl->get(); build_progress("Retreive index from repository", 40); $curl = new ccurl("{$uri}?time=" . time() . "&datas={$uriplus}"); $curl->NoHTTP_POST = true; $curl->forceCache = true; echo "Starting......: " . date("H:i:s") . " Downloading collection using Interface: `{$curl->interface}`\n"; echo "Starting......: " . date("H:i:s") . " Using \"{$GLOBALS["MasterIndexFile"]}\"\n"; echo "Starting......: " . date("H:i:s") . " Timeout set to \"{$curl->Timeout}s\"\n"; if (!$curl->GetFile($GLOBALS["MasterIndexFile"])) { build_progress("Retreive index from repository !! FAILED !!", 100); if (!$GLOBALS["NOT_FORCE_PROXY"]) { echo "Starting......: " . date("H:i:s") . " FATAL: Unable to download index file, try in direct mode\n"; $GLOBALS["NOT_FORCE_PROXY"] = true; return RefreshIndex(); } echo "Starting......: " . date("H:i:s") . " FATAL: {$GLOBALS["MasterIndexFile"]} " . @filesize($GLOBALS["MasterIndexFile"]) . " bytes\n"; echo "Starting......: " . date("H:i:s") . " FATAL: Unable to download index file with error {$curl->error_num}, {$curl->error}\n"; _artica_update_event(0, "Unable to download index file with error {$curl->error_num}, {$curl->error}", null, __FILE__, __LINE__); exec("{$nice} /usr/share/artica-postfix/bin/artica-update -refresh-index 2>&1", $results); while (list($num, $ligne) = each($dirs)) { echo "Starting......: " . date("H:i:s") . " {$ligne}\n"; } return; } build_progress("Retreive index from repository !! Success !!", 100); $md5string2 = md5_file($GLOBALS["MasterIndexFile"]); echo "Starting......: " . date("H:i:s") . " source: `{$md5string}` new: `{$md5string2}`\n"; echo "Starting......: " . date("H:i:s") . " Success...\n"; return true; }
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); }
function build_default_asArtica() { $nginx = new nginx(); $unix = new unix(); $squidR = new squidbee(); $f[] = "server {"; $f[] = "\tlisten 80;"; $f[] = "\tserver_name " . $unix->hostname_g() . ";"; $f[] = "\tindex logon.php;"; $f[] = "\tlocation /nginx_status {"; $f[] = "\tstub_status on;"; $f[] = "\terror_log /var/log/nginx/default.error.log warn;"; $f[] = "\taccess_log /var/log/nginx/default.access.log;"; $f[] = "\tallow all;"; $f[] = "\t}"; $f[] = "\tlocation / {"; $f[] = "\t\troot\t/usr/share/artica-postfix;"; $f[] = "\t}"; $f[] = $nginx->php_fpm("logon.php", "/usr/share/artica-postfix", 1); $f[] = "}"; $f[] = "server {"; $f[] = "\tlisten 443;"; $f[] = "\tindex logon.php;"; $f[] = "\tkeepalive_timeout 70;"; $f[] = "\terror_log /var/log/nginx/default.error.log warn;"; $f[] = "\taccess_log /var/log/nginx/default.access.log;"; $f[] = "\tssl on;"; $f[] = "\t" . $squidR->SaveCertificate($unix->hostname_g(), false, true); $f[] = "\tssl_session_timeout 5m;"; $f[] = "\tssl_protocols SSLv3 TLSv1;"; $f[] = "\tssl_ciphers HIGH:!aNULL:!MD5;"; $f[] = "\tssl_prefer_server_ciphers on;"; $f[] = "\tserver_name " . $unix->hostname_g() . ";"; $f[] = "\tlocation / {"; $f[] = "\t\troot\t/usr/share/artica-postfix;"; $f[] = "\t}"; $f[] = $nginx->php_fpm("logon.php", "/usr/share/artica-postfix", 1); $f[] = "}"; @file_put_contents("/etc/nginx/conf.d/default.conf", @implode("\n", $f)); if ($GLOBALS["RELOAD"]) { reload(true); } }
function build($nopid = false) { if (isset($GLOBALS["BUILD_EXECUTED"])) { progress_logs(20, "{continue}", "Already executed"); return; } $GLOBALS["BUILD_EXECUTED"] = true; $unix = new unix(); $sock = new sockets(); $function = __FUNCTION__; $EnableKerbAuth = $sock->GET_INFO("EnableKerbAuth"); if (!is_numeric($EnableKerbAuth)) { $EnableKerbAuth = 0; } if ($EnableKerbAuth == 0) { progress_logs(110, "{authentication_via_activedirectory_is_disabled}", "{authentication_via_activedirectory_is_disabled}"); if (is_file("/etc/monit/conf.d/winbindd.monitrc")) { @unlink("/etc/monit/conf.d/winbindd.monitrc"); } return; } if (!$nopid) { $timefile = "/etc/artica-postfix/pids/" . basename(__FILE__) . ".time"; $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . ".pid"; $pid = $unix->get_pid_from_file($pidfile); if ($unix->process_exists($pid, basename(__FILE__))) { $timeExec = intval($unix->PROCCESS_TIME_MIN($pid)); if ($GLOBALS["OUTPUT"]) { progress_logs(20, "{join_activedirectory_domain}", "Process {$pid} already exists since {$timeExec}Mn"); } writelogs("Process {$pid} already exists since {$timeExec}Mn", __FUNCTION__, __FILE__, __LINE__); if ($timeExec > 5) { $kill = $unix->find_program("kill"); progress_logs(20, "{join_activedirectory_domain}", "killing old pid {$pid} (already exists since {$timeExec}Mn)"); unix_system_kill_force($pid); } else { return; } } $time = $unix->file_time_min($timefile); if ($time < 2) { if ($GLOBALS["OUTPUT"]) { progress_logs(20, "{join_activedirectory_domain}", "2mn minimal to run this script currently ({$time}Mn)"); } writelogs("2mn minimal to run this script currently ({$time}Mn)", __FUNCTION__, __FILE__, __LINE__); return; } } pinglic(true); $mypid = getmypid(); @file_put_contents($pidfile, $mypid); progress_logs(20, "{join_activedirectory_domain} Running PID {$mypid}", "Running PID {$mypid}", __LINE__); writelogs("Running PID {$mypid}", __FUNCTION__, __FILE__, __LINE__); $wbinfo = $unix->find_program("wbinfo"); $nohup = $unix->find_program("nohup"); $tar = $unix->find_program("tar"); $ntpdate = $unix->find_program("ntpdate"); $php5 = $unix->LOCATE_PHP5_BIN(); if (!is_file($wbinfo)) { shell_exec("{$php5} /usr/share/artica-postfix exec.apt-get.php --sources-list"); shell_exec("{$nohup} /usr/share/artica-postfix/bin/setup-ubuntu --check-samba >/dev/null 2>&1 &"); $wbinfo = $unix->find_program("wbinfo"); } if (!is_file($wbinfo)) { progress_logs(20, "{join_activedirectory_domain}", "Auth Winbindd, samba is not installed"); progress_logs(100, "{finish}", "Auth Winbindd, samba is not installed"); return; } if (!checkParams()) { progress_logs(20, "{join_activedirectory_domain} {failed}", "Auth Winbindd, misconfiguration failed"); progress_logs(100, "{finish}", "Auth Winbindd, misconfiguration failed"); return; } $unix = new unix(); $chmod = $unix->find_program("chmod"); $msktutil = check_msktutil(); $kdb5_util = $unix->find_program("kdb5_util"); $kadmin_bin = $unix->find_program("kadmin"); $netbin = $unix->LOCATE_NET_BIN_PATH(); if (!is_file($msktutil)) { return; } @mkdir("/var/log/samba", 0755, true); @mkdir("/var/run/samba", 0755, true); $uname = posix_uname(); $mydomain = $uname["domainname"]; $myFullHostname = $unix->hostname_g(); $myNetBiosName = $unix->hostname_simple(); $enctype = null; $sock = new sockets(); $array = unserialize(base64_decode($sock->GET_INFO("KerbAuthInfos"))); $hostname = strtolower(trim($array["WINDOWS_SERVER_NETBIOSNAME"])) . "." . strtolower(trim($array["WINDOWS_DNS_SUFFIX"])); $domainUp = strtoupper($array["WINDOWS_DNS_SUFFIX"]); $domaindow = strtolower($array["WINDOWS_DNS_SUFFIX"]); $kinitpassword = $array["WINDOWS_SERVER_PASS"]; $kinitpassword = $unix->shellEscapeChars($kinitpassword); $ipaddr = trim($array["ADNETIPADDR"]); $UseADAsNameServer = $sock->GET_INFO("UseADAsNameServer"); if (!is_numeric($UseADAsNameServer)) { $UseADAsNameServer = 0; } if ($UseADAsNameServer == 1) { if (preg_match("#[0-9\\.]+#", $ipaddr)) { progress_logs(8, "{apply_settings}", "Patching Resolv.conf"); PatchResolvConf($ipaddr); } } if ($ipaddr != null) { $ipaddrZ = explode(".", $ipaddr); while (list($num, $a) = each($ipaddrZ)) { $ipaddrZ[$num] = intval($a); } $ipaddr = @implode(".", $ipaddrZ); } progress_logs(9, "{apply_settings} Synchronize time", "Synchronize time" . " in line " . __LINE__); sync_time(); progress_logs(10, "{apply_settings} Check kerb5", "Check kerb5..in line " . __LINE__); if (!krb5conf(12)) { progress_logs(110, "{apply_settings} Check kerb5 {failed}", "Check kerb5..in line " . __LINE__); return; } progress_logs(15, "{apply_settings} Check mskt", "Check msktutils in line " . __LINE__); if (!run_msktutils()) { progress_logs(110, "{apply_settings} Check mskt {failed}", "Check mskt..in line " . __LINE__); return; } progress_logs(15, "{apply_settings} netbin", "netbin -> {$netbin} in line " . __LINE__); if (is_file($netbin)) { try { progress_logs(15, "{apply_settings} netbin", "netbin -> SAMBA_PROXY() in line " . __LINE__); SAMBA_PROXY(); } catch (Exception $e) { progress_logs(15, "{failed}", "Exception Error: Message: " . $e->getMessage()); } } progress_logs(19, "{apply_settings} [kadmin_bin]", $kadmin_bin); progress_logs(19, "{apply_settings} [netbin]", $netbin); if (is_file("{$netbin}")) { progress_logs(20, "{join_activedirectory_domain}", "netbin -> JOIN_ACTIVEDIRECTORY() "); JOIN_ACTIVEDIRECTORY(); // 29% } progress_logs(51, "{restarting_winbind} 1", "winbind_priv();"); winbind_priv(false, 52); progress_logs(60, "{restarting_winbind} 2", "winbind_priv();"); winbindd_monit(); progress_logs(65, "{restarting_winbind} 3", "winbind_priv();"); $php5 = $unix->LOCATE_PHP5_BIN(); if (!is_file("/etc/init.d/winbind")) { shell_exec("{$php5} /usr/share/artica-postfix/exec.initslapd.php --winbind"); } progress_logs(65, "{restarting_winbind}", "winbind_priv();"); system("/etc/init.d/winbind restart --force"); return true; }